Search in sources :

Example 41 with AuthorizationResponse

use of org.keycloak.representations.idm.authorization.AuthorizationResponse in project keycloak by keycloak.

the class AuthorizationTokenService method createAuthorizationResponse.

private AuthorizationResponse createAuthorizationResponse(KeycloakIdentity identity, Collection<Permission> entitlements, KeycloakAuthorizationRequest request, ClientModel targetClient) {
    KeycloakSession keycloakSession = request.getKeycloakSession();
    AccessToken accessToken = identity.getAccessToken();
    RealmModel realm = request.getRealm();
    UserSessionProvider sessions = keycloakSession.sessions();
    UserSessionModel userSessionModel;
    if (accessToken.getSessionState() == null) {
        // Create temporary (request-scoped) transient session
        UserModel user = TokenManager.lookupUserFromStatelessToken(keycloakSession, realm, accessToken);
        userSessionModel = sessions.createUserSession(KeycloakModelUtils.generateId(), realm, user, user.getUsername(), request.getClientConnection().getRemoteAddr(), ServiceAccountConstants.CLIENT_AUTH, false, null, null, UserSessionModel.SessionPersistenceState.TRANSIENT);
    } else {
        userSessionModel = sessions.getUserSession(realm, accessToken.getSessionState());
        if (userSessionModel == null) {
            userSessionModel = sessions.getOfflineUserSession(realm, accessToken.getSessionState());
        }
    }
    ClientModel client = realm.getClientByClientId(accessToken.getIssuedFor());
    AuthenticatedClientSessionModel clientSession = userSessionModel.getAuthenticatedClientSessionByClient(targetClient.getId());
    ClientSessionContext clientSessionCtx;
    if (clientSession == null) {
        RootAuthenticationSessionModel rootAuthSession = keycloakSession.authenticationSessions().getRootAuthenticationSession(realm, userSessionModel.getId());
        if (rootAuthSession == null) {
            if (userSessionModel.getUser().getServiceAccountClientLink() == null) {
                rootAuthSession = keycloakSession.authenticationSessions().createRootAuthenticationSession(realm, userSessionModel.getId());
            } else {
                // if the user session is associated with a service account
                rootAuthSession = new AuthenticationSessionManager(keycloakSession).createAuthenticationSession(realm, false);
            }
        }
        AuthenticationSessionModel authSession = rootAuthSession.createAuthenticationSession(targetClient);
        authSession.setAuthenticatedUser(userSessionModel.getUser());
        authSession.setProtocol(OIDCLoginProtocol.LOGIN_PROTOCOL);
        authSession.setClientNote(OIDCLoginProtocol.ISSUER, Urls.realmIssuer(keycloakSession.getContext().getUri().getBaseUri(), realm.getName()));
        AuthenticationManager.setClientScopesInSession(authSession);
        clientSessionCtx = TokenManager.attachAuthenticationSession(keycloakSession, userSessionModel, authSession);
    } else {
        clientSessionCtx = DefaultClientSessionContext.fromClientSessionScopeParameter(clientSession, keycloakSession);
    }
    TokenManager tokenManager = request.getTokenManager();
    EventBuilder event = request.getEvent();
    AccessTokenResponseBuilder responseBuilder = tokenManager.responseBuilder(realm, client, event, keycloakSession, userSessionModel, clientSessionCtx).generateAccessToken();
    AccessToken rpt = responseBuilder.getAccessToken();
    Authorization authorization = new Authorization();
    authorization.setPermissions(entitlements);
    rpt.setAuthorization(authorization);
    if (accessToken.getSessionState() == null) {
        // Skip generating refresh token for accessToken without sessionState claim. This is "stateless" accessToken not pointing to any real persistent userSession
        rpt.setSessionState(null);
    } else {
        if (OIDCAdvancedConfigWrapper.fromClientModel(client).isUseRefreshToken()) {
            responseBuilder.generateRefreshToken();
            RefreshToken refreshToken = responseBuilder.getRefreshToken();
            refreshToken.issuedFor(client.getClientId());
            refreshToken.setAuthorization(authorization);
        }
    }
    if (!rpt.hasAudience(targetClient.getClientId())) {
        rpt.audience(targetClient.getClientId());
    }
    return new AuthorizationResponse(responseBuilder.build(), isUpgraded(request, authorization));
}
Also used : UserSessionModel(org.keycloak.models.UserSessionModel) AuthenticationSessionModel(org.keycloak.sessions.AuthenticationSessionModel) RootAuthenticationSessionModel(org.keycloak.sessions.RootAuthenticationSessionModel) AuthenticatedClientSessionModel(org.keycloak.models.AuthenticatedClientSessionModel) AuthorizationResponse(org.keycloak.representations.idm.authorization.AuthorizationResponse) RealmModel(org.keycloak.models.RealmModel) UserModel(org.keycloak.models.UserModel) AuthenticationSessionManager(org.keycloak.services.managers.AuthenticationSessionManager) Authorization(org.keycloak.representations.AccessToken.Authorization) UserSessionProvider(org.keycloak.models.UserSessionProvider) ClientModel(org.keycloak.models.ClientModel) EventBuilder(org.keycloak.events.EventBuilder) RefreshToken(org.keycloak.representations.RefreshToken) DefaultClientSessionContext(org.keycloak.services.util.DefaultClientSessionContext) ClientSessionContext(org.keycloak.models.ClientSessionContext) AccessToken(org.keycloak.representations.AccessToken) KeycloakSession(org.keycloak.models.KeycloakSession) RootAuthenticationSessionModel(org.keycloak.sessions.RootAuthenticationSessionModel) AccessTokenResponseBuilder(org.keycloak.protocol.oidc.TokenManager.AccessTokenResponseBuilder) TokenManager(org.keycloak.protocol.oidc.TokenManager)

Example 42 with AuthorizationResponse

use of org.keycloak.representations.idm.authorization.AuthorizationResponse in project keycloak by keycloak.

the class ConflictingScopePermissionTest method getEntitlements.

private Collection<Permission> getEntitlements(String username, String password) {
    AuthzClient authzClient = getAuthzClient();
    AuthorizationResponse response = authzClient.authorization(username, password).authorize();
    AccessToken accessToken;
    try {
        accessToken = new JWSInput(response.getToken()).readJsonContent(AccessToken.class);
    } catch (JWSInputException cause) {
        throw new RuntimeException("Failed to deserialize RPT", cause);
    }
    AccessToken.Authorization authorization = accessToken.getAuthorization();
    assertNotNull("RPT does not contain any authorization data", authorization);
    return authorization.getPermissions();
}
Also used : AuthzClient(org.keycloak.authorization.client.AuthzClient) AccessToken(org.keycloak.representations.AccessToken) JWSInputException(org.keycloak.jose.jws.JWSInputException) JWSInput(org.keycloak.jose.jws.JWSInput) AuthorizationResponse(org.keycloak.representations.idm.authorization.AuthorizationResponse)

Example 43 with AuthorizationResponse

use of org.keycloak.representations.idm.authorization.AuthorizationResponse in project keycloak by keycloak.

the class UserManagedPermissionServiceTest method testUserManagedPermission.

@Test
public void testUserManagedPermission() {
    ResourceRepresentation resource = new ResourceRepresentation();
    resource.setName("Resource A");
    resource.setOwnerManagedAccess(true);
    resource.setOwner("marta");
    resource.addScope("Scope A", "Scope B", "Scope C");
    resource = getAuthzClient().protection().resource().create(resource);
    UmaPermissionRepresentation permission = new UmaPermissionRepresentation();
    permission.setName("Custom User-Managed Permission");
    permission.setDescription("Users from specific roles are allowed to access");
    permission.addScope("Scope A");
    permission.addRole("role_a");
    ProtectionResource protection = getAuthzClient().protection("marta", "password");
    permission = protection.policy(resource.getId()).create(permission);
    AuthorizationResource authorization = getAuthzClient().authorization("kolo", "password");
    AuthorizationRequest request = new AuthorizationRequest();
    request.addPermission(resource.getId(), "Scope A");
    AuthorizationResponse authzResponse = authorization.authorize(request);
    assertNotNull(authzResponse);
    permission.removeRole("role_a");
    permission.addRole("role_b");
    protection.policy(resource.getId()).update(permission);
    try {
        authorization.authorize(request);
        fail("User should not have permission");
    } catch (Exception e) {
        assertTrue(AuthorizationDeniedException.class.isInstance(e));
    }
    try {
        getAuthzClient().authorization("alice", "password").authorize(request);
        fail("User should not have permission");
    } catch (Exception e) {
        assertTrue(AuthorizationDeniedException.class.isInstance(e));
    }
    permission.addRole("role_a");
    protection.policy(resource.getId()).update(permission);
    authzResponse = authorization.authorize(request);
    assertNotNull(authzResponse);
    protection.policy(resource.getId()).delete(permission.getId());
    try {
        authorization.authorize(request);
        fail("User should not have permission");
    } catch (Exception e) {
        assertTrue(AuthorizationDeniedException.class.isInstance(e));
    }
    try {
        getAuthzClient().protection("marta", "password").policy(resource.getId()).findById(permission.getId());
        fail("Permission must not exist");
    } catch (Exception e) {
        assertEquals(404, HttpResponseException.class.cast(e.getCause()).getStatusCode());
    }
    // create a user based permission, where only selected users are allowed access to the resource.
    permission = new UmaPermissionRepresentation();
    permission.setName("Custom User-Managed Permission");
    permission.setDescription("Specific users are allowed access to the resource");
    permission.addScope("Scope A");
    permission.addUser("alice");
    protection.policy(resource.getId()).create(permission);
    // alice should be able to access the resource with the updated permission.
    authzResponse = getAuthzClient().authorization("alice", "password").authorize(request);
    assertNotNull(authzResponse);
    // kolo shouldn't be able to access the resource with the updated permission.
    try {
        authorization.authorize(request);
        fail("User should not have permission to access the protected resource");
    } catch (Exception e) {
        assertTrue(AuthorizationDeniedException.class.isInstance(e));
    }
}
Also used : ProtectionResource(org.keycloak.authorization.client.resource.ProtectionResource) AuthorizationRequest(org.keycloak.representations.idm.authorization.AuthorizationRequest) HttpResponseException(org.keycloak.authorization.client.util.HttpResponseException) UmaPermissionRepresentation(org.keycloak.representations.idm.authorization.UmaPermissionRepresentation) AuthorizationResource(org.keycloak.authorization.client.resource.AuthorizationResource) HttpResponseException(org.keycloak.authorization.client.util.HttpResponseException) AuthorizationDeniedException(org.keycloak.authorization.client.AuthorizationDeniedException) NotFoundException(javax.ws.rs.NotFoundException) ResourceRepresentation(org.keycloak.representations.idm.authorization.ResourceRepresentation) AuthorizationResponse(org.keycloak.representations.idm.authorization.AuthorizationResponse) Test(org.junit.Test)

Example 44 with AuthorizationResponse

use of org.keycloak.representations.idm.authorization.AuthorizationResponse in project keycloak by keycloak.

the class UserManagedPermissionServiceTest method testGrantRequestedScopesOnly.

@Test
public void testGrantRequestedScopesOnly() {
    ResourceRepresentation resource = new ResourceRepresentation();
    resource.setName(UUID.randomUUID().toString());
    resource.setOwnerManagedAccess(true);
    resource.setOwner("marta");
    resource.addScope("view", "delete");
    ProtectionResource protection = getAuthzClient().protection("marta", "password");
    resource = protection.resource().create(resource);
    UmaPermissionRepresentation permission = new UmaPermissionRepresentation();
    permission.setName("Custom User-Managed Permission");
    permission.addScope("view");
    permission.addUser("kolo");
    permission = protection.policy(resource.getId()).create(permission);
    AuthorizationRequest request = new AuthorizationRequest();
    request.addPermission(resource.getId(), "view");
    AuthorizationResponse response = getAuthzClient().authorization("kolo", "password").authorize(request);
    AccessToken rpt = toAccessToken(response.getToken());
    Collection<Permission> permissions = rpt.getAuthorization().getPermissions();
    assertPermissions(permissions, resource.getId(), "view");
    assertTrue(permissions.isEmpty());
    request = new AuthorizationRequest();
    request.addPermission(resource.getId(), "delete");
    try {
        getAuthzClient().authorization("kolo", "password").authorize(request);
        fail("User should not have permission");
    } catch (Exception e) {
        assertTrue(AuthorizationDeniedException.class.isInstance(e));
    }
    request = new AuthorizationRequest();
    request.addPermission(resource.getId(), "delete");
    try {
        getAuthzClient().authorization("kolo", "password").authorize(request);
        fail("User should not have permission");
    } catch (Exception e) {
        assertTrue(AuthorizationDeniedException.class.isInstance(e));
    }
    request = new AuthorizationRequest();
    request.addPermission(resource.getId());
    response = getAuthzClient().authorization("kolo", "password").authorize(request);
    rpt = toAccessToken(response.getToken());
    permissions = rpt.getAuthorization().getPermissions();
    assertPermissions(permissions, resource.getId(), "view");
    assertTrue(permissions.isEmpty());
}
Also used : ProtectionResource(org.keycloak.authorization.client.resource.ProtectionResource) AuthorizationRequest(org.keycloak.representations.idm.authorization.AuthorizationRequest) AccessToken(org.keycloak.representations.AccessToken) Permission(org.keycloak.representations.idm.authorization.Permission) UmaPermissionRepresentation(org.keycloak.representations.idm.authorization.UmaPermissionRepresentation) HttpResponseException(org.keycloak.authorization.client.util.HttpResponseException) AuthorizationDeniedException(org.keycloak.authorization.client.AuthorizationDeniedException) NotFoundException(javax.ws.rs.NotFoundException) ResourceRepresentation(org.keycloak.representations.idm.authorization.ResourceRepresentation) AuthorizationResponse(org.keycloak.representations.idm.authorization.AuthorizationResponse) Test(org.junit.Test)

Example 45 with AuthorizationResponse

use of org.keycloak.representations.idm.authorization.AuthorizationResponse in project keycloak by keycloak.

the class UserManagedPermissionServiceTest method testPermissionInAdditionToUserGrantedPermission.

@Test
public void testPermissionInAdditionToUserGrantedPermission() {
    ResourceRepresentation resource = new ResourceRepresentation();
    resource.setName("Resource A");
    resource.setOwnerManagedAccess(true);
    resource.setOwner("marta");
    resource.addScope("Scope A", "Scope B", "Scope C");
    resource = getAuthzClient().protection().resource().create(resource);
    PermissionResponse ticketResponse = getAuthzClient().protection().permission().create(new PermissionRequest(resource.getId(), "Scope A"));
    AuthorizationRequest request = new AuthorizationRequest();
    request.setTicket(ticketResponse.getTicket());
    try {
        getAuthzClient().authorization("kolo", "password").authorize(request);
        fail("User should not have permission");
    } catch (Exception e) {
        assertTrue(AuthorizationDeniedException.class.isInstance(e));
        assertTrue(e.getMessage().contains("request_submitted"));
    }
    List<PermissionTicketRepresentation> tickets = getAuthzClient().protection().permission().findByResource(resource.getId());
    assertEquals(1, tickets.size());
    PermissionTicketRepresentation ticket = tickets.get(0);
    ticket.setGranted(true);
    getAuthzClient().protection().permission().update(ticket);
    AuthorizationResponse authzResponse = getAuthzClient().authorization("kolo", "password").authorize(request);
    assertNotNull(authzResponse);
    UmaPermissionRepresentation permission = new UmaPermissionRepresentation();
    permission.setName("Custom User-Managed Permission");
    permission.addScope("Scope A");
    permission.addRole("role_a");
    ProtectionResource protection = getAuthzClient().protection("marta", "password");
    permission = protection.policy(resource.getId()).create(permission);
    getAuthzClient().authorization("kolo", "password").authorize(request);
    ticket.setGranted(false);
    getAuthzClient().protection().permission().update(ticket);
    getAuthzClient().authorization("kolo", "password").authorize(request);
    permission = getAuthzClient().protection("marta", "password").policy(resource.getId()).findById(permission.getId());
    assertNotNull(permission);
    permission.removeRole("role_a");
    permission.addRole("role_b");
    getAuthzClient().protection("marta", "password").policy(resource.getId()).update(permission);
    try {
        getAuthzClient().authorization("kolo", "password").authorize(request);
        fail("User should not have permission");
    } catch (Exception e) {
        assertTrue(AuthorizationDeniedException.class.isInstance(e));
    }
    request = new AuthorizationRequest();
    request.addPermission(resource.getId());
    try {
        getAuthzClient().authorization("kolo", "password").authorize(request);
        fail("User should not have permission");
    } catch (Exception e) {
        assertTrue(AuthorizationDeniedException.class.isInstance(e));
    }
    getAuthzClient().protection("marta", "password").policy(resource.getId()).delete(permission.getId());
    try {
        getAuthzClient().authorization("kolo", "password").authorize(request);
        fail("User should not have permission");
    } catch (Exception e) {
        assertTrue(AuthorizationDeniedException.class.isInstance(e));
    }
}
Also used : PermissionRequest(org.keycloak.representations.idm.authorization.PermissionRequest) ProtectionResource(org.keycloak.authorization.client.resource.ProtectionResource) AuthorizationRequest(org.keycloak.representations.idm.authorization.AuthorizationRequest) PermissionTicketRepresentation(org.keycloak.representations.idm.authorization.PermissionTicketRepresentation) PermissionResponse(org.keycloak.representations.idm.authorization.PermissionResponse) UmaPermissionRepresentation(org.keycloak.representations.idm.authorization.UmaPermissionRepresentation) HttpResponseException(org.keycloak.authorization.client.util.HttpResponseException) AuthorizationDeniedException(org.keycloak.authorization.client.AuthorizationDeniedException) NotFoundException(javax.ws.rs.NotFoundException) ResourceRepresentation(org.keycloak.representations.idm.authorization.ResourceRepresentation) AuthorizationResponse(org.keycloak.representations.idm.authorization.AuthorizationResponse) Test(org.junit.Test)

Aggregations

AuthorizationResponse (org.keycloak.representations.idm.authorization.AuthorizationResponse)69 Test (org.junit.Test)58 AccessToken (org.keycloak.representations.AccessToken)43 Permission (org.keycloak.representations.idm.authorization.Permission)43 AuthorizationRequest (org.keycloak.representations.idm.authorization.AuthorizationRequest)41 AuthzClient (org.keycloak.authorization.client.AuthzClient)35 ResourceRepresentation (org.keycloak.representations.idm.authorization.ResourceRepresentation)30 ResourcePermissionRepresentation (org.keycloak.representations.idm.authorization.ResourcePermissionRepresentation)22 AuthorizationResource (org.keycloak.admin.client.resource.AuthorizationResource)20 ClientResource (org.keycloak.admin.client.resource.ClientResource)20 PermissionRequest (org.keycloak.representations.idm.authorization.PermissionRequest)20 AuthorizationDeniedException (org.keycloak.authorization.client.AuthorizationDeniedException)19 OAuthClient (org.keycloak.testsuite.util.OAuthClient)17 AccessTokenResponse (org.keycloak.representations.AccessTokenResponse)15 JSPolicyRepresentation (org.keycloak.representations.idm.authorization.JSPolicyRepresentation)14 PermissionResponse (org.keycloak.representations.idm.authorization.PermissionResponse)14 ScopePermissionRepresentation (org.keycloak.representations.idm.authorization.ScopePermissionRepresentation)14 Response (javax.ws.rs.core.Response)13 TokenIntrospectionResponse (org.keycloak.authorization.client.representation.TokenIntrospectionResponse)12 ArrayList (java.util.ArrayList)11