Search in sources :

Example 21 with ClientModel

use of org.keycloak.models.ClientModel in project keycloak by keycloak.

the class ApplicationsBean method getApplications.

private Stream<ClientModel> getApplications(KeycloakSession session, RealmModel realm, UserModel user) {
    Predicate<ClientModel> bearerOnly = ClientModel::isBearerOnly;
    Stream<ClientModel> clients = realm.getClientsStream().filter(bearerOnly.negate());
    Predicate<ClientModel> isLocal = client -> new StorageId(client.getId()).isLocal();
    return Stream.concat(clients, session.users().getConsentsStream(realm, user.getId()).map(UserConsentModel::getClient).filter(isLocal.negate())).distinct();
}
Also used : ClientModel(org.keycloak.models.ClientModel) AdminPermissions(org.keycloak.services.resources.admin.permissions.AdminPermissions) ClientScopeModel(org.keycloak.models.ClientScopeModel) RealmModel(org.keycloak.models.RealmModel) Predicate(java.util.function.Predicate) Constants(org.keycloak.models.Constants) KeycloakSession(org.keycloak.models.KeycloakSession) Set(java.util.Set) RoleModel(org.keycloak.models.RoleModel) TokenManager(org.keycloak.protocol.oidc.TokenManager) Collectors(java.util.stream.Collectors) StorageId(org.keycloak.storage.StorageId) ResolveRelative(org.keycloak.services.util.ResolveRelative) ArrayList(java.util.ArrayList) OrderedModel(org.keycloak.models.OrderedModel) Objects(java.util.Objects) List(java.util.List) UserModel(org.keycloak.models.UserModel) Stream(java.util.stream.Stream) UserSessionManager(org.keycloak.services.managers.UserSessionManager) UserConsentModel(org.keycloak.models.UserConsentModel) MultivaluedHashMap(org.keycloak.common.util.MultivaluedHashMap) LinkedList(java.util.LinkedList) ClientModel(org.keycloak.models.ClientModel) StorageId(org.keycloak.storage.StorageId)

Example 22 with ClientModel

use of org.keycloak.models.ClientModel in project keycloak by keycloak.

the class ApplicationsBean method processRoles.

private void processRoles(Set<RoleModel> inputRoles, List<RoleModel> realmRoles, MultivaluedHashMap<String, ClientRoleEntry> clientRoles) {
    for (RoleModel role : inputRoles) {
        if (role.getContainer() instanceof RealmModel) {
            realmRoles.add(role);
        } else {
            ClientModel currentClient = (ClientModel) role.getContainer();
            ClientRoleEntry clientRole = new ClientRoleEntry(currentClient.getClientId(), currentClient.getName(), role.getName(), role.getDescription());
            clientRoles.add(currentClient.getClientId(), clientRole);
        }
    }
}
Also used : RealmModel(org.keycloak.models.RealmModel) ClientModel(org.keycloak.models.ClientModel) RoleModel(org.keycloak.models.RoleModel)

Example 23 with ClientModel

use of org.keycloak.models.ClientModel in project keycloak by keycloak.

the class DefaultTokenManager method decodeClientJWT.

@Override
public <T> T decodeClientJWT(String jwt, ClientModel client, BiConsumer<JOSE, ClientModel> jwtValidator, Class<T> clazz) {
    if (jwt == null) {
        return null;
    }
    JOSE joseToken = JOSEParser.parse(jwt);
    jwtValidator.accept(joseToken, client);
    if (joseToken instanceof JWE) {
        try {
            Optional<KeyWrapper> activeKey;
            String kid = joseToken.getHeader().getKeyId();
            Stream<KeyWrapper> keys = session.keys().getKeysStream(session.getContext().getRealm());
            if (kid == null) {
                activeKey = keys.filter(k -> KeyUse.ENC.equals(k.getUse()) && k.getPublicKey() != null).sorted(Comparator.comparingLong(KeyWrapper::getProviderPriority).reversed()).findFirst();
            } else {
                activeKey = keys.filter(k -> KeyUse.ENC.equals(k.getUse()) && k.getKid().equals(kid)).findAny();
            }
            JWE jwe = JWE.class.cast(joseToken);
            Key privateKey = activeKey.map(KeyWrapper::getPrivateKey).orElseThrow(() -> new RuntimeException("Could not find private key for decrypting token"));
            jwe.getKeyStorage().setDecryptionKey(privateKey);
            byte[] content = jwe.verifyAndDecodeJwe().getContent();
            try {
                JOSE jws = JOSEParser.parse(new String(content));
                if (jws instanceof JWSInput) {
                    jwtValidator.accept(jws, client);
                    return verifyJWS(client, clazz, (JWSInput) jws);
                }
            } catch (Exception ignore) {
            // try to decrypt content as is
            }
            return JsonSerialization.readValue(content, clazz);
        } catch (IOException cause) {
            throw new RuntimeException("Failed to deserialize JWT", cause);
        } catch (JWEException cause) {
            throw new RuntimeException("Failed to decrypt JWT", cause);
        }
    }
    return verifyJWS(client, clazz, (JWSInput) joseToken);
}
Also used : KeyWrapper(org.keycloak.crypto.KeyWrapper) ClientModel(org.keycloak.models.ClientModel) KeycloakModelUtils(org.keycloak.models.utils.KeycloakModelUtils) LogoutToken(org.keycloak.representations.LogoutToken) Logger(org.jboss.logging.Logger) SignatureSignerContext(org.keycloak.crypto.SignatureSignerContext) Constants(org.keycloak.models.Constants) Algorithm(org.keycloak.crypto.Algorithm) JWEEncryptionProvider(org.keycloak.jose.jwe.enc.JWEEncryptionProvider) Function(java.util.function.Function) Supplier(java.util.function.Supplier) Token(org.keycloak.Token) SignatureProvider(org.keycloak.crypto.SignatureProvider) TokenUtil(org.keycloak.util.TokenUtil) UserModel(org.keycloak.models.UserModel) ContentEncryptionProvider(org.keycloak.crypto.ContentEncryptionProvider) JWEAlgorithmProvider(org.keycloak.jose.jwe.alg.JWEAlgorithmProvider) AuthenticatedClientSessionModel(org.keycloak.models.AuthenticatedClientSessionModel) OIDCAdvancedConfigWrapper(org.keycloak.protocol.oidc.OIDCAdvancedConfigWrapper) BiConsumer(java.util.function.BiConsumer) TokenManager(org.keycloak.models.TokenManager) JOSEParser(org.keycloak.jose.JOSEParser) RealmModel(org.keycloak.models.RealmModel) JWE(org.keycloak.jose.jwe.JWE) JWK(org.keycloak.jose.jwk.JWK) Predicate(java.util.function.Predicate) JWEException(org.keycloak.jose.jwe.JWEException) PublicKeyStorageManager(org.keycloak.keys.loader.PublicKeyStorageManager) KeycloakSession(org.keycloak.models.KeycloakSession) IOException(java.io.IOException) CekManagementProvider(org.keycloak.crypto.CekManagementProvider) TokenCategory(org.keycloak.TokenCategory) JsonSerialization(org.keycloak.util.JsonSerialization) Key(java.security.Key) OIDCConfigAttributes(org.keycloak.protocol.oidc.OIDCConfigAttributes) Stream(java.util.stream.Stream) KeyUse(org.keycloak.crypto.KeyUse) PrivateKey(java.security.PrivateKey) OIDCLoginProtocol(org.keycloak.protocol.oidc.OIDCLoginProtocol) Optional(java.util.Optional) JOSE(org.keycloak.jose.JOSE) Comparator(java.util.Comparator) ClientSignatureVerifierProvider(org.keycloak.crypto.ClientSignatureVerifierProvider) UnsupportedEncodingException(java.io.UnsupportedEncodingException) JWEException(org.keycloak.jose.jwe.JWEException) IOException(java.io.IOException) JWEException(org.keycloak.jose.jwe.JWEException) IOException(java.io.IOException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) KeyWrapper(org.keycloak.crypto.KeyWrapper) JOSE(org.keycloak.jose.JOSE) JWE(org.keycloak.jose.jwe.JWE) Key(java.security.Key) PrivateKey(java.security.PrivateKey)

Example 24 with ClientModel

use of org.keycloak.models.ClientModel in project keycloak by keycloak.

the class DefaultTokenManager method getEncryptedToken.

private String getEncryptedToken(TokenCategory category, String encodedToken) {
    String encryptedToken = null;
    String algAlgorithm = cekManagementAlgorithm(category);
    String encAlgorithm = encryptAlgorithm(category);
    CekManagementProvider cekManagementProvider = session.getProvider(CekManagementProvider.class, algAlgorithm);
    JWEAlgorithmProvider jweAlgorithmProvider = cekManagementProvider.jweAlgorithmProvider();
    ContentEncryptionProvider contentEncryptionProvider = session.getProvider(ContentEncryptionProvider.class, encAlgorithm);
    JWEEncryptionProvider jweEncryptionProvider = contentEncryptionProvider.jweEncryptionProvider();
    ClientModel client = session.getContext().getClient();
    KeyWrapper keyWrapper = PublicKeyStorageManager.getClientPublicKeyWrapper(session, client, JWK.Use.ENCRYPTION, algAlgorithm);
    if (keyWrapper == null) {
        throw new RuntimeException("can not get encryption KEK");
    }
    Key encryptionKek = keyWrapper.getPublicKey();
    String encryptionKekId = keyWrapper.getKid();
    try {
        encryptedToken = TokenUtil.jweKeyEncryptionEncode(encryptionKek, encodedToken.getBytes("UTF-8"), algAlgorithm, encAlgorithm, encryptionKekId, jweAlgorithmProvider, jweEncryptionProvider);
    } catch (JWEException | UnsupportedEncodingException e) {
        throw new RuntimeException(e);
    }
    return encryptedToken;
}
Also used : KeyWrapper(org.keycloak.crypto.KeyWrapper) ClientModel(org.keycloak.models.ClientModel) ContentEncryptionProvider(org.keycloak.crypto.ContentEncryptionProvider) JWEAlgorithmProvider(org.keycloak.jose.jwe.alg.JWEAlgorithmProvider) JWEException(org.keycloak.jose.jwe.JWEException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) JWEEncryptionProvider(org.keycloak.jose.jwe.enc.JWEEncryptionProvider) Key(java.security.Key) PrivateKey(java.security.PrivateKey) CekManagementProvider(org.keycloak.crypto.CekManagementProvider)

Example 25 with ClientModel

use of org.keycloak.models.ClientModel in project keycloak by keycloak.

the class AuthenticationManager method frontchannelLogoutClientSession.

private static Response frontchannelLogoutClientSession(KeycloakSession session, RealmModel realm, AuthenticatedClientSessionModel clientSession, AuthenticationSessionModel logoutAuthSession, UriInfo uriInfo, HttpHeaders headers) {
    UserSessionModel userSession = clientSession.getUserSession();
    ClientModel client = clientSession.getClient();
    if (!client.isFrontchannelLogout() || AuthenticationSessionModel.Action.LOGGED_OUT.name().equals(clientSession.getAction())) {
        return null;
    }
    final AuthenticationSessionModel.Action logoutState = getClientLogoutAction(logoutAuthSession, client.getId());
    if (logoutState == AuthenticationSessionModel.Action.LOGGED_OUT || logoutState == AuthenticationSessionModel.Action.LOGGING_OUT) {
        return null;
    }
    try {
        session.clientPolicy().triggerOnEvent(new LogoutRequestContext());
    } catch (ClientPolicyException cpe) {
        throw new ErrorResponseException(cpe.getError(), cpe.getErrorDetail(), cpe.getErrorStatus());
    }
    try {
        setClientLogoutAction(logoutAuthSession, client.getId(), AuthenticationSessionModel.Action.LOGGING_OUT);
        String authMethod = clientSession.getProtocol();
        // must be a keycloak service like account
        if (authMethod == null)
            return null;
        logger.debugv("frontchannel logout to: {0}", client.getClientId());
        LoginProtocol protocol = session.getProvider(LoginProtocol.class, authMethod);
        protocol.setRealm(realm).setHttpHeaders(headers).setUriInfo(uriInfo);
        Response response = protocol.frontchannelLogout(userSession, clientSession);
        if (response != null) {
            logger.debug("returning frontchannel logout request to client");
            if (!AuthenticationSessionModel.Action.LOGGING_OUT.name().equals(clientSession.getAction())) {
                setClientLogoutAction(logoutAuthSession, client.getId(), AuthenticationSessionModel.Action.LOGGED_OUT);
            }
            return response;
        }
    } catch (Exception e) {
        ServicesLogger.LOGGER.failedToLogoutClient(e);
    }
    return null;
}
Also used : BackchannelLogoutResponse(org.keycloak.protocol.oidc.BackchannelLogoutResponse) Response(javax.ws.rs.core.Response) ClientModel(org.keycloak.models.ClientModel) UserSessionModel(org.keycloak.models.UserSessionModel) AuthenticationSessionModel(org.keycloak.sessions.AuthenticationSessionModel) RootAuthenticationSessionModel(org.keycloak.sessions.RootAuthenticationSessionModel) ErrorResponseException(org.keycloak.services.ErrorResponseException) LogoutRequestContext(org.keycloak.services.clientpolicy.context.LogoutRequestContext) LoginProtocol(org.keycloak.protocol.LoginProtocol) OIDCLoginProtocol(org.keycloak.protocol.oidc.OIDCLoginProtocol) ErrorResponseException(org.keycloak.services.ErrorResponseException) AuthenticationFlowException(org.keycloak.authentication.AuthenticationFlowException) ClientPolicyException(org.keycloak.services.clientpolicy.ClientPolicyException) VerificationException(org.keycloak.common.VerificationException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) ClientPolicyException(org.keycloak.services.clientpolicy.ClientPolicyException)

Aggregations

ClientModel (org.keycloak.models.ClientModel)344 RealmModel (org.keycloak.models.RealmModel)148 UserModel (org.keycloak.models.UserModel)88 RoleModel (org.keycloak.models.RoleModel)74 KeycloakSession (org.keycloak.models.KeycloakSession)67 Test (org.junit.Test)64 UserSessionModel (org.keycloak.models.UserSessionModel)41 ResourceServer (org.keycloak.authorization.model.ResourceServer)39 Policy (org.keycloak.authorization.model.Policy)38 HashMap (java.util.HashMap)37 AuthorizationProvider (org.keycloak.authorization.AuthorizationProvider)36 AbstractTestRealmKeycloakTest (org.keycloak.testsuite.AbstractTestRealmKeycloakTest)34 ModelTest (org.keycloak.testsuite.arquillian.annotation.ModelTest)34 List (java.util.List)32 Map (java.util.Map)32 Path (javax.ws.rs.Path)29 LinkedList (java.util.LinkedList)28 ClientScopeModel (org.keycloak.models.ClientScopeModel)28 ArrayList (java.util.ArrayList)27 AuthenticatedClientSessionModel (org.keycloak.models.AuthenticatedClientSessionModel)27