问题
I am using Spring cloud Gateway with Spring security and Keycloak for Access management. I am having an issue getting the access token with spring cloud gateway as the token I am getting doesn't have all the parameters like what I get from the token endpoint in keycloak.
When I hit the keycloak token endpoint with all the details:
http://localhost:8080/auth/realms/myrealm/protocol/openid-connect/token
{
"exp": 1595310135,
"iat": 1595309835,
"jti": "0a78d67c-878c-468c-8d03-e003af0350c3",
"iss": "http://localhost:8080/auth/realms/myrealm",
"aud": "account",
"sub": "5c3c71c8-4682-4cd8-8e28-ee66a7edea4e",
"typ": "Bearer",
"azp": "myclient",
"session_state": "af8acabc-b9fb-4d15-9160-b9c613007075",
"acr": "1",
"allowed-origins": [
"http://localhost:8080"
],
"realm_access": {
"roles": [
"offline_access",
"uma_authorization"
]
},
"resource_access": {
"account": {
"roles": [
"manage-account",
"manage-account-links",
"view-profile"
]
}
},
"scope": "profile email",
"email_verified": true,
"name": "Vijay 123",
"preferred_username": "vijay",
"given_name": "Vijay",
"family_name": "123"
}
But at the same time when I try to get the same token from my Spring Cloud Gateway Configuration I get following token:
{
"exp": 1595244254,
"iat": 1595243954,
"auth_time": 1595243954,
"jti": "6d76736d-51d4-4ae7-9c15-55fc2cf9d96a",
"iss": "http://localhost:8080/auth/realms/myrealm",
"aud": "myclient",
"sub": "5c3c71c8-4682-4cd8-8e28-ee66a7edea4e",
"typ": "ID",
"azp": "myclient",
"session_state": "dfbeb8a3-5d8e-4750-b8af-3dd00105cafa",
"acr": "1",
"upn": "vijay",
"email_verified": true,
"address": {},
"name": "Vijay 123",
"groups": [
"offline_access",
"uma_authorization"
],
"preferred_username": "vijay",
"given_name": "Vijay",
"family_name": "123"
}
Below are the configuration I have used:
@Bean
public GlobalFilter customGlobalFilter() {
return (exchange, chain) -> exchange.getPrincipal().map(principal -> {
String token = "";
String session = "";
if (principal instanceof OAuth2AuthenticationToken) {
// For Getting token from request
SecurityContextImpl context =
exchange.getSession().block().getAttribute("SPRING_SECURITY_CONTEXT");
DefaultOidcUser principal1 = (DefaultOidcUser) context.getAuthentication().getPrincipal();
token = principal1.getIdToken().getTokenValue();
}
}
The token value does not match the token value from keycloak.
Is there any other way of getting the OIDC token from the request instead of the OAuth2 token?
I could see the principle is of type OAuth2AuthenticationToken.
来源:https://stackoverflow.com/questions/63020779/getting-access-token-with-spring-cloud-gateway-and-spring-security-with-keycloak