Search in sources :

Example 66 with AccessToken

use of org.keycloak.representations.AccessToken in project keycloak by keycloak.

the class OIDCScopeTest method testTwoRefreshTokensWithDifferentScopes.

// KEYCLOAK-6170
@Test
public void testTwoRefreshTokensWithDifferentScopes() {
    // Add 2 client scopes. Each with scope to 1 realm role
    ClientScopeRepresentation clientScope1 = new ClientScopeRepresentation();
    clientScope1.setName("scope-role-1");
    clientScope1.setProtocol(OIDCLoginProtocol.LOGIN_PROTOCOL);
    Response response = testRealm().clientScopes().create(clientScope1);
    String scope1Id = ApiUtil.getCreatedId(response);
    getCleanup().addClientScopeId(scope1Id);
    response.close();
    ClientScopeRepresentation clientScope2 = new ClientScopeRepresentation();
    clientScope2.setName("scope-role-2");
    clientScope2.setProtocol(OIDCLoginProtocol.LOGIN_PROTOCOL);
    response = testRealm().clientScopes().create(clientScope2);
    String scope2Id = ApiUtil.getCreatedId(response);
    getCleanup().addClientScopeId(scope2Id);
    response.close();
    RoleRepresentation role1 = testRealm().roles().get("role-1").toRepresentation();
    testRealm().clientScopes().get(scope1Id).getScopeMappings().realmLevel().add(Arrays.asList(role1));
    RoleRepresentation role2 = testRealm().roles().get("role-2").toRepresentation();
    testRealm().clientScopes().get(scope2Id).getScopeMappings().realmLevel().add(Arrays.asList(role2));
    // Add client scopes to our client. Disable fullScopeAllowed
    ClientResource testApp = ApiUtil.findClientByClientId(testRealm(), "test-app");
    ClientRepresentation testAppRep = testApp.toRepresentation();
    testAppRep.setFullScopeAllowed(false);
    testApp.update(testAppRep);
    testApp.addOptionalClientScope(scope1Id);
    testApp.addOptionalClientScope(scope2Id);
    // Login with scope-role-1. Save refresh token
    oauth.scope("scope-role-1");
    oauth.doLogin("john", "password");
    EventRepresentation loginEvent = events.expectLogin().user(userId).assertEvent();
    Tokens tokens1 = sendTokenRequest(loginEvent, userId, "openid email profile scope-role-1", "test-app");
    Assert.assertTrue(tokens1.accessToken.getRealmAccess().isUserInRole("role-1"));
    Assert.assertFalse(tokens1.accessToken.getRealmAccess().isUserInRole("role-2"));
    // SSO login with scope-role-2. Save refresh token
    oauth.scope("scope-role-2");
    oauth.openLoginForm();
    loginEvent = events.expectLogin().user(userId).removeDetail(Details.USERNAME).client("test-app").assertEvent();
    Tokens tokens2 = sendTokenRequest(loginEvent, userId, "openid email profile scope-role-2", "test-app");
    Assert.assertFalse(tokens2.accessToken.getRealmAccess().isUserInRole("role-1"));
    Assert.assertTrue(tokens2.accessToken.getRealmAccess().isUserInRole("role-2"));
    // Ensure I can refresh refreshToken1. Just role1 is present
    OAuthClient.AccessTokenResponse refreshResponse1 = oauth.doRefreshTokenRequest(tokens1.refreshToken, "password");
    Assert.assertEquals(200, refreshResponse1.getStatusCode());
    AccessToken accessToken1 = oauth.verifyToken(refreshResponse1.getAccessToken());
    Assert.assertTrue(accessToken1.getRealmAccess().isUserInRole("role-1"));
    Assert.assertFalse(accessToken1.getRealmAccess().isUserInRole("role-2"));
    // Ensure I can refresh refreshToken2. Just role2 is present
    OAuthClient.AccessTokenResponse refreshResponse2 = oauth.doRefreshTokenRequest(tokens2.refreshToken, "password");
    Assert.assertEquals(200, refreshResponse2.getStatusCode());
    AccessToken accessToken2 = oauth.verifyToken(refreshResponse2.getAccessToken());
    Assert.assertFalse(accessToken2.getRealmAccess().isUserInRole("role-1"));
    Assert.assertTrue(accessToken2.getRealmAccess().isUserInRole("role-2"));
    // Revert
    testAppRep.setFullScopeAllowed(true);
    testApp.update(testAppRep);
    testApp.removeOptionalClientScope(scope1Id);
    testApp.removeOptionalClientScope(scope2Id);
}
Also used : Response(javax.ws.rs.core.Response) RoleRepresentation(org.keycloak.representations.idm.RoleRepresentation) OAuthClient(org.keycloak.testsuite.util.OAuthClient) AccessToken(org.keycloak.representations.AccessToken) ClientScopeRepresentation(org.keycloak.representations.idm.ClientScopeRepresentation) EventRepresentation(org.keycloak.representations.idm.EventRepresentation) ClientResource(org.keycloak.admin.client.resource.ClientResource) ClientRepresentation(org.keycloak.representations.idm.ClientRepresentation) Test(org.junit.Test)

Example 67 with AccessToken

use of org.keycloak.representations.AccessToken in project keycloak by keycloak.

the class OpenShiftTokenReviewEndpoint method tokenReview.

@Path("/{client_id}")
@POST
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Response tokenReview(@PathParam("client_id") String clientId, OpenShiftTokenReviewRequestRepresentation reviewRequest) throws Exception {
    event.event(EventType.INTROSPECT_TOKEN);
    if (clientId != null) {
        session.setAttribute("client_id", clientId);
    }
    checkSsl();
    checkRealm();
    authorizeClient();
    RealmModel realm = session.getContext().getRealm();
    AccessToken token = null;
    try {
        TokenVerifier<AccessToken> verifier = TokenVerifier.create(reviewRequest.getSpec().getToken(), AccessToken.class).realmUrl(Urls.realmIssuer(session.getContext().getUri().getBaseUri(), realm.getName())).audience(reviewRequest.getSpec().getAudiences());
        SignatureVerifierContext verifierContext = session.getProvider(SignatureProvider.class, verifier.getHeader().getAlgorithm().name()).verifier(verifier.getHeader().getKeyId());
        verifier.verifierContext(verifierContext);
        verifier.verify();
        token = verifier.getToken();
    } catch (VerificationException e) {
        error(401, Errors.INVALID_TOKEN, "Token verification failure");
    }
    if (!tokenManager.checkTokenValidForIntrospection(session, realm, token, true)) {
        error(401, Errors.INVALID_TOKEN, "Token verification failure");
    }
    OpenShiftTokenReviewResponseRepresentation response = new OpenShiftTokenReviewResponseRepresentation();
    response.getStatus().setAuthenticated(true);
    response.getStatus().setUser(new OpenShiftTokenReviewResponseRepresentation.User());
    OpenShiftTokenReviewResponseRepresentation.User userRep = response.getStatus().getUser();
    userRep.setUid(token.getSubject());
    userRep.setUsername(token.getPreferredUsername());
    if (token.getScope() != null && !token.getScope().isEmpty()) {
        OpenShiftTokenReviewResponseRepresentation.Extra extra = new OpenShiftTokenReviewResponseRepresentation.Extra();
        extra.setScopes(token.getScope().split(" "));
        userRep.setExtra(extra);
    }
    if (token.getOtherClaims() != null && token.getOtherClaims().get("groups") != null) {
        List<String> groups = (List<String>) token.getOtherClaims().get("groups");
        userRep.setGroups(groups);
    }
    event.success();
    return Response.ok(response, MediaType.APPLICATION_JSON).build();
}
Also used : SignatureVerifierContext(org.keycloak.crypto.SignatureVerifierContext) RealmModel(org.keycloak.models.RealmModel) SignatureProvider(org.keycloak.crypto.SignatureProvider) AccessToken(org.keycloak.representations.AccessToken) VerificationException(org.keycloak.common.VerificationException) List(java.util.List) Path(javax.ws.rs.Path) POST(javax.ws.rs.POST) Consumes(javax.ws.rs.Consumes) Produces(javax.ws.rs.Produces)

Example 68 with AccessToken

use of org.keycloak.representations.AccessToken in project keycloak by keycloak.

the class RoleResolveUtil method addToToken.

private static void addToToken(AccessToken token, RoleModel role) {
    AccessToken.Access access = null;
    if (role.getContainer() instanceof RealmModel) {
        access = token.getRealmAccess();
        if (token.getRealmAccess() == null) {
            access = new AccessToken.Access();
            token.setRealmAccess(access);
        } else if (token.getRealmAccess().getRoles() != null && token.getRealmAccess().isUserInRole(role.getName()))
            return;
    } else {
        ClientModel app = (ClientModel) role.getContainer();
        access = token.getResourceAccess(app.getClientId());
        if (access == null) {
            access = token.addAccess(app.getClientId());
            if (app.isSurrogateAuthRequired())
                access.verifyCaller(true);
        } else if (access.isUserInRole(role.getName()))
            return;
    }
    access.addRole(role.getName());
}
Also used : RealmModel(org.keycloak.models.RealmModel) ClientModel(org.keycloak.models.ClientModel) AccessToken(org.keycloak.representations.AccessToken)

Example 69 with AccessToken

use of org.keycloak.representations.AccessToken in project keycloak by keycloak.

the class RoleResolveUtil method getAndCacheResolvedRoles.

private static AccessToken getAndCacheResolvedRoles(KeycloakSession session, ClientSessionContext clientSessionCtx) {
    ClientModel client = clientSessionCtx.getClientSession().getClient();
    String resolvedRolesAttrName = RESOLVED_ROLES_ATTR + ":" + clientSessionCtx.getClientSession().getUserSession().getId() + ":" + client.getId();
    AccessToken token = session.getAttribute(resolvedRolesAttrName, AccessToken.class);
    if (token == null) {
        AccessToken finalToken = new AccessToken();
        clientSessionCtx.getRolesStream().forEach(role -> addToToken(finalToken, role));
        token = finalToken;
        session.setAttribute(resolvedRolesAttrName, token);
    }
    return token;
}
Also used : ClientModel(org.keycloak.models.ClientModel) AccessToken(org.keycloak.representations.AccessToken)

Example 70 with AccessToken

use of org.keycloak.representations.AccessToken in project keycloak by keycloak.

the class RoleResolveUtil method getResolvedRealmRoles.

/**
 * Object (possibly null) containing all the user's realm roles. Including user's groups roles. Composite roles are expanded.
 * Just the roles, which current client has role-scope-mapping for (or it's clientScopes) are included.
 * Current client means the client corresponding to specified clientSessionCtx.
 *
 * @param session
 * @param clientSessionCtx
 * @param createIfMissing
 * @return can return null (just in case that createIfMissing is false)
 */
public static AccessToken.Access getResolvedRealmRoles(KeycloakSession session, ClientSessionContext clientSessionCtx, boolean createIfMissing) {
    AccessToken rolesToken = getAndCacheResolvedRoles(session, clientSessionCtx);
    AccessToken.Access access = rolesToken.getRealmAccess();
    if (access == null && createIfMissing) {
        access = new AccessToken.Access();
        rolesToken.setRealmAccess(access);
    }
    return access;
}
Also used : AccessToken(org.keycloak.representations.AccessToken)

Aggregations

AccessToken (org.keycloak.representations.AccessToken)230 Test (org.junit.Test)129 OAuthClient (org.keycloak.testsuite.util.OAuthClient)104 AbstractKeycloakTest (org.keycloak.testsuite.AbstractKeycloakTest)54 RefreshToken (org.keycloak.representations.RefreshToken)45 AuthorizationResponse (org.keycloak.representations.idm.authorization.AuthorizationResponse)37 JWSInput (org.keycloak.jose.jws.JWSInput)29 Permission (org.keycloak.representations.idm.authorization.Permission)28 EventRepresentation (org.keycloak.representations.idm.EventRepresentation)27 Response (javax.ws.rs.core.Response)26 ClientResource (org.keycloak.admin.client.resource.ClientResource)22 VerificationException (org.keycloak.common.VerificationException)19 ClientRepresentation (org.keycloak.representations.idm.ClientRepresentation)19 AccessTokenResponse (org.keycloak.representations.AccessTokenResponse)18 IDToken (org.keycloak.representations.IDToken)18 AuthorizationRequest (org.keycloak.representations.idm.authorization.AuthorizationRequest)17 IOException (java.io.IOException)15 AuthzClient (org.keycloak.authorization.client.AuthzClient)15 ResourceRepresentation (org.keycloak.representations.idm.authorization.ResourceRepresentation)14 ArrayList (java.util.ArrayList)13