我正在使用keycloak和angular 5,我正在试图接受,我接受了keyxloak doc和heres te code:
getTokenKeyCloak() {
let headers = new HttpHeaders();
headers = headers.append('Content-Type','application/x-www-form-urlencoded');
let data = {
client_id :'admin-cli',
username :'**',
password :'**',
grant_type : 'password'
};
return this.http
.post("auth/realms/master/protocol/openid-connect/token",data, {headers:headers})
.map((res: Response) => {
alert('hello');
}).catch(this.handleError);
}
每次发送请求时,我收到此消息:
后端返回代码400,正文为:{“error”:“invalid_request”,“error_description”:“缺少表单参数:grant_type”}
答案 0 :(得分:1)
可能有点晚了,但也许有人还在寻找答案。
这有效:
login(username: string, password: string): Observable<any> {
const httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/x-www-form-urlencoded'
})};
const params = new HttpParams({
fromObject: {
grant_type: 'password',
client_id: 'myclient',
username: username,
password: password,
scope: 'openid'
}
});
return this.http.post('/auth/realms/<realm>/protocol/openid-connect/token', params, httpOptions)
.pipe(tap((response: any) => {
this.tokeninfo = jwtDecode(response.access_token);
}));
}
答案 1 :(得分:0)
尝试添加client_secret
。卷曲示例:
curl \
-d "client_id=myclient" \
-d "client_secret=40cc097b-2a57-4c17-b36a-8fdf3fc2d578" \
-d "username=user" \
-d "password=password" \
-d "grant_type=password" \
"http://localhost:8080/auth/realms/master/protocol/openid-connect/token"
Doc:http://www.keycloak.org/docs/3.2/securing_apps/topics/oidc/oidc-generic.html
但是在这种情况下会暴露client_secret
。所以这不是Angular的最佳选择。更好的选择是使用隐式流。 Angular的示例库:https://github.com/damienbod/angular-auth-oidc-client