use of org.keycloak.representations.AccessTokenResponse in project keycloak by keycloak.
the class AbstractOAuth2IdentityProvider method hasExternalExchangeToken.
/**
* check to see if we have a token exchange in session
* in other words check to see if this session was created by an external exchange
* @param tokenUserSession
* @param params
* @return
*/
protected Response hasExternalExchangeToken(EventBuilder event, UserSessionModel tokenUserSession, MultivaluedMap<String, String> params) {
if (getConfig().getAlias().equals(tokenUserSession.getNote(OIDCIdentityProvider.EXCHANGE_PROVIDER))) {
String requestedType = params.getFirst(OAuth2Constants.REQUESTED_TOKEN_TYPE);
if ((requestedType == null || requestedType.equals(OAuth2Constants.ACCESS_TOKEN_TYPE))) {
String accessToken = tokenUserSession.getNote(FEDERATED_ACCESS_TOKEN);
if (accessToken != null) {
AccessTokenResponse tokenResponse = new AccessTokenResponse();
tokenResponse.setToken(accessToken);
tokenResponse.setIdToken(null);
tokenResponse.setRefreshToken(null);
tokenResponse.setRefreshExpiresIn(0);
tokenResponse.setExpiresIn(0);
tokenResponse.getOtherClaims().clear();
tokenResponse.getOtherClaims().put(OAuth2Constants.ISSUED_TOKEN_TYPE, OAuth2Constants.ACCESS_TOKEN_TYPE);
event.success();
return Response.ok(tokenResponse).type(MediaType.APPLICATION_JSON_TYPE).build();
}
} else if (OAuth2Constants.ID_TOKEN_TYPE.equals(requestedType)) {
String idToken = tokenUserSession.getNote(OIDCIdentityProvider.FEDERATED_ID_TOKEN);
if (idToken != null) {
AccessTokenResponse tokenResponse = new AccessTokenResponse();
tokenResponse.setToken(null);
tokenResponse.setIdToken(idToken);
tokenResponse.setRefreshToken(null);
tokenResponse.setRefreshExpiresIn(0);
tokenResponse.setExpiresIn(0);
tokenResponse.getOtherClaims().clear();
tokenResponse.getOtherClaims().put(OAuth2Constants.ISSUED_TOKEN_TYPE, OAuth2Constants.ID_TOKEN_TYPE);
event.success();
return Response.ok(tokenResponse).type(MediaType.APPLICATION_JSON_TYPE).build();
}
}
}
return null;
}
use of org.keycloak.representations.AccessTokenResponse in project keycloak by keycloak.
the class OIDCIdentityProvider method exchangeSessionToken.
@Override
protected Response exchangeSessionToken(UriInfo uriInfo, EventBuilder event, ClientModel authorizedClient, UserSessionModel tokenUserSession, UserModel tokenSubject) {
String refreshToken = tokenUserSession.getNote(FEDERATED_REFRESH_TOKEN);
String accessToken = tokenUserSession.getNote(FEDERATED_ACCESS_TOKEN);
String idToken = tokenUserSession.getNote(FEDERATED_ID_TOKEN);
if (accessToken == null) {
event.detail(Details.REASON, "requested_issuer is not linked");
event.error(Errors.INVALID_TOKEN);
return exchangeTokenExpired(uriInfo, authorizedClient, tokenUserSession, tokenSubject);
}
try (VaultStringSecret vaultStringSecret = session.vault().getStringSecret(getConfig().getClientSecret())) {
long expiration = Long.parseLong(tokenUserSession.getNote(FEDERATED_TOKEN_EXPIRATION));
if (expiration == 0 || expiration > Time.currentTime()) {
AccessTokenResponse tokenResponse = new AccessTokenResponse();
tokenResponse.setExpiresIn(expiration);
tokenResponse.setToken(accessToken);
tokenResponse.setIdToken(null);
tokenResponse.setRefreshToken(null);
tokenResponse.setRefreshExpiresIn(0);
tokenResponse.getOtherClaims().put(OAuth2Constants.ISSUED_TOKEN_TYPE, OAuth2Constants.ACCESS_TOKEN_TYPE);
tokenResponse.getOtherClaims().put(ACCOUNT_LINK_URL, getLinkingUrl(uriInfo, authorizedClient, tokenUserSession));
event.success();
return Response.ok(tokenResponse).type(MediaType.APPLICATION_JSON_TYPE).build();
}
String response = getRefreshTokenRequest(session, refreshToken, getConfig().getClientId(), vaultStringSecret.get().orElse(getConfig().getClientSecret())).asString();
if (response.contains("error")) {
logger.debugv("Error refreshing token, refresh token expiration?: {0}", response);
event.detail(Details.REASON, "requested_issuer token expired");
event.error(Errors.INVALID_TOKEN);
return exchangeTokenExpired(uriInfo, authorizedClient, tokenUserSession, tokenSubject);
}
AccessTokenResponse newResponse = JsonSerialization.readValue(response, AccessTokenResponse.class);
long accessTokenExpiration = newResponse.getExpiresIn() > 0 ? Time.currentTime() + newResponse.getExpiresIn() : 0;
tokenUserSession.setNote(FEDERATED_TOKEN_EXPIRATION, Long.toString(accessTokenExpiration));
tokenUserSession.setNote(FEDERATED_REFRESH_TOKEN, newResponse.getRefreshToken());
tokenUserSession.setNote(FEDERATED_ACCESS_TOKEN, newResponse.getToken());
tokenUserSession.setNote(FEDERATED_ID_TOKEN, newResponse.getIdToken());
newResponse.setIdToken(null);
newResponse.setRefreshToken(null);
newResponse.setRefreshExpiresIn(0);
newResponse.getOtherClaims().clear();
newResponse.getOtherClaims().put(OAuth2Constants.ISSUED_TOKEN_TYPE, OAuth2Constants.ACCESS_TOKEN_TYPE);
newResponse.getOtherClaims().put(ACCOUNT_LINK_URL, getLinkingUrl(uriInfo, authorizedClient, tokenUserSession));
event.success();
return Response.ok(newResponse).type(MediaType.APPLICATION_JSON_TYPE).build();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
use of org.keycloak.representations.AccessTokenResponse in project keycloak by keycloak.
the class OIDCIdentityProvider method authenticationFinished.
@Override
public void authenticationFinished(AuthenticationSessionModel authSession, BrokeredIdentityContext context) {
AccessTokenResponse tokenResponse = (AccessTokenResponse) context.getContextData().get(FEDERATED_ACCESS_TOKEN_RESPONSE);
int currentTime = Time.currentTime();
long expiration = tokenResponse.getExpiresIn() > 0 ? tokenResponse.getExpiresIn() + currentTime : 0;
authSession.setUserSessionNote(FEDERATED_TOKEN_EXPIRATION, Long.toString(expiration));
authSession.setUserSessionNote(FEDERATED_REFRESH_TOKEN, tokenResponse.getRefreshToken());
authSession.setUserSessionNote(FEDERATED_ACCESS_TOKEN, tokenResponse.getToken());
authSession.setUserSessionNote(FEDERATED_ID_TOKEN, tokenResponse.getIdToken());
}
use of org.keycloak.representations.AccessTokenResponse in project keycloak by keycloak.
the class EntitlementAPITest method testUsingExpiredToken.
@Test
public void testUsingExpiredToken() throws Exception {
ClientResource client = getClient(getRealm(), RESOURCE_SERVER_TEST);
AuthorizationResource authorization = client.authorization();
JSPolicyRepresentation policy = new JSPolicyRepresentation();
policy.setName(KeycloakModelUtils.generateId());
policy.setCode("$evaluation.grant();");
authorization.policies().js().create(policy).close();
ResourceRepresentation resource = new ResourceRepresentation();
resource.setName("Sensors");
try (Response response = authorization.resources().create(resource)) {
resource = response.readEntity(ResourceRepresentation.class);
}
ResourcePermissionRepresentation permission = new ResourcePermissionRepresentation();
permission.setName("View Sensor");
permission.addPolicy(policy.getName());
authorization.permissions().resource().create(permission).close();
String accessToken = new OAuthClient().realm("authz-test").clientId(RESOURCE_SERVER_TEST).doGrantAccessTokenRequest("secret", "marta", "password").getAccessToken();
AuthzClient authzClient = getAuthzClient(AUTHZ_CLIENT_CONFIG);
AccessTokenResponse response = authzClient.authorization(accessToken).authorize();
assertNotNull(response.getToken());
getRealm().logoutAll();
AuthorizationRequest request = new AuthorizationRequest();
request.addPermission("Sensors");
request.setSubjectToken(accessToken);
try {
authzClient.authorization().authorize(request);
fail("should fail, session invalidated");
} catch (Exception e) {
Throwable expected = e.getCause();
assertEquals(400, HttpResponseException.class.cast(expected).getStatusCode());
assertTrue(HttpResponseException.class.cast(expected).toString().contains("unauthorized_client"));
}
}
use of org.keycloak.representations.AccessTokenResponse in project keycloak by keycloak.
the class UmaGrantTypeTest method testRefreshRpt.
@Test
public void testRefreshRpt() {
AccessTokenResponse accessTokenResponse = getAuthzClient().obtainAccessToken("marta", "password");
AuthorizationResponse response = authorize(null, null, null, null, accessTokenResponse.getToken(), null, null, new PermissionRequest("Resource A", "ScopeA", "ScopeB"));
String rpt = response.getToken();
assertNotNull(rpt);
AccessToken accessToken = toAccessToken(rpt);
AccessToken.Authorization authorization = accessToken.getAuthorization();
assertNotNull(authorization);
Collection<Permission> permissions = authorization.getPermissions();
assertNotNull(permissions);
assertPermissions(permissions, "Resource A", "ScopeA", "ScopeB");
assertTrue(permissions.isEmpty());
String refreshToken = response.getRefreshToken();
assertNotNull(refreshToken);
AccessToken refreshTokenToken = toAccessToken(refreshToken);
assertNotNull(refreshTokenToken.getAuthorization());
Client client = AdminClientUtil.createResteasyClient();
UriBuilder builder = UriBuilder.fromUri(AUTH_SERVER_ROOT);
URI uri = OIDCLoginProtocolService.tokenUrl(builder).build(REALM_NAME);
WebTarget target = client.target(uri);
Form parameters = new Form();
parameters.param("grant_type", OAuth2Constants.REFRESH_TOKEN);
parameters.param(OAuth2Constants.REFRESH_TOKEN, refreshToken);
AccessTokenResponse refreshTokenResponse = target.request().header(HttpHeaders.AUTHORIZATION, BasicAuthHelper.createHeader("resource-server-test", "secret")).post(Entity.form(parameters)).readEntity(AccessTokenResponse.class);
assertNotNull(refreshTokenResponse.getToken());
refreshToken = refreshTokenResponse.getRefreshToken();
refreshTokenToken = toAccessToken(refreshToken);
assertNotNull(refreshTokenToken.getAuthorization());
AccessToken refreshedToken = toAccessToken(rpt);
authorization = refreshedToken.getAuthorization();
assertNotNull(authorization);
permissions = authorization.getPermissions();
assertNotNull(permissions);
assertPermissions(permissions, "Resource A", "ScopeA", "ScopeB");
assertTrue(permissions.isEmpty());
refreshTokenResponse = target.request().header(HttpHeaders.AUTHORIZATION, BasicAuthHelper.createHeader("resource-server-test", "secret")).post(Entity.form(parameters)).readEntity(AccessTokenResponse.class);
assertNotNull(refreshTokenResponse.getToken());
refreshToken = refreshTokenResponse.getRefreshToken();
refreshTokenToken = toAccessToken(refreshToken);
assertNotNull(refreshTokenToken.getAuthorization());
refreshedToken = toAccessToken(rpt);
authorization = refreshedToken.getAuthorization();
assertNotNull(authorization);
permissions = authorization.getPermissions();
assertNotNull(permissions);
assertPermissions(permissions, "Resource A", "ScopeA", "ScopeB");
assertTrue(permissions.isEmpty());
}
Aggregations