几天前,我已将 keycloak 与我的 php 应用程序集成。哪个工作正常。现在我正在尝试为我的 vue js 应用程序做同样的事情。
在第二步(对于使用授权代码的客户端令牌请求)我收到 400 错误。响应消息“代码无效”。
第一步:(内部安装)
const AUTHORIZE_URL = 'auth/realms/rstore/protocol/openid-connect/auth';
const params = {
'response_type': 'code',
'redirect_uri': 'http://localhost:8080/sso/callback',
'client_id': client_id,
'nonce': uuid(),
'state': uuid(),
'scope': 'openid profile email'
};
window.location = baseUrl + AUTHORIZE_URL + '?' + queryString.stringify(params);
Run Code Online (Sandbox Code Playgroud)
第二步:(对于客户端令牌请求)
let url = baseUrl + ACCESS_TOKEN_URL;
let params = {
'grant_type': 'authorization_code',
'code': code,
'redirect_uri': 'http://localhost:8080/sso/callback',
'client_id': client_id,
'client_secret': client_secret
};
let result = fetch(url, {
method: 'POST',
body: queryString.stringify(params),
headers: {
'Content-Type': 'application/x-www-form-urlencoded' // ,
}
})
.then(resp => {
return resp.json();
})
.catch(error => {
throw new Error('FetchError in request to ES: ' + error.toString())
})
Run Code Online (Sandbox Code Playgroud)
我也从命令提示符尝试过 --->
curl -X POST 'https://example.com/auth/realms/nstore/protocol/openid-connect/token' \
--header 'Content-Type: application/x-www-form-urlencoded' \
--data-urlencode 'grant_type=authorization_code' \
--data-urlencode 'code=095516b7-e545-4b02-9dad-ec9c6366e0e4.33e1f298-a440-4bdc-9118-96ed669cabcd.e1c5d85f-3441-490d-a1fd-eb3b00d3c47c' \
--data-urlencode 'client_id=vue' \
--data-urlencode 'client_secret=b329ade3-2b71-4e3b-ab25-926cb32c5c8c' \
--data-urlencode 'redirect_uri=http://localhost:8080/sso/callback'
Run Code Online (Sandbox Code Playgroud)
输出相同 ---> {"error":"invalid_grant","error_description":"代码无效"}
Pra*_*dav 10
“代码无效”错误消息是一种常见错误消息。它可能具有以下含义之一: http://localhost:8080/auth/realms/{realm_name}/protocol/openid-connect/auth
每个授权代码只能使用一次,以生成单个新的访问令牌。因此,从一个代码生成多个访问令牌是不可能的。您可能收到此错误的原因之一是授权代码已被 Postman 或 Web 应用程序使用。
解决方案: 在您的领域的 keycloak 服务器中重新生成 client_secret,然后再次执行完整的过程,您将获得 accesstoken 和 Referesh 令牌。
注意:每个授权代码只能使用一次,以生成单个新的访问令牌。因此,从一个代码生成多个访问令牌是不可能的。