Search in sources :

Example 91 with AccessToken

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

the class ClientAuthSignedJWTTest method assertSuccess.

private void assertSuccess(OAuthClient.AccessTokenResponse response, String clientId, String userId, String userName) {
    assertEquals(200, response.getStatusCode());
    AccessToken accessToken = oauth.verifyToken(response.getAccessToken());
    RefreshToken refreshToken = oauth.parseRefreshToken(response.getRefreshToken());
    events.expectClientLogin().client(clientId).user(userId).session(accessToken.getSessionState()).detail(Details.TOKEN_ID, accessToken.getId()).detail(Details.REFRESH_TOKEN_ID, refreshToken.getId()).detail(Details.USERNAME, userName).detail(Details.CLIENT_AUTH_METHOD, JWTClientAuthenticator.PROVIDER_ID).assertEvent();
}
Also used : RefreshToken(org.keycloak.representations.RefreshToken) AccessToken(org.keycloak.representations.AccessToken)

Example 92 with AccessToken

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

the class ClientAuthSignedJWTTest method testClientWithGeneratedKeys.

private void testClientWithGeneratedKeys(String format) throws Exception {
    ClientRepresentation client = app3;
    UserRepresentation user = defaultUser;
    final String keyAlias = "somekey";
    final String keyPassword = "pwd1";
    final String storePassword = "pwd2";
    // Generate new keystore (which is intended for sending to the user and store in a client app)
    // with public/private keys; in KC, store the certificate itself
    KeyStoreConfig keyStoreConfig = new KeyStoreConfig();
    keyStoreConfig.setFormat(format);
    keyStoreConfig.setKeyPassword(keyPassword);
    keyStoreConfig.setStorePassword(storePassword);
    keyStoreConfig.setKeyAlias(keyAlias);
    client = getClient(testRealm.getRealm(), client.getId()).toRepresentation();
    final String certOld = client.getAttributes().get(JWTClientAuthenticator.CERTIFICATE_ATTR);
    // Generate the keystore and save the new certificate in client (in KC)
    byte[] keyStoreBytes = getClientAttributeCertificateResource(testRealm.getRealm(), client.getId()).generateAndGetKeystore(keyStoreConfig);
    ByteArrayInputStream keyStoreIs = new ByteArrayInputStream(keyStoreBytes);
    KeyStore keyStore = getKeystore(keyStoreIs, storePassword, format);
    keyStoreIs.close();
    client = getClient(testRealm.getRealm(), client.getId()).toRepresentation();
    X509Certificate x509Cert = (X509Certificate) keyStore.getCertificate(keyAlias);
    assertCertificate(client, certOld, KeycloakModelUtils.getPemFromCertificate(x509Cert));
    // Try to login with the new keys
    oauth.clientId(client.getClientId());
    PrivateKey privateKey = (PrivateKey) keyStore.getKey(keyAlias, keyPassword.toCharArray());
    KeyPair keyPair = new KeyPair(x509Cert.getPublicKey(), privateKey);
    OAuthClient.AccessTokenResponse response = doGrantAccessTokenRequest(user.getUsername(), user.getCredentials().get(0).getValue(), getClientSignedJWT(keyPair, client.getClientId()));
    assertEquals(200, response.getStatusCode());
    AccessToken accessToken = oauth.verifyToken(response.getAccessToken());
    RefreshToken refreshToken = oauth.parseRefreshToken(response.getRefreshToken());
    events.expectLogin().client(client.getClientId()).session(accessToken.getSessionState()).detail(Details.GRANT_TYPE, OAuth2Constants.PASSWORD).detail(Details.TOKEN_ID, accessToken.getId()).detail(Details.REFRESH_TOKEN_ID, refreshToken.getId()).detail(Details.USERNAME, user.getUsername()).detail(Details.CLIENT_AUTH_METHOD, JWTClientAuthenticator.PROVIDER_ID).removeDetail(Details.CODE_ID).removeDetail(Details.REDIRECT_URI).removeDetail(Details.CONSENT).assertEvent();
}
Also used : KeyPair(java.security.KeyPair) PrivateKey(java.security.PrivateKey) OAuthClient(org.keycloak.testsuite.util.OAuthClient) KeyStore(java.security.KeyStore) X509Certificate(java.security.cert.X509Certificate) ClientRepresentation(org.keycloak.representations.idm.ClientRepresentation) RefreshToken(org.keycloak.representations.RefreshToken) ByteArrayInputStream(java.io.ByteArrayInputStream) AccessToken(org.keycloak.representations.AccessToken) UserRepresentation(org.keycloak.representations.idm.UserRepresentation) KeyStoreConfig(org.keycloak.representations.KeyStoreConfig)

Example 93 with AccessToken

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

the class AccessTokenDuplicateEmailsTest method loginWithSecondDuplicateEmailUser.

@Test
public void loginWithSecondDuplicateEmailUser() throws Exception {
    oauth.doLogin("duplicate-email-user2", "password");
    String code = oauth.getCurrentQuery().get(OAuth2Constants.CODE);
    OAuthClient.AccessTokenResponse response = oauth.doAccessTokenRequest(code, "password");
    assertEquals(200, response.getStatusCode());
    AccessToken token = oauth.verifyToken(response.getAccessToken());
    assertEquals(findUserByUsername(adminClient.realm("test-duplicate-emails"), "duplicate-email-user2").getId(), token.getSubject());
    assertEquals("duplicate-email-user@localhost", token.getEmail());
}
Also used : OAuthClient(org.keycloak.testsuite.util.OAuthClient) AccessToken(org.keycloak.representations.AccessToken) Test(org.junit.Test) AbstractKeycloakTest(org.keycloak.testsuite.AbstractKeycloakTest)

Example 94 with AccessToken

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

the class PolicyEvaluationResponseBuilder method build.

public static PolicyEvaluationResponse build(PolicyEvaluationService.EvaluationDecisionCollector decision, ResourceServer resourceServer, AuthorizationProvider authorization, KeycloakIdentity identity) {
    PolicyEvaluationResponse response = new PolicyEvaluationResponse();
    List<PolicyEvaluationResponse.EvaluationResultRepresentation> resultsRep = new ArrayList<>();
    AccessToken accessToken = identity.getAccessToken();
    AccessToken.Authorization authorizationData = new AccessToken.Authorization();
    authorizationData.setPermissions(decision.results());
    accessToken.setAuthorization(authorizationData);
    ClientModel clientModel = authorization.getRealm().getClientById(resourceServer.getId());
    if (!accessToken.hasAudience(clientModel.getClientId())) {
        accessToken.audience(clientModel.getClientId());
    }
    response.setRpt(accessToken);
    Collection<Result> results = decision.getResults();
    if (results.stream().anyMatch(evaluationResult -> evaluationResult.getEffect().equals(Decision.Effect.DENY))) {
        response.setStatus(DecisionEffect.DENY);
    } else {
        response.setStatus(DecisionEffect.PERMIT);
    }
    for (Result result : results) {
        PolicyEvaluationResponse.EvaluationResultRepresentation rep = new PolicyEvaluationResponse.EvaluationResultRepresentation();
        if (result.getEffect() == Decision.Effect.DENY) {
            rep.setStatus(DecisionEffect.DENY);
        } else {
            rep.setStatus(DecisionEffect.PERMIT);
        }
        resultsRep.add(rep);
        if (result.getPermission().getResource() != null) {
            ResourceRepresentation resource = new ResourceRepresentation();
            resource.setId(result.getPermission().getResource().getId());
            resource.setName(result.getPermission().getResource().getName());
            rep.setResource(resource);
        } else {
            ResourceRepresentation resource = new ResourceRepresentation();
            resource.setName("Any Resource with Scopes " + result.getPermission().getScopes().stream().map(Scope::getName).collect(Collectors.toList()));
            rep.setResource(resource);
        }
        rep.setScopes(result.getPermission().getScopes().stream().map(scope -> {
            ScopeRepresentation representation = new ScopeRepresentation();
            representation.setId(scope.getId());
            representation.setName(scope.getName());
            return representation;
        }).collect(Collectors.toList()));
        List<PolicyEvaluationResponse.PolicyResultRepresentation> policies = new ArrayList<>();
        for (Result.PolicyResult policy : result.getResults()) {
            PolicyResultRepresentation policyRep = toRepresentation(policy, authorization);
            if ("resource".equals(policy.getPolicy().getType())) {
                policyRep.getPolicy().setScopes(result.getPermission().getResource().getScopes().stream().map(Scope::getName).collect(Collectors.toSet()));
            }
            policies.add(policyRep);
        }
        rep.setPolicies(policies);
    }
    resultsRep.sort(Comparator.comparing(o -> o.getResource().getName()));
    Map<String, PolicyEvaluationResponse.EvaluationResultRepresentation> groupedResults = new HashMap<>();
    resultsRep.forEach(evaluationResultRepresentation -> {
        PolicyEvaluationResponse.EvaluationResultRepresentation result = groupedResults.get(evaluationResultRepresentation.getResource().getId());
        ResourceRepresentation resource = evaluationResultRepresentation.getResource();
        if (result == null) {
            groupedResults.put(resource.getId(), evaluationResultRepresentation);
            result = evaluationResultRepresentation;
        }
        if (result.getStatus().equals(DecisionEffect.PERMIT) || (evaluationResultRepresentation.getStatus().equals(DecisionEffect.PERMIT) && result.getStatus().equals(DecisionEffect.DENY))) {
            result.setStatus(DecisionEffect.PERMIT);
        }
        List<ScopeRepresentation> scopes = result.getScopes();
        if (DecisionEffect.PERMIT.equals(result.getStatus())) {
            result.setAllowedScopes(scopes);
        }
        if (resource.getId() != null) {
            if (!scopes.isEmpty()) {
                result.getResource().setName(evaluationResultRepresentation.getResource().getName() + " with scopes " + scopes.stream().flatMap((Function<ScopeRepresentation, Stream<?>>) scopeRepresentation -> Arrays.asList(scopeRepresentation.getName()).stream()).collect(Collectors.toList()));
            } else {
                result.getResource().setName(evaluationResultRepresentation.getResource().getName());
            }
        } else {
            result.getResource().setName("Any Resource with Scopes " + scopes.stream().flatMap((Function<ScopeRepresentation, Stream<?>>) scopeRepresentation -> Arrays.asList(scopeRepresentation.getName()).stream()).collect(Collectors.toList()));
        }
        List<PolicyEvaluationResponse.PolicyResultRepresentation> policies = result.getPolicies();
        for (PolicyEvaluationResponse.PolicyResultRepresentation policy : new ArrayList<>(evaluationResultRepresentation.getPolicies())) {
            if (!policies.contains(policy)) {
                policies.add(policy);
            }
        }
    });
    response.setResults(groupedResults.values().stream().collect(Collectors.toList()));
    return response;
}
Also used : ClientModel(org.keycloak.models.ClientModel) Scope(org.keycloak.authorization.model.Scope) ResourceRepresentation(org.keycloak.representations.idm.authorization.ResourceRepresentation) Arrays(java.util.Arrays) PolicyResultRepresentation(org.keycloak.representations.idm.authorization.PolicyEvaluationResponse.PolicyResultRepresentation) HashMap(java.util.HashMap) Function(java.util.function.Function) PolicyRepresentation(org.keycloak.representations.idm.authorization.PolicyRepresentation) PermissionTicket(org.keycloak.authorization.model.PermissionTicket) ArrayList(java.util.ArrayList) PolicyEvaluationService(org.keycloak.authorization.admin.PolicyEvaluationService) UserModel(org.keycloak.models.UserModel) AccessToken(org.keycloak.representations.AccessToken) Map(java.util.Map) ScopeRepresentation(org.keycloak.representations.idm.authorization.ScopeRepresentation) AuthorizationProvider(org.keycloak.authorization.AuthorizationProvider) ResourceServer(org.keycloak.authorization.model.ResourceServer) RealmModel(org.keycloak.models.RealmModel) EnumMap(java.util.EnumMap) Collection(java.util.Collection) KeycloakSession(org.keycloak.models.KeycloakSession) Set(java.util.Set) Decision(org.keycloak.authorization.Decision) Collectors(java.util.stream.Collectors) KeycloakIdentity(org.keycloak.authorization.common.KeycloakIdentity) Policy(org.keycloak.authorization.model.Policy) List(java.util.List) Stream(java.util.stream.Stream) Result(org.keycloak.authorization.policy.evaluation.Result) PolicyEvaluationResponse(org.keycloak.representations.idm.authorization.PolicyEvaluationResponse) DecisionEffect(org.keycloak.representations.idm.authorization.DecisionEffect) Comparator(java.util.Comparator) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) PolicyResultRepresentation(org.keycloak.representations.idm.authorization.PolicyEvaluationResponse.PolicyResultRepresentation) Result(org.keycloak.authorization.policy.evaluation.Result) ResourceRepresentation(org.keycloak.representations.idm.authorization.ResourceRepresentation) ClientModel(org.keycloak.models.ClientModel) Function(java.util.function.Function) Scope(org.keycloak.authorization.model.Scope) AccessToken(org.keycloak.representations.AccessToken) PolicyEvaluationResponse(org.keycloak.representations.idm.authorization.PolicyEvaluationResponse) ScopeRepresentation(org.keycloak.representations.idm.authorization.ScopeRepresentation) PolicyResultRepresentation(org.keycloak.representations.idm.authorization.PolicyEvaluationResponse.PolicyResultRepresentation)

Example 95 with AccessToken

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

the class AuthorizationTokenService method resolvePreviousGrantedPermissions.

private void resolvePreviousGrantedPermissions(PermissionTicketToken ticket, KeycloakAuthorizationRequest request, ResourceServer resourceServer, Map<String, ResourcePermission> permissionsToEvaluate, ResourceStore resourceStore, ScopeStore scopeStore, AtomicInteger limit) {
    AccessToken rpt = request.getRpt();
    if (rpt != null && rpt.isActive()) {
        Authorization authorizationData = rpt.getAuthorization();
        if (authorizationData != null) {
            Collection<Permission> permissions = authorizationData.getPermissions();
            if (permissions != null) {
                for (Permission grantedPermission : permissions) {
                    if (limit != null && limit.get() <= 0) {
                        break;
                    }
                    Resource resource = resourceStore.findById(grantedPermission.getResourceId(), ticket.getIssuedFor());
                    if (resource != null) {
                        ResourcePermission permission = permissionsToEvaluate.get(resource.getId());
                        if (permission == null) {
                            permission = new ResourcePermission(resource, new ArrayList<>(), resourceServer, grantedPermission.getClaims());
                            permissionsToEvaluate.put(resource.getId(), permission);
                            if (limit != null) {
                                limit.decrementAndGet();
                            }
                        } else {
                            if (grantedPermission.getClaims() != null) {
                                for (Entry<String, Set<String>> entry : grantedPermission.getClaims().entrySet()) {
                                    Set<String> claims = permission.getClaims().get(entry.getKey());
                                    if (claims != null) {
                                        claims.addAll(entry.getValue());
                                    }
                                }
                            }
                        }
                        for (String scopeName : grantedPermission.getScopes()) {
                            Scope scope = scopeStore.findByName(scopeName, resourceServer.getId());
                            if (scope != null) {
                                if (!permission.getScopes().contains(scope)) {
                                    permission.getScopes().add(scope);
                                }
                            }
                        }
                    }
                }
            }
        }
    }
}
Also used : Authorization(org.keycloak.representations.AccessToken.Authorization) Set(java.util.Set) HashSet(java.util.HashSet) Scope(org.keycloak.authorization.model.Scope) AccessToken(org.keycloak.representations.AccessToken) ResourcePermission(org.keycloak.authorization.permission.ResourcePermission) Permission(org.keycloak.representations.idm.authorization.Permission) Resource(org.keycloak.authorization.model.Resource) ArrayList(java.util.ArrayList) ResourcePermission(org.keycloak.authorization.permission.ResourcePermission)

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