Java Code Examples for org.keycloak.models.utils.KeycloakModelUtils#getClientScopeByName()

The following examples show how to use org.keycloak.models.utils.KeycloakModelUtils#getClientScopeByName() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: MigrationUtils.java    From keycloak with Apache License 2.0 6 votes vote down vote up
public static void migrateOldOfflineToken(KeycloakSession session, RealmModel realm, ClientModel client, UserModel user) throws OAuthErrorException {
    ClientScopeModel offlineScope = KeycloakModelUtils.getClientScopeByName(realm, OAuth2Constants.OFFLINE_ACCESS);
    if (offlineScope == null) {
        throw new OAuthErrorException(OAuthErrorException.INVALID_GRANT, "Offline Access scope not found");
    }

    if (client.isConsentRequired()) {
        // Automatically add consents for client and for offline_access. We know that both were defacto approved by user already and offlineSession is still valid
        UserConsentModel consent = session.users().getConsentByClient(realm, user.getId(), client.getId());
        if (consent != null) {
            if (client.isDisplayOnConsentScreen()) {
                consent.addGrantedClientScope(client);
            }
            if (offlineScope.isDisplayOnConsentScreen()) {
                consent.addGrantedClientScope(offlineScope);
            }
            session.users().updateConsent(realm, user.getId(), consent);
        }
    }
}
 
Example 2
Source File: OIDCLoginProtocolFactory.java    From keycloak with Apache License 2.0 6 votes vote down vote up
public static ClientScopeModel addRolesClientScope(RealmModel newRealm) {
    ClientScopeModel rolesScope = KeycloakModelUtils.getClientScopeByName(newRealm, ROLES_SCOPE);
    if (rolesScope == null) {
        rolesScope = newRealm.addClientScope(ROLES_SCOPE);
        rolesScope.setDescription("OpenID Connect scope for add user roles to the access token");
        rolesScope.setDisplayOnConsentScreen(true);
        rolesScope.setConsentScreenText(ROLES_SCOPE_CONSENT_TEXT);
        rolesScope.setIncludeInTokenScope(false);
        rolesScope.setProtocol(OIDCLoginProtocol.LOGIN_PROTOCOL);
        rolesScope.addProtocolMapper(builtins.get(REALM_ROLES));
        rolesScope.addProtocolMapper(builtins.get(CLIENT_ROLES));
        rolesScope.addProtocolMapper(builtins.get(AUDIENCE_RESOLVE));

        // 'roles' will be default client scope
        newRealm.addDefaultClientScope(rolesScope, true);
    } else {
        logger.debugf("Client scope '%s' already exists in realm '%s'. Skip creating it.", ROLES_SCOPE, newRealm.getName());
    }

    return rolesScope;
}
 
Example 3
Source File: OIDCLoginProtocolFactory.java    From keycloak with Apache License 2.0 6 votes vote down vote up
public static ClientScopeModel addWebOriginsClientScope(RealmModel newRealm) {
    ClientScopeModel originsScope = KeycloakModelUtils.getClientScopeByName(newRealm, WEB_ORIGINS_SCOPE);
    if (originsScope == null) {
        originsScope = newRealm.addClientScope(WEB_ORIGINS_SCOPE);
        originsScope.setDescription("OpenID Connect scope for add allowed web origins to the access token");
        originsScope.setDisplayOnConsentScreen(false); // No requesting consent from user for this. It is rather the permission of client
        originsScope.setConsentScreenText("");
        originsScope.setIncludeInTokenScope(false);
        originsScope.setProtocol(OIDCLoginProtocol.LOGIN_PROTOCOL);
        originsScope.addProtocolMapper(builtins.get(ALLOWED_WEB_ORIGINS));

        // 'web-origins' will be default client scope
        newRealm.addDefaultClientScope(originsScope, true);
    } else {
        logger.debugf("Client scope '%s' already exists in realm '%s'. Skip creating it.", WEB_ORIGINS_SCOPE, newRealm.getName());
    }

    return originsScope;
}
 
Example 4
Source File: OIDCLoginProtocolFactory.java    From keycloak with Apache License 2.0 6 votes vote down vote up
/**
 * Adds the {@code microprofile-jwt} optional client scope to the specified realm. If a {@code microprofile-jwt} client scope
 * already exists in the realm then the existing scope is returned. Otherwise, a new scope is created and returned.
 *
 * @param newRealm the realm to which the {@code microprofile-jwt} scope is to be added.
 * @return a reference to the {@code microprofile-jwt} client scope that was either created or already exists in the realm.
 */
public static ClientScopeModel addMicroprofileJWTClientScope(RealmModel newRealm) {
    ClientScopeModel microprofileScope = KeycloakModelUtils.getClientScopeByName(newRealm, MICROPROFILE_JWT_SCOPE);
    if (microprofileScope == null) {
        microprofileScope = newRealm.addClientScope(MICROPROFILE_JWT_SCOPE);
        microprofileScope.setDescription("Microprofile - JWT built-in scope");
        microprofileScope.setDisplayOnConsentScreen(false);
        microprofileScope.setIncludeInTokenScope(true);
        microprofileScope.setProtocol(OIDCLoginProtocol.LOGIN_PROTOCOL);
        microprofileScope.addProtocolMapper(builtins.get(UPN));
        microprofileScope.addProtocolMapper(builtins.get(GROUPS));
        newRealm.addDefaultClientScope(microprofileScope, false);
    } else {
        logger.debugf("Client scope '%s' already exists in realm '%s'. Skip creating it.", MICROPROFILE_JWT_SCOPE, newRealm.getName());
    }

    return microprofileScope;
}
 
Example 5
Source File: HardcodedClientStorageProvider.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Override
public Map<String, ClientScopeModel> getClientScopes(boolean defaultScope, boolean filterByProtocol) {
    if (defaultScope) {
        ClientScopeModel rolesScope = KeycloakModelUtils.getClientScopeByName(realm, OIDCLoginProtocolFactory.ROLES_SCOPE);
        ClientScopeModel webOriginsScope = KeycloakModelUtils.getClientScopeByName(realm, OIDCLoginProtocolFactory.WEB_ORIGINS_SCOPE);
        return Arrays.asList(rolesScope, webOriginsScope)
                .stream()
                .collect(Collectors.toMap(ClientScopeModel::getName, clientScope -> clientScope));

    } else {
        ClientScopeModel offlineScope = KeycloakModelUtils.getClientScopeByName(realm, "offline_access");
        return Collections.singletonMap("offline_access", offlineScope);
    }
}
 
Example 6
Source File: TokenManager.java    From keycloak with Apache License 2.0 5 votes vote down vote up
protected AccessToken initToken(RealmModel realm, ClientModel client, UserModel user, UserSessionModel session,
                                ClientSessionContext clientSessionCtx, UriInfo uriInfo) {
    AccessToken token = new AccessToken();
    token.id(KeycloakModelUtils.generateId());
    token.type(TokenUtil.TOKEN_TYPE_BEARER);
    token.subject(user.getId());
    token.issuedNow();
    token.issuedFor(client.getClientId());

    AuthenticatedClientSessionModel clientSession = clientSessionCtx.getClientSession();
    token.issuer(clientSession.getNote(OIDCLoginProtocol.ISSUER));
    token.setNonce(clientSessionCtx.getAttribute(OIDCLoginProtocol.NONCE_PARAM, String.class));
    token.setScope(clientSessionCtx.getScopeString());

    // Best effort for "acr" value. Use 0 if clientSession was authenticated through cookie ( SSO )
    // TODO: Add better acr support. See KEYCLOAK-3314
    String acr = (AuthenticationManager.isSSOAuthentication(clientSession)) ? "0" : "1";
    token.setAcr(acr);

    String authTime = session.getNote(AuthenticationManager.AUTH_TIME);
    if (authTime != null) {
        token.setAuthTime(Integer.parseInt(authTime));
    }


    token.setSessionState(session.getId());
    ClientScopeModel offlineAccessScope = KeycloakModelUtils.getClientScopeByName(realm, OAuth2Constants.OFFLINE_ACCESS);
    boolean offlineTokenRequested = offlineAccessScope == null ? false
        : clientSessionCtx.getClientScopeIds().contains(offlineAccessScope.getId());
    token.expiration(getTokenExpiration(realm, client, session, clientSession, offlineTokenRequested));

    return token;
}
 
Example 7
Source File: TokenManager.java    From keycloak with Apache License 2.0 5 votes vote down vote up
public AccessTokenResponseBuilder generateRefreshToken() {
    if (accessToken == null) {
        throw new IllegalStateException("accessToken not set");
    }

    ClientScopeModel offlineAccessScope = KeycloakModelUtils.getClientScopeByName(realm, OAuth2Constants.OFFLINE_ACCESS);
    boolean offlineTokenRequested = offlineAccessScope==null ? false : clientSessionCtx.getClientScopeIds().contains(offlineAccessScope.getId());
    if (offlineTokenRequested) {
        UserSessionManager sessionManager = new UserSessionManager(session);
        if (!sessionManager.isOfflineTokenAllowed(clientSessionCtx)) {
            event.error(Errors.NOT_ALLOWED);
            throw new ErrorResponseException("not_allowed", "Offline tokens not allowed for the user or client", Response.Status.BAD_REQUEST);
        }

        refreshToken = new RefreshToken(accessToken);
        refreshToken.type(TokenUtil.TOKEN_TYPE_OFFLINE);
        if (realm.isOfflineSessionMaxLifespanEnabled())
            refreshToken.expiration(getOfflineExpiration());
        sessionManager.createOrUpdateOfflineSession(clientSessionCtx.getClientSession(), userSession);
    } else {
        refreshToken = new RefreshToken(accessToken);
        refreshToken.expiration(getRefreshExpiration());
    }
    refreshToken.id(KeycloakModelUtils.generateId());
    refreshToken.issuedNow();
    return this;
}
 
Example 8
Source File: UserConsentModelTest.java    From keycloak with Apache License 2.0 4 votes vote down vote up
private boolean isClientScopeGranted(RealmModel realm, String scopeName, UserConsentModel consentModel) {
    ClientScopeModel clientScope = KeycloakModelUtils.getClientScopeByName(realm, scopeName);
    return consentModel.isClientScopeGranted(clientScope);
}
 
Example 9
Source File: UserConsentWithUserStorageModelTest.java    From keycloak with Apache License 2.0 4 votes vote down vote up
private boolean isClientScopeGranted(RealmModel realm, String scopeName, UserConsentModel consentModel) {
    ClientScopeModel clientScope = KeycloakModelUtils.getClientScopeByName(realm, scopeName);
    return consentModel.isClientScopeGranted(clientScope);
}
 
Example 10
Source File: OIDCLoginProtocolFactory.java    From keycloak with Apache License 2.0 4 votes vote down vote up
@Override
protected void createDefaultClientScopesImpl(RealmModel newRealm) {
    //name, family_name, given_name, middle_name, nickname, preferred_username, profile, picture, website, gender, birthdate, zoneinfo, locale, and updated_at.
    ClientScopeModel profileScope = newRealm.addClientScope(OAuth2Constants.SCOPE_PROFILE);
    profileScope.setDescription("OpenID Connect built-in scope: profile");
    profileScope.setDisplayOnConsentScreen(true);
    profileScope.setConsentScreenText(PROFILE_SCOPE_CONSENT_TEXT);
    profileScope.setIncludeInTokenScope(true);
    profileScope.setProtocol(getId());
    profileScope.addProtocolMapper(builtins.get(FULL_NAME));
    profileScope.addProtocolMapper(builtins.get(FAMILY_NAME));
    profileScope.addProtocolMapper(builtins.get(GIVEN_NAME));
    profileScope.addProtocolMapper(builtins.get(MIDDLE_NAME));
    profileScope.addProtocolMapper(builtins.get(NICKNAME));
    profileScope.addProtocolMapper(builtins.get(USERNAME));
    profileScope.addProtocolMapper(builtins.get(PROFILE_CLAIM));
    profileScope.addProtocolMapper(builtins.get(PICTURE));
    profileScope.addProtocolMapper(builtins.get(WEBSITE));
    profileScope.addProtocolMapper(builtins.get(GENDER));
    profileScope.addProtocolMapper(builtins.get(BIRTHDATE));
    profileScope.addProtocolMapper(builtins.get(ZONEINFO));
    profileScope.addProtocolMapper(builtins.get(LOCALE));
    profileScope.addProtocolMapper(builtins.get(UPDATED_AT));

    ClientScopeModel emailScope = newRealm.addClientScope(OAuth2Constants.SCOPE_EMAIL);
    emailScope.setDescription("OpenID Connect built-in scope: email");
    emailScope.setDisplayOnConsentScreen(true);
    emailScope.setConsentScreenText(EMAIL_SCOPE_CONSENT_TEXT);
    emailScope.setIncludeInTokenScope(true);
    emailScope.setProtocol(getId());
    emailScope.addProtocolMapper(builtins.get(EMAIL));
    emailScope.addProtocolMapper(builtins.get(EMAIL_VERIFIED));

    ClientScopeModel addressScope = newRealm.addClientScope(OAuth2Constants.SCOPE_ADDRESS);
    addressScope.setDescription("OpenID Connect built-in scope: address");
    addressScope.setDisplayOnConsentScreen(true);
    addressScope.setConsentScreenText(ADDRESS_SCOPE_CONSENT_TEXT);
    addressScope.setIncludeInTokenScope(true);
    addressScope.setProtocol(getId());
    addressScope.addProtocolMapper(builtins.get(ADDRESS));

    ClientScopeModel phoneScope = newRealm.addClientScope(OAuth2Constants.SCOPE_PHONE);
    phoneScope.setDescription("OpenID Connect built-in scope: phone");
    phoneScope.setDisplayOnConsentScreen(true);
    phoneScope.setConsentScreenText(PHONE_SCOPE_CONSENT_TEXT);
    phoneScope.setIncludeInTokenScope(true);
    phoneScope.setProtocol(getId());
    phoneScope.addProtocolMapper(builtins.get(PHONE_NUMBER));
    phoneScope.addProtocolMapper(builtins.get(PHONE_NUMBER_VERIFIED));

    // 'profile' and 'email' will be default scopes for now. 'address' and 'phone' will be optional scopes
    newRealm.addDefaultClientScope(profileScope, true);
    newRealm.addDefaultClientScope(emailScope, true);
    newRealm.addDefaultClientScope(addressScope, false);
    newRealm.addDefaultClientScope(phoneScope, false);

    RoleModel offlineRole = newRealm.getRole(OAuth2Constants.OFFLINE_ACCESS);
    if (offlineRole != null) {
        ClientScopeModel offlineAccessScope = KeycloakModelUtils.getClientScopeByName(newRealm, OAuth2Constants.OFFLINE_ACCESS);
        if (offlineAccessScope == null) {
            DefaultClientScopes.createOfflineAccessClientScope(newRealm, offlineRole);
        }
    }

    addRolesClientScope(newRealm);
    addWebOriginsClientScope(newRealm);
    addMicroprofileJWTClientScope(newRealm);
}