Search in sources :

Example 11 with RealmModel

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

the class UserResource method impersonate.

/**
 * Impersonate the user
 *
 * @return
 */
@Path("impersonation")
@POST
@NoCache
@Produces(MediaType.APPLICATION_JSON)
public Map<String, Object> impersonate() {
    ProfileHelper.requireFeature(Profile.Feature.IMPERSONATION);
    auth.users().requireImpersonate(user);
    RealmModel authenticatedRealm = auth.adminAuth().getRealm();
    // if same realm logout before impersonation
    boolean sameRealm = false;
    String sessionState = auth.adminAuth().getToken().getSessionState();
    if (authenticatedRealm.getId().equals(realm.getId()) && sessionState != null) {
        sameRealm = true;
        UserSessionModel userSession = session.sessions().getUserSession(authenticatedRealm, sessionState);
        AuthenticationManager.expireIdentityCookie(realm, session.getContext().getUri(), clientConnection);
        AuthenticationManager.expireRememberMeCookie(realm, session.getContext().getUri(), clientConnection);
        AuthenticationManager.backchannelLogout(session, authenticatedRealm, userSession, session.getContext().getUri(), clientConnection, headers, true);
    }
    EventBuilder event = new EventBuilder(realm, session, clientConnection);
    UserSessionModel userSession = session.sessions().createUserSession(realm, user, user.getUsername(), clientConnection.getRemoteAddr(), "impersonate", false, null, null);
    UserModel adminUser = auth.adminAuth().getUser();
    String impersonatorId = adminUser.getId();
    String impersonator = adminUser.getUsername();
    userSession.setNote(IMPERSONATOR_ID.toString(), impersonatorId);
    userSession.setNote(IMPERSONATOR_USERNAME.toString(), impersonator);
    AuthenticationManager.createLoginCookie(session, realm, userSession.getUser(), userSession, session.getContext().getUri(), clientConnection);
    URI redirect = AccountFormService.accountServiceBaseUrl(session.getContext().getUri()).build(realm.getName());
    Map<String, Object> result = new HashMap<>();
    result.put("sameRealm", sameRealm);
    result.put("redirect", redirect.toString());
    event.event(EventType.IMPERSONATE).session(userSession).user(user).detail(Details.IMPERSONATOR_REALM, authenticatedRealm.getName()).detail(Details.IMPERSONATOR, impersonator).success();
    return result;
}
Also used : RealmModel(org.keycloak.models.RealmModel) UserModel(org.keycloak.models.UserModel) UserSessionModel(org.keycloak.models.UserSessionModel) EventBuilder(org.keycloak.events.EventBuilder) HashMap(java.util.HashMap) URI(java.net.URI) Path(javax.ws.rs.Path) POST(javax.ws.rs.POST) Produces(javax.ws.rs.Produces) NoCache(org.jboss.resteasy.annotations.cache.NoCache)

Example 12 with RealmModel

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

the class UsersResource method toRepresentation.

private Stream<UserRepresentation> toRepresentation(RealmModel realm, UserPermissionEvaluator usersEvaluator, Boolean briefRepresentation, Stream<UserModel> userModels) {
    boolean briefRepresentationB = briefRepresentation != null && briefRepresentation;
    boolean canViewGlobal = usersEvaluator.canView();
    usersEvaluator.grantIfNoPermission(session.getAttribute(UserModel.GROUPS) != null);
    return userModels.filter(user -> canViewGlobal || usersEvaluator.canView(user)).map(user -> {
        UserRepresentation userRep = briefRepresentationB ? ModelToRepresentation.toBriefRepresentation(user) : ModelToRepresentation.toRepresentation(session, realm, user);
        userRep.setAccess(usersEvaluator.getAccess(user));
        return userRep;
    });
}
Also used : ResourceType(org.keycloak.events.admin.ResourceType) Produces(javax.ws.rs.Produces) PasswordPolicyNotMetException(org.keycloak.policy.PasswordPolicyNotMetException) Path(javax.ws.rs.Path) USER_API(org.keycloak.userprofile.UserProfileContext.USER_API) RepresentationToModel(org.keycloak.models.utils.RepresentationToModel) MediaType(javax.ws.rs.core.MediaType) QueryParam(javax.ws.rs.QueryParam) Consumes(javax.ws.rs.Consumes) Map(java.util.Map) ClientConnection(org.keycloak.common.ClientConnection) RealmModel(org.keycloak.models.RealmModel) Context(javax.ws.rs.core.Context) Set(java.util.Set) Collectors(java.util.stream.Collectors) NotFoundException(javax.ws.rs.NotFoundException) KeycloakModelUtils.findGroupByPath(org.keycloak.models.utils.KeycloakModelUtils.findGroupByPath) Objects(java.util.Objects) ModelToRepresentation(org.keycloak.models.utils.ModelToRepresentation) List(java.util.List) HttpHeaders(javax.ws.rs.core.HttpHeaders) Stream(java.util.stream.Stream) Response(javax.ws.rs.core.Response) ForbiddenException(org.keycloak.services.ForbiddenException) Optional(java.util.Optional) SearchQueryUtils(org.keycloak.utils.SearchQueryUtils) OperationType(org.keycloak.events.admin.OperationType) UserProfile(org.keycloak.userprofile.UserProfile) PathParam(javax.ws.rs.PathParam) UserPermissionEvaluator(org.keycloak.services.resources.admin.permissions.UserPermissionEvaluator) Profile(org.keycloak.common.Profile) KeycloakModelUtils(org.keycloak.models.utils.KeycloakModelUtils) GET(javax.ws.rs.GET) Logger(org.jboss.logging.Logger) Constants(org.keycloak.models.Constants) HashMap(java.util.HashMap) ObjectUtil(org.keycloak.common.util.ObjectUtil) ResteasyProviderFactory(org.jboss.resteasy.spi.ResteasyProviderFactory) UserModel(org.keycloak.models.UserModel) UserProfileProvider(org.keycloak.userprofile.UserProfileProvider) GroupModel(org.keycloak.models.GroupModel) UserRepresentation(org.keycloak.representations.idm.UserRepresentation) POST(javax.ws.rs.POST) AdminPermissionEvaluator(org.keycloak.services.resources.admin.permissions.AdminPermissionEvaluator) KeycloakSession(org.keycloak.models.KeycloakSession) NoCache(org.jboss.resteasy.annotations.cache.NoCache) ModelException(org.keycloak.models.ModelException) ModelDuplicateException(org.keycloak.models.ModelDuplicateException) Collections(java.util.Collections) ErrorResponse(org.keycloak.services.ErrorResponse) UserRepresentation(org.keycloak.representations.idm.UserRepresentation)

Example 13 with RealmModel

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

the class BrokerLinkAndTokenExchangeTest method turnOnTokenStore.

public static void turnOnTokenStore(KeycloakSession session) {
    RealmModel realm = session.realms().getRealmByName(CHILD_IDP);
    IdentityProviderModel idp = realm.getIdentityProviderByAlias(PARENT_IDP);
    idp.setStoreToken(true);
    realm.updateIdentityProvider(idp);
}
Also used : RealmModel(org.keycloak.models.RealmModel) IdentityProviderModel(org.keycloak.models.IdentityProviderModel)

Example 14 with RealmModel

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

the class RefreshTokenTest method refreshTokenAfterUserAdminLogoutEndpointAndLoginAgain.

@Test
@AuthServerContainerExclude(AuthServerContainerExclude.AuthServer.REMOTE)
public void refreshTokenAfterUserAdminLogoutEndpointAndLoginAgain() {
    try {
        String refreshToken1 = loginAndForceNewLoginPage();
        RefreshToken refreshTokenParsed1 = oauth.parseRefreshToken(refreshToken1);
        String userId = refreshTokenParsed1.getSubject();
        UserResource user = adminClient.realm("test").users().get(userId);
        user.logout();
        // Set time offset to 2 (Just to simulate to be more close to real situation)
        setTimeOffset(2);
        // Continue with login
        WaitUtils.waitForPageToLoad();
        loginPage.login("password");
        assertFalse(loginPage.isCurrent());
        OAuthClient.AccessTokenResponse tokenResponse2 = null;
        String code = oauth.getCurrentQuery().get(OAuth2Constants.CODE);
        tokenResponse2 = oauth.doAccessTokenRequest(code, "password");
        setTimeOffset(4);
        // Now try refresh with the original refreshToken1 created in logged-out userSession. It should fail
        OAuthClient.AccessTokenResponse responseReuseExceeded = oauth.doRefreshTokenRequest(refreshToken1, "password");
        assertEquals(400, responseReuseExceeded.getStatusCode());
        setTimeOffset(6);
        // Finally try with valid refresh token
        responseReuseExceeded = oauth.doRefreshTokenRequest(tokenResponse2.getRefreshToken(), "password");
        assertEquals(200, responseReuseExceeded.getStatusCode());
    } finally {
        // Need to reset not-before of user, which was updated during user.logout()
        testingClient.server().run(session -> {
            RealmModel realm = session.realms().getRealmByName("test");
            UserModel user = session.users().getUserByUsername(realm, "test-user@localhost");
            session.users().setNotBeforeForUser(realm, user, 0);
        });
    }
}
Also used : RealmModel(org.keycloak.models.RealmModel) UserModel(org.keycloak.models.UserModel) RefreshToken(org.keycloak.representations.RefreshToken) OAuthClient(org.keycloak.testsuite.util.OAuthClient) UserResource(org.keycloak.admin.client.resource.UserResource) AuthServerContainerExclude(org.keycloak.testsuite.arquillian.annotation.AuthServerContainerExclude) AbstractKeycloakTest(org.keycloak.testsuite.AbstractKeycloakTest) Test(org.junit.Test)

Example 15 with RealmModel

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

the class ClientTokenExchangeSAML2Test method addDirectExchanger.

private static void addDirectExchanger(KeycloakSession session) {
    RealmModel realm = session.realms().getRealmByName(TEST);
    RoleModel exampleRole = realm.addRole("example");
    AdminPermissionManagement management = AdminPermissions.management(session, realm);
    ClientModel directExchanger = realm.addClient("direct-exchanger");
    directExchanger.setName("direct-exchanger");
    directExchanger.setClientId("direct-exchanger");
    directExchanger.setPublicClient(false);
    directExchanger.setDirectAccessGrantsEnabled(true);
    directExchanger.setEnabled(true);
    directExchanger.setSecret("secret");
    directExchanger.setProtocol(OIDCLoginProtocol.LOGIN_PROTOCOL);
    directExchanger.setFullScopeAllowed(false);
    // permission for client to client exchange to "target" client
    management.clients().setPermissionsEnabled(realm.getClientByClientId(SAML_SIGNED_TARGET), true);
    management.clients().setPermissionsEnabled(realm.getClientByClientId(SAML_ENCRYPTED_TARGET), true);
    management.clients().setPermissionsEnabled(realm.getClientByClientId(SAML_SIGNED_AND_ENCRYPTED_TARGET), true);
    management.clients().setPermissionsEnabled(realm.getClientByClientId(SAML_UNSIGNED_AND_UNENCRYPTED_TARGET), true);
    ClientPolicyRepresentation clientImpersonateRep = new ClientPolicyRepresentation();
    clientImpersonateRep.setName("clientImpersonatorsDirect");
    clientImpersonateRep.addClient(directExchanger.getId());
    ResourceServer server = management.realmResourceServer();
    Policy clientImpersonatePolicy = management.authz().getStoreFactory().getPolicyStore().create(clientImpersonateRep, server);
    management.users().setPermissionsEnabled(true);
    management.users().adminImpersonatingPermission().addAssociatedPolicy(clientImpersonatePolicy);
    management.users().adminImpersonatingPermission().setDecisionStrategy(DecisionStrategy.AFFIRMATIVE);
    UserModel impersonatedUser = session.users().addUser(realm, "impersonated-user");
    impersonatedUser.setEnabled(true);
    session.userCredentialManager().updateCredential(realm, impersonatedUser, UserCredentialModel.password("password"));
    impersonatedUser.grantRole(exampleRole);
}
Also used : RealmModel(org.keycloak.models.RealmModel) Policy(org.keycloak.authorization.model.Policy) UserModel(org.keycloak.models.UserModel) ClientModel(org.keycloak.models.ClientModel) ClientPolicyRepresentation(org.keycloak.representations.idm.authorization.ClientPolicyRepresentation) RoleModel(org.keycloak.models.RoleModel) ResourceServer(org.keycloak.authorization.model.ResourceServer) AdminPermissionManagement(org.keycloak.services.resources.admin.permissions.AdminPermissionManagement)

Aggregations

RealmModel (org.keycloak.models.RealmModel)591 Test (org.junit.Test)249 UserModel (org.keycloak.models.UserModel)225 KeycloakSession (org.keycloak.models.KeycloakSession)152 ClientModel (org.keycloak.models.ClientModel)149 AbstractTestRealmKeycloakTest (org.keycloak.testsuite.AbstractTestRealmKeycloakTest)90 ModelTest (org.keycloak.testsuite.arquillian.annotation.ModelTest)84 ComponentModel (org.keycloak.component.ComponentModel)83 RoleModel (org.keycloak.models.RoleModel)73 UserSessionModel (org.keycloak.models.UserSessionModel)64 LDAPObject (org.keycloak.storage.ldap.idm.model.LDAPObject)62 List (java.util.List)55 LDAPStorageProvider (org.keycloak.storage.ldap.LDAPStorageProvider)51 GroupModel (org.keycloak.models.GroupModel)47 HashMap (java.util.HashMap)38 Collectors (java.util.stream.Collectors)34 CachedUserModel (org.keycloak.models.cache.CachedUserModel)34 Path (javax.ws.rs.Path)30 AbstractAuthTest (org.keycloak.testsuite.AbstractAuthTest)30 Map (java.util.Map)29