当我通过Angular调用api时,我得到了这个错误。然而,当我通过Postman调用它时,我得到了期望的响应。我不知道我做错了什么。下面是我使用的代码:
generateToken() {
let serverUIUri: string;
const sessionState = sessionStorage.getItem('state');
if (sessionState === undefined || sessionState !== this.state) {
this.router.navigate(['/account/login']);
} else {
this.userService.tokenGeneration("SSO", 'authorization_code', 'http://localhost:4200', this.code).subscribe((response: any) => {
sessionStorage.setItem('demo_cookiee', response.accessToken);
this.router.navigate(['/']);
}, error => {
this.continueToAppSelection();
//this.router.navigate(['/account/login']);
});
}
}
tokenGeneration(clientId: any, authorizationCode: any, redirectUri: any, code: any): Observable<any> {
const options = {
headers: new HttpHeaders()
.append('Content-Type', 'application/x-www-form-urlencoded'),
withCredentials: true,
origin: 'http://localhost:4200/',
referer: 'http://localhost:4200/'
};
const body = {
grant_type: authorizationCode,
redirect_uri: redirectUri,
client_id: clientId,
code: code
}
return this.demohttp.postData(this.url + 'connect/token', options, body);
}
postData(url: string, headers: any, body: any): Observable<any> {
return this.http.post(url, body, headers);
}
我也将Body和Header中相同的参数传递给postman。在这里,它成功地获得了响应。然而,通过代码,它给出了以下错误:
Object {error: "invalid_request", error_description: "The mandatory 'grant_type' parameter is missing."}
我传递grant_type作为'authorization_code',它仍然给出了错误。知道我哪里做错了吗?
当使用application/x-www-form-urlencoded内容类型时,client_secret, client_id和grant_type应该在body的x-www-form-urlencoded部分设置
我假设您正在使用某种形式的OIDC/OAuth2服务。如果你看一下这里的规范,参数必须使用FormData发布,而不是作为请求的主体。
可能这就是区别。
猜它应该看起来像这样(没有测试,从我的头顶-参考现有的SO问题/教程,如果它失败)。
tokenGeneration(clientId: any, authorizationCode: any, redirectUri: any, code: any): Observable<any> {
const options = {
headers: new HttpHeaders()
.append('Content-Type', 'application/x-www-form-urlencoded'),
withCredentials: true,
origin: 'http://localhost:4200/',
referer: 'http://localhost:4200/'
};
const form = new FormData();
form.append('grant_type', authorizationCode);
form.append('redirect_uri', redirectUri);
form.append('client_id', clientId);
form.append('code', code);
return this.demohttp.postData(this.url + 'connect/token', form, options);
}
我纠正了这个问题,由于我得到错误,body对象被正确创建强制性的'grant_type'参数缺失. 然而,在修复了body对象之后,它运行得非常好。
tokenGeneration(clientId: any, authorizationCode: any, redirectUri: any, code: any): Observable<any> {
const options = {
headers: new HttpHeaders()
.append('Content-Type', 'application/x-www-form-urlencoded'),
withCredentials: true
};
const body = 'grant_type=' + authorizationCode + '&redirect_uri=' + redirectUri + '&client_id=' + clientId + '&code=' + code;
return this.demoHttp.postDataWithOptions(this.ssoUrl + 'connect/token',options, body);
}