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;
}
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;
});
}
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);
}
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);
});
}
}
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);
}
Aggregations