use of org.keycloak.services.managers.ClientManager in project keycloak by keycloak.
the class AdapterInstallationClientRegistrationProvider method get.
@GET
@Path("{clientId}")
@Produces(MediaType.APPLICATION_JSON)
public Response get(@PathParam("clientId") String clientId) {
event.event(EventType.CLIENT_INFO);
ClientModel client = session.getContext().getRealm().getClientByClientId(clientId);
auth.requireView(client, true);
ClientManager clientManager = new ClientManager(new RealmManager(session));
Object rep = clientManager.toInstallationRepresentation(session.getContext().getRealm(), client, session.getContext().getUri().getBaseUri());
event.client(client.getClientId()).success();
return Response.ok(rep).build();
}
use of org.keycloak.services.managers.ClientManager in project keycloak by keycloak.
the class AbstractClientRegistrationProvider method create.
public ClientRepresentation create(ClientRegistrationContext context) {
ClientRepresentation client = context.getClient();
event.event(EventType.CLIENT_REGISTER);
RegistrationAuth registrationAuth = auth.requireCreate(context);
try {
RealmModel realm = session.getContext().getRealm();
ClientModel clientModel = ClientManager.createClient(session, realm, client);
if (client.getDefaultRoles() != null) {
for (String name : client.getDefaultRoles()) {
clientModel.addDefaultRole(name);
}
}
if (clientModel.isServiceAccountsEnabled()) {
new ClientManager(new RealmManager(session)).enableServiceAccount(clientModel);
}
if (Boolean.TRUE.equals(client.getAuthorizationServicesEnabled())) {
RepresentationToModel.createResourceServer(clientModel, session, true);
}
session.clientPolicy().triggerOnEvent(new DynamicClientRegisteredContext(context, clientModel, auth.getJwt(), realm));
ClientRegistrationPolicyManager.triggerAfterRegister(context, registrationAuth, clientModel);
client = ModelToRepresentation.toRepresentation(clientModel, session);
client.setSecret(clientModel.getSecret());
String registrationAccessToken = ClientRegistrationTokenUtils.updateRegistrationAccessToken(session, clientModel, registrationAuth);
client.setRegistrationAccessToken(registrationAccessToken);
if (auth.isInitialAccessToken()) {
ClientInitialAccessModel initialAccessModel = auth.getInitialAccessModel();
session.realms().decreaseRemainingCount(realm, initialAccessModel);
}
client.setDirectAccessGrantsEnabled(false);
Stream<String> defaultRolesNames = clientModel.getDefaultRolesStream();
if (defaultRolesNames != null) {
client.setDefaultRoles(defaultRolesNames.toArray(String[]::new));
}
event.client(client.getClientId()).success();
return client;
} catch (ModelDuplicateException e) {
throw new ErrorResponseException(ErrorCodes.INVALID_CLIENT_METADATA, "Client Identifier in use", Response.Status.BAD_REQUEST);
} catch (ClientPolicyException cpe) {
throw new ErrorResponseException(cpe.getError(), cpe.getErrorDetail(), Response.Status.BAD_REQUEST);
}
}
use of org.keycloak.services.managers.ClientManager in project keycloak by keycloak.
the class TokenEndpoint method clientCredentialsGrant.
public Response clientCredentialsGrant() {
if (client.isBearerOnly()) {
event.error(Errors.INVALID_CLIENT);
throw new CorsErrorResponseException(cors, OAuthErrorException.UNAUTHORIZED_CLIENT, "Bearer-only client not allowed to retrieve service account", Response.Status.UNAUTHORIZED);
}
if (client.isPublicClient()) {
event.error(Errors.INVALID_CLIENT);
throw new CorsErrorResponseException(cors, OAuthErrorException.UNAUTHORIZED_CLIENT, "Public client not allowed to retrieve service account", Response.Status.UNAUTHORIZED);
}
if (!client.isServiceAccountsEnabled()) {
event.error(Errors.INVALID_CLIENT);
throw new CorsErrorResponseException(cors, OAuthErrorException.UNAUTHORIZED_CLIENT, "Client not enabled to retrieve service account", Response.Status.UNAUTHORIZED);
}
UserModel clientUser = session.users().getServiceAccount(client);
if (clientUser == null || client.getProtocolMapperByName(OIDCLoginProtocol.LOGIN_PROTOCOL, ServiceAccountConstants.CLIENT_ID_PROTOCOL_MAPPER) == null) {
// May need to handle bootstrap here as well
logger.debugf("Service account user for client '%s' not found or default protocol mapper for service account not found. Creating now", client.getClientId());
new ClientManager(new RealmManager(session)).enableServiceAccount(client);
clientUser = session.users().getServiceAccount(client);
}
String clientUsername = clientUser.getUsername();
event.detail(Details.USERNAME, clientUsername);
event.user(clientUser);
if (!clientUser.isEnabled()) {
event.error(Errors.USER_DISABLED);
throw new CorsErrorResponseException(cors, OAuthErrorException.INVALID_REQUEST, "User '" + clientUsername + "' disabled", Response.Status.UNAUTHORIZED);
}
String scope = getRequestedScopes();
RootAuthenticationSessionModel rootAuthSession = new AuthenticationSessionManager(session).createAuthenticationSession(realm, false);
AuthenticationSessionModel authSession = rootAuthSession.createAuthenticationSession(client);
authSession.setAuthenticatedUser(clientUser);
authSession.setProtocol(OIDCLoginProtocol.LOGIN_PROTOCOL);
authSession.setClientNote(OIDCLoginProtocol.ISSUER, Urls.realmIssuer(session.getContext().getUri().getBaseUri(), realm.getName()));
authSession.setClientNote(OIDCLoginProtocol.SCOPE_PARAM, scope);
// persisting of userSession by default
UserSessionModel.SessionPersistenceState sessionPersistenceState = UserSessionModel.SessionPersistenceState.PERSISTENT;
boolean useRefreshToken = OIDCAdvancedConfigWrapper.fromClientModel(client).isUseRefreshTokenForClientCredentialsGrant();
if (!useRefreshToken) {
// we don't want to store a session hence we mark it as transient, see KEYCLOAK-9551
sessionPersistenceState = UserSessionModel.SessionPersistenceState.TRANSIENT;
}
UserSessionModel userSession = session.sessions().createUserSession(authSession.getParentSession().getId(), realm, clientUser, clientUsername, clientConnection.getRemoteAddr(), ServiceAccountConstants.CLIENT_AUTH, false, null, null, sessionPersistenceState);
event.session(userSession);
AuthenticationManager.setClientScopesInSession(authSession);
ClientSessionContext clientSessionCtx = TokenManager.attachAuthenticationSession(session, userSession, authSession);
// Notes about client details
userSession.setNote(ServiceAccountConstants.CLIENT_ID, client.getClientId());
userSession.setNote(ServiceAccountConstants.CLIENT_HOST, clientConnection.getRemoteHost());
userSession.setNote(ServiceAccountConstants.CLIENT_ADDRESS, clientConnection.getRemoteAddr());
try {
session.clientPolicy().triggerOnEvent(new ServiceAccountTokenRequestContext(formParams, clientSessionCtx.getClientSession()));
} catch (ClientPolicyException cpe) {
event.error(cpe.getError());
throw new CorsErrorResponseException(cors, cpe.getError(), cpe.getErrorDetail(), Response.Status.BAD_REQUEST);
}
updateUserSessionFromClientAuth(userSession);
TokenManager.AccessTokenResponseBuilder responseBuilder = tokenManager.responseBuilder(realm, client, event, session, userSession, clientSessionCtx).generateAccessToken();
// Make refresh token generation optional, see KEYCLOAK-9551
if (useRefreshToken) {
responseBuilder = responseBuilder.generateRefreshToken();
} else {
responseBuilder.getAccessToken().setSessionState(null);
}
checkMtlsHoKToken(responseBuilder, useRefreshToken);
String scopeParam = clientSessionCtx.getClientSession().getNote(OAuth2Constants.SCOPE);
if (TokenUtil.isOIDCRequest(scopeParam)) {
responseBuilder.generateIDToken().generateAccessTokenHash();
}
// TODO : do the same as codeToToken()
AccessTokenResponse res = responseBuilder.build();
event.success();
return cors.builder(Response.ok(res, MediaType.APPLICATION_JSON_TYPE)).build();
}
use of org.keycloak.services.managers.ClientManager in project keycloak by keycloak.
the class UserSessionProviderOfflineTest method testOnClientRemoved.
@Test
@ModelTest
public void testOnClientRemoved(KeycloakSession session) {
KeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession sessionCR) -> {
try {
int started = Time.currentTime();
AtomicReference<String> userSessionID = new AtomicReference<>();
KeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession sessionCR1) -> {
currentSession = sessionCR1;
sessionManager = new UserSessionManager(currentSession);
RealmModel fooRealm = currentSession.realms().createRealm("foo", "foo");
fooRealm.setDefaultRole(currentSession.roles().addRealmRole(fooRealm, Constants.DEFAULT_ROLES_ROLE_PREFIX + "-" + fooRealm.getName()));
fooRealm.setSsoSessionIdleTimeout(1800);
fooRealm.setSsoSessionMaxLifespan(36000);
fooRealm.setOfflineSessionIdleTimeout(2592000);
fooRealm.setOfflineSessionMaxLifespan(5184000);
fooRealm.addClient("foo-app");
fooRealm.addClient("bar-app");
currentSession.users().addUser(fooRealm, "user3");
UserSessionModel userSession = currentSession.sessions().createUserSession(fooRealm, currentSession.users().getUserByUsername(fooRealm, "user3"), "user3", "127.0.0.1", "form", true, null, null);
userSessionID.set(userSession.getId());
createClientSession(currentSession, fooRealm.getClientByClientId("foo-app"), userSession, "http://redirect", "state");
createClientSession(currentSession, fooRealm.getClientByClientId("bar-app"), userSession, "http://redirect", "state");
});
KeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession sessionCR2) -> {
currentSession = sessionCR2;
// Create offline currentSession
RealmModel fooRealm = currentSession.realms().getRealm("foo");
UserSessionModel userSession = currentSession.sessions().getUserSession(fooRealm, userSessionID.get());
createOfflineSessionIncludeClientSessions(currentSession, userSession);
});
KeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession sessionCR3) -> {
currentSession = sessionCR3;
RealmManager realmMgr = new RealmManager(currentSession);
ClientManager clientMgr = new ClientManager(realmMgr);
RealmModel fooRealm = realmMgr.getRealm("foo");
// Assert currentSession was persisted with both clientSessions
UserSessionModel offlineSession = currentSession.sessions().getOfflineUserSession(fooRealm, userSessionID.get());
assertSession(offlineSession, currentSession.users().getUserByUsername(fooRealm, "user3"), "127.0.0.1", started, started, "foo-app", "bar-app");
// Remove foo-app client
ClientModel client = fooRealm.getClientByClientId("foo-app");
clientMgr.removeClient(fooRealm, client);
});
KeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession sessionCR4) -> {
currentSession = sessionCR4;
RealmManager realmMgr = new RealmManager(currentSession);
ClientManager clientMgr = new ClientManager(realmMgr);
RealmModel fooRealm = realmMgr.getRealm("foo");
// Assert just one bar-app clientSession persisted now
UserSessionModel offlineSession = currentSession.sessions().getOfflineUserSession(fooRealm, userSessionID.get());
Assert.assertEquals(1, offlineSession.getAuthenticatedClientSessions().size());
Assert.assertEquals("bar-app", offlineSession.getAuthenticatedClientSessions().values().iterator().next().getClient().getClientId());
// Remove bar-app client
ClientModel client = fooRealm.getClientByClientId("bar-app");
clientMgr.removeClient(fooRealm, client);
});
KeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession sessionCR5) -> {
currentSession = sessionCR5;
// Assert nothing loaded - userSession was removed as well because it was last userSession
RealmManager realmMgr = new RealmManager(currentSession);
RealmModel fooRealm = realmMgr.getRealm("foo");
UserSessionModel offlineSession = currentSession.sessions().getOfflineUserSession(fooRealm, userSessionID.get());
Assert.assertEquals(0, offlineSession.getAuthenticatedClientSessions().size());
});
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
KeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession sessionTearDown) -> {
currentSession = sessionTearDown;
RealmManager realmMgr = new RealmManager(currentSession);
RealmModel fooRealm = realmMgr.getRealm("foo");
UserModel user3 = currentSession.users().getUserByUsername(fooRealm, "user3");
// Remove user3
new UserManager(currentSession).removeUser(fooRealm, user3);
// Cleanup
realmMgr = new RealmManager(currentSession);
realmMgr.removeRealm(realmMgr.getRealm("foo"));
});
}
});
}
use of org.keycloak.services.managers.ClientManager in project keycloak by keycloak.
the class AuthenticationSessionProviderTest method testOnClientRemoved.
@Test
@ModelTest
public void testOnClientRemoved(KeycloakSession session) {
AtomicReference<String> tab1ID = new AtomicReference<>();
AtomicReference<String> tab2ID = new AtomicReference<>();
AtomicReference<String> authSessionID = new AtomicReference<>();
KeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession sesRealmRemoved1) -> {
KeycloakSession currentSession = sesRealmRemoved1;
RealmModel realm = currentSession.realms().getRealm("test");
authSessionID.set(currentSession.authenticationSessions().createRootAuthenticationSession(realm).getId());
AuthenticationSessionModel authSession1 = currentSession.authenticationSessions().getRootAuthenticationSession(realm, authSessionID.get()).createAuthenticationSession(realm.getClientByClientId("test-app"));
AuthenticationSessionModel authSession2 = currentSession.authenticationSessions().getRootAuthenticationSession(realm, authSessionID.get()).createAuthenticationSession(realm.getClientByClientId("third-party"));
tab1ID.set(authSession1.getTabId());
tab2ID.set(authSession2.getTabId());
authSession1.setAuthNote("foo", "bar");
authSession2.setAuthNote("foo", "baz");
});
KeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession sesRealmRemoved1) -> {
KeycloakSession currentSession = sesRealmRemoved1;
RealmModel realm = currentSession.realms().getRealm("test");
RootAuthenticationSessionModel rootAuthSession = currentSession.authenticationSessions().getRootAuthenticationSession(realm, authSessionID.get());
assertThat(rootAuthSession.getAuthenticationSessions().size(), is(2));
assertThat(rootAuthSession.getAuthenticationSession(realm.getClientByClientId("test-app"), tab1ID.get()).getAuthNote("foo"), is("bar"));
assertThat(rootAuthSession.getAuthenticationSession(realm.getClientByClientId("third-party"), tab2ID.get()).getAuthNote("foo"), is("baz"));
new ClientManager(new RealmManager(currentSession)).removeClient(realm, realm.getClientByClientId("third-party"));
});
KeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession sesRealmRemoved1) -> {
KeycloakSession currentSession = sesRealmRemoved1;
RealmModel realm = currentSession.realms().getRealm("test");
RootAuthenticationSessionModel rootAuthSession = currentSession.authenticationSessions().getRootAuthenticationSession(realm, authSessionID.get());
assertThat(rootAuthSession.getAuthenticationSession(realm.getClientByClientId("test-app"), tab1ID.get()).getAuthNote("foo"), is("bar"));
assertThat(rootAuthSession.getAuthenticationSession(realm.getClientByClientId("third-party"), tab2ID.get()), nullValue());
// Revert client
realm.addClient("third-party");
});
}
Aggregations