Java Code Examples for org.keycloak.models.UserModel#hasRole()

The following examples show how to use org.keycloak.models.UserModel#hasRole() . 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: ConditionalRoleAuthenticator.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Override
public boolean matchCondition(AuthenticationFlowContext context) {
    UserModel user = context.getUser();
    RealmModel realm = context.getRealm();
    AuthenticatorConfigModel authConfig = context.getAuthenticatorConfig();
    if (user != null && authConfig!=null && authConfig.getConfig()!=null) {
        String requiredRole = authConfig.getConfig().get(ConditionalRoleAuthenticatorFactory.CONDITIONAL_USER_ROLE);
        RoleModel role = KeycloakModelUtils.getRoleFromString(realm, requiredRole);
        if (role == null) {
            logger.errorv("Invalid role name submitted: {0}", requiredRole);
            return false;
        }
        return user.hasRole(role);
    }
    return false;
}
 
Example 2
Source File: ClientRegistrationAuth.java    From keycloak with Apache License 2.0 6 votes vote down vote up
private boolean hasRoleInModel(String[] roles) {
    ClientModel roleNamespace;
    UserModel user = session.users().getUserById(jwt.getSubject(), realm);
    if (user == null) {
        return false;
    }
    if (realm.getName().equals(Config.getAdminRealm())) {
        roleNamespace = realm.getMasterAdminClient();
    } else {
        roleNamespace = realm.getClientByClientId(Constants.REALM_MANAGEMENT_CLIENT_ID);
    }
    for (String role : roles) {
        RoleModel roleModel = roleNamespace.getRole(role);
        if (user.hasRole(roleModel)) return true;
    }
    return false;
}
 
Example 3
Source File: ConditionalOtpFormAuthenticator.java    From keycloak with Apache License 2.0 5 votes vote down vote up
private boolean userHasRole(RealmModel realm, UserModel user, String roleName) {

        if (roleName == null) {
            return false;
        }

        RoleModel role = getRoleFromString(realm, roleName);
        if (role != null) {
            return user.hasRole(role);
        }
        return false;
    }
 
Example 4
Source File: AdminConsole.java    From keycloak with Apache License 2.0 5 votes vote down vote up
/**
 * Permission information
 *
 * @param headers
 * @return
 */
@Path("whoami")
@GET
@Produces(MediaType.APPLICATION_JSON)
@NoCache
public Response whoAmI(final @Context HttpHeaders headers) {
    RealmManager realmManager = new RealmManager(session);
    AuthenticationManager.AuthResult authResult = authManager.authenticateBearerToken(session, realm, session.getContext().getUri(), clientConnection, headers);
    if (authResult == null) {
        return Response.status(401).build();
    }
    UserModel user= authResult.getUser();
    String displayName;
    if ((user.getFirstName() != null && !user.getFirstName().trim().equals("")) || (user.getLastName() != null && !user.getLastName().trim().equals(""))) {
        displayName = user.getFirstName();
        if (user.getLastName() != null) {
            displayName = displayName != null ? displayName + " " + user.getLastName() : user.getLastName();
        }
    } else {
        displayName = user.getUsername();
    }

    RealmModel masterRealm = getAdminstrationRealm(realmManager);
    Map<String, Set<String>> realmAccess = new HashMap<String, Set<String>>();
    if (masterRealm == null)
        throw new NotFoundException("No realm found");
    boolean createRealm = false;
    if (realm.equals(masterRealm)) {
        logger.debug("setting up realm access for a master realm user");
        createRealm = user.hasRole(masterRealm.getRole(AdminRoles.CREATE_REALM));
        addMasterRealmAccess(realm, user, realmAccess);
    } else {
        logger.debug("setting up realm access for a realm user");
        addRealmAccess(realm, user, realmAccess);
    }

    Locale locale = session.getContext().resolveLocale(user);

    return Response.ok(new WhoAmI(user.getId(), realm.getName(), displayName, createRealm, realmAccess, locale)).build();
}
 
Example 5
Source File: AdminConsole.java    From keycloak with Apache License 2.0 5 votes vote down vote up
private void addRealmAccess(RealmModel realm, UserModel user, Map<String, Set<String>> realmAdminAccess) {
    RealmManager realmManager = new RealmManager(session);
    ClientModel realmAdminApp = realm.getClientByClientId(realmManager.getRealmAdminClientId(realm));
    Set<RoleModel> roles = realmAdminApp.getRoles();
    for (RoleModel role : roles) {
        if (!user.hasRole(role)) continue;
        if (!realmAdminAccess.containsKey(realm.getName())) {
            realmAdminAccess.put(realm.getName(), new HashSet<String>());
        }
        realmAdminAccess.get(realm.getName()).add(role.getName());
    }

}
 
Example 6
Source File: AdminConsole.java    From keycloak with Apache License 2.0 5 votes vote down vote up
private void addMasterRealmAccess(RealmModel masterRealm, UserModel user, Map<String, Set<String>> realmAdminAccess) {
    List<RealmModel> realms = session.realms().getRealms();
    for (RealmModel realm : realms) {
        ClientModel realmAdminApp = realm.getMasterAdminClient();
        Set<RoleModel> roles = realmAdminApp.getRoles();
        for (RoleModel role : roles) {
            if (!user.hasRole(role)) continue;
            if (!realmAdminAccess.containsKey(realm.getName())) {
                realmAdminAccess.put(realm.getName(), new HashSet<String>());
            }
            realmAdminAccess.get(realm.getName()).add(role.getName());
        }
    }
}
 
Example 7
Source File: IdentityBrokerService.java    From keycloak with Apache License 2.0 4 votes vote down vote up
private Response performAccountLinking(AuthenticationSessionModel authSession, UserSessionModel userSession, BrokeredIdentityContext context, FederatedIdentityModel newModel, UserModel federatedUser) {
    logger.debugf("Will try to link identity provider [%s] to user [%s]", context.getIdpConfig().getAlias(), userSession.getUser().getUsername());

    this.event.event(EventType.FEDERATED_IDENTITY_LINK);



    UserModel authenticatedUser = userSession.getUser();
    authSession.setAuthenticatedUser(authenticatedUser);

    if (federatedUser != null && !authenticatedUser.getId().equals(federatedUser.getId())) {
        return redirectToErrorWhenLinkingFailed(authSession, Messages.IDENTITY_PROVIDER_ALREADY_LINKED, context.getIdpConfig().getAlias());
    }

    if (!authenticatedUser.hasRole(this.realmModel.getClientByClientId(Constants.ACCOUNT_MANAGEMENT_CLIENT_ID).getRole(AccountRoles.MANAGE_ACCOUNT))) {
        return redirectToErrorPage(authSession, Response.Status.FORBIDDEN, Messages.INSUFFICIENT_PERMISSION);
    }

    if (!authenticatedUser.isEnabled()) {
        return redirectToErrorWhenLinkingFailed(authSession, Messages.ACCOUNT_DISABLED);
    }



    if (federatedUser != null) {
        if (context.getIdpConfig().isStoreToken()) {
            FederatedIdentityModel oldModel = this.session.users().getFederatedIdentity(federatedUser, context.getIdpConfig().getAlias(), this.realmModel);
            if (!ObjectUtil.isEqualOrBothNull(context.getToken(), oldModel.getToken())) {
                this.session.users().updateFederatedIdentity(this.realmModel, federatedUser, newModel);
                if (isDebugEnabled()) {
                    logger.debugf("Identity [%s] update with response from identity provider [%s].", federatedUser, context.getIdpConfig().getAlias());
                }
            }
        }
    } else {
        this.session.users().addFederatedIdentity(this.realmModel, authenticatedUser, newModel);
    }
    context.getIdp().authenticationFinished(authSession, context);

    AuthenticationManager.setClientScopesInSession(authSession);
    TokenManager.attachAuthenticationSession(session, userSession, authSession);

    if (isDebugEnabled()) {
        logger.debugf("Linking account [%s] from identity provider [%s] to user [%s].", newModel, context.getIdpConfig().getAlias(), authenticatedUser);
    }

    this.event.user(authenticatedUser)
            .detail(Details.USERNAME, authenticatedUser.getUsername())
            .detail(Details.IDENTITY_PROVIDER, newModel.getIdentityProvider())
            .detail(Details.IDENTITY_PROVIDER_USERNAME, newModel.getUserName())
            .success();

    // we do this to make sure that the parent IDP is logged out when this user session is complete.
    // But for the case when userSession was previously authenticated with broker1 and now is linked to another broker2, we shouldn't override broker1 notes with the broker2 for sure.
    // Maybe broker logout should be rather always skiped in case of broker-linking
    if (userSession.getNote(Details.IDENTITY_PROVIDER) == null) {
        userSession.setNote(Details.IDENTITY_PROVIDER, context.getIdpConfig().getAlias());
        userSession.setNote(Details.IDENTITY_PROVIDER_USERNAME, context.getUsername());
    }

    return Response.status(302).location(UriBuilder.fromUri(authSession.getRedirectUri()).build()).build();
}