我正在尝试使用Angular实现OAuth2身份验证:
login(name: string, password: string): Observable<any> {
const formData = new FormData();
formData.append('username', name);
formData.append('password', password);
formData.append('grant_type', 'password');
formData.append('scope', 'read');
const headers = new HttpHeaders({
Authorization: `Basic ${btoa(`${name}:${password}`)}`,
username: name,
password: password,
// 'Content-Type': 'multipart/form-data',
});
return this.httpClient
.post(`http://localhost:8080/engine/oauth/token`, formData, {
headers,
withCredentials: true,
})
.pipe(
map((response: Authorize) => {
sessionStorage.setItem('token', response.accessToken);
return true;
})
);
}
Github code
但是我总是出错:{"error":"invalid_request","error_description":"Missing grant type"}
有了邮递员,我可以成功请求:
但是使用Angular会出现此错误。你知道我该怎么解决吗?
答案 0 :(得分:0)
免责声明:it has been officially deprecated请避免花费高昂的“密码”流。但是,如果必须使用它,这是一种简单的方法:
// Please avoid "password" flow at all cost, it has been officially deprecated
// https://tools.ietf.org/html/draft-ietf-oauth-security-topics-15#section-2.4
// But, if you must use it, here's a simple way to do so:
async function getTokenResponse(clientId, identityServerUrl, username, password) {
const response = await fetch(identityServerUrl + "/connect/token", {
method: "POST",
headers: {
'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',
},
body: new URLSearchParams({
"grant_type": "password",
"client_id": clientId,
"username": username,
"password": password,
}),
});
const json = await response.json();
console.log(json); // json.access_token should contain the actual token
return JSON.stringify(json, null, 2);
}
此has worked for me至少与IdentityServer4。
主要区别在于,它使用了另一个is mandatory per RFC 6749或至少建议的模式Content-Type
(x-www-form-urlencoded
)。我不确定为什么您的邮递员屏幕截图仍然可以正常工作...