use of org.keycloak.models.ClientScopeModel in project keycloak by keycloak.
the class ClientScopePolicyProviderFactory method onExport.
@Override
public void onExport(Policy policy, PolicyRepresentation representation, AuthorizationProvider authorizationProvider) {
Map<String, String> config = new HashMap<>();
Set<ClientScopePolicyRepresentation.ClientScopeDefinition> clientScopes = toRepresentation(policy, authorizationProvider).getClientScopes();
for (ClientScopePolicyRepresentation.ClientScopeDefinition clientScopeDefinition : clientScopes) {
ClientScopeModel clientScope = authorizationProvider.getRealm().getClientScopeById(clientScopeDefinition.getId());
clientScopeDefinition.setId(clientScope.getName());
}
try {
config.put("clientScopes", JsonSerialization.writeValueAsString(clientScopes));
} catch (IOException e) {
throw new RuntimeException("Failed to export client scope policy [" + policy.getName() + "]", e);
}
representation.setConfig(config);
}
use of org.keycloak.models.ClientScopeModel in project keycloak by keycloak.
the class CibaGrantType method createUserSession.
private UserSessionModel createUserSession(CIBAAuthenticationRequest request, Map<String, String> additionalParams) {
RootAuthenticationSessionModel rootAuthSession = session.authenticationSessions().createRootAuthenticationSession(realm);
// here Client Model of CD(Consumption Device) needs to be used to bind its Client Session with User Session.
AuthenticationSessionModel authSession = rootAuthSession.createAuthenticationSession(client);
authSession.setProtocol(OIDCLoginProtocol.LOGIN_PROTOCOL);
authSession.setAction(AuthenticatedClientSessionModel.Action.AUTHENTICATE.name());
authSession.setClientNote(OIDCLoginProtocol.ISSUER, Urls.realmIssuer(session.getContext().getUri().getBaseUri(), realm.getName()));
authSession.setClientNote(OIDCLoginProtocol.SCOPE_PARAM, request.getScope());
if (additionalParams != null) {
for (String paramName : additionalParams.keySet()) {
authSession.setClientNote(ADDITIONAL_CALLBACK_PARAMS_PREFIX + paramName, additionalParams.get(paramName));
}
}
if (request.getOtherClaims() != null) {
for (String paramName : request.getOtherClaims().keySet()) {
authSession.setClientNote(ADDITIONAL_BACKCHANNEL_REQ_PARAMS_PREFIX + paramName, request.getOtherClaims().get(paramName).toString());
}
}
UserModel user = session.users().getUserById(realm, request.getSubject());
if (user == null) {
event.error(Errors.USERNAME_MISSING);
throw new ErrorResponseException(OAuthErrorException.INVALID_GRANT, "Could not identify user", Response.Status.BAD_REQUEST);
}
if (!user.isEnabled()) {
event.error(Errors.USER_DISABLED);
throw new CorsErrorResponseException(cors, OAuthErrorException.INVALID_GRANT, "User disabled", Response.Status.BAD_REQUEST);
}
logger.debugf("CIBA Grant :: user model found. user.getId() = %s, user.getEmail() = %s, user.getUsername() = %s.", user.getId(), user.getEmail(), user.getUsername());
authSession.setAuthenticatedUser(user);
if (user.getRequiredActionsStream().count() > 0) {
event.error(Errors.RESOLVE_REQUIRED_ACTIONS);
throw new ErrorResponseException(OAuthErrorException.INVALID_GRANT, "Account is not fully set up", Response.Status.BAD_REQUEST);
}
AuthenticationManager.setClientScopesInSession(authSession);
ClientSessionContext context = AuthenticationProcessor.attachSession(authSession, null, session, realm, session.getContext().getConnection(), event);
UserSessionModel userSession = context.getClientSession().getUserSession();
if (userSession == null) {
event.error(Errors.USER_SESSION_NOT_FOUND);
throw new ErrorResponseException(OAuthErrorException.INVALID_GRANT, "User session is not found", Response.Status.BAD_REQUEST);
}
// authorization (consent)
UserConsentModel grantedConsent = session.users().getConsentByClient(realm, user.getId(), client.getId());
if (grantedConsent == null) {
grantedConsent = new UserConsentModel(client);
session.users().addConsent(realm, user.getId(), grantedConsent);
if (logger.isTraceEnabled()) {
grantedConsent.getGrantedClientScopes().forEach(i -> logger.tracef("CIBA Grant :: Consent granted. %s", i.getName()));
}
}
boolean updateConsentRequired = false;
for (String clientScopeId : authSession.getClientScopes()) {
ClientScopeModel clientScope = KeycloakModelUtils.findClientScopeById(realm, client, clientScopeId);
if (clientScope != null && !grantedConsent.isClientScopeGranted(clientScope) && clientScope.isDisplayOnConsentScreen()) {
grantedConsent.addGrantedClientScope(clientScope);
updateConsentRequired = true;
}
}
if (updateConsentRequired) {
session.users().updateConsent(realm, user.getId(), grantedConsent);
if (logger.isTraceEnabled()) {
grantedConsent.getGrantedClientScopes().forEach(i -> logger.tracef("CIBA Grant :: Consent updated. %s", i.getName()));
}
}
event.detail(Details.CONSENT, Details.CONSENT_VALUE_CONSENT_GRANTED);
event.detail(Details.CODE_ID, userSession.getId());
event.session(userSession.getId());
event.user(user);
logger.debugf("Successfully verified Authe Req Id '%s'. User session: '%s', client: '%s'", request, userSession.getId(), client.getId());
return userSession;
}
use of org.keycloak.models.ClientScopeModel in project keycloak by keycloak.
the class MapUserProvider method updateConsent.
@Override
public void updateConsent(RealmModel realm, String userId, UserConsentModel consent) {
LOG.tracef("updateConsent(%s, %s, %s)%s", realm, userId, consent, getShortStackTrace());
MapUserEntity user = getEntityByIdOrThrow(realm, userId);
MapUserConsentEntity userConsentEntity = user.getUserConsent(consent.getClient().getId()).orElseThrow(() -> new ModelException("Consent not found for client [" + consent.getClient().getId() + "] and user [" + userId + "]"));
userConsentEntity.setGrantedClientScopesIds(consent.getGrantedClientScopes().stream().map(ClientScopeModel::getId).collect(Collectors.toSet()));
userConsentEntity.setLastUpdatedDate(Time.currentTimeMillis());
}
use of org.keycloak.models.ClientScopeModel in project keycloak by keycloak.
the class ApplicationsBean method toApplicationEntry.
/**
* Constructs a {@link ApplicationEntry} from the specified parameters.
*
* @param session a reference to the {@code Keycloak} session.
* @param realm a reference to the realm.
* @param user a reference to the user.
* @param client a reference to the client that contains the applications.
* @param offlineClients a {@link Set} containing the offline clients.
* @return the constructed {@link ApplicationEntry} instance or {@code null} if the user can't access the applications
* in the specified client.
*/
private ApplicationEntry toApplicationEntry(final KeycloakSession session, final RealmModel realm, final UserModel user, final ClientModel client, final Set<ClientModel> offlineClients) {
// Construct scope parameter with all optional scopes to see all potentially available roles
Stream<ClientScopeModel> allClientScopes = Stream.concat(client.getClientScopes(true).values().stream(), client.getClientScopes(false).values().stream());
allClientScopes = Stream.concat(allClientScopes, Stream.of(client)).distinct();
Set<RoleModel> availableRoles = TokenManager.getAccess(user, client, allClientScopes);
// unless this is can be changed by approving/revoking consent
if (!isAdminClient(client) && availableRoles.isEmpty() && !client.isConsentRequired()) {
return null;
}
List<RoleModel> realmRolesAvailable = new LinkedList<>();
MultivaluedHashMap<String, ClientRoleEntry> resourceRolesAvailable = new MultivaluedHashMap<>();
processRoles(availableRoles, realmRolesAvailable, resourceRolesAvailable);
List<ClientScopeModel> orderedScopes = new LinkedList<>();
if (client.isConsentRequired()) {
UserConsentModel consent = session.users().getConsentByClient(realm, user.getId(), client.getId());
if (consent != null) {
orderedScopes.addAll(consent.getGrantedClientScopes());
}
}
List<String> clientScopesGranted = orderedScopes.stream().sorted(OrderedModel.OrderedModelComparator.getInstance()).map(ClientScopeModel::getConsentScreenText).collect(Collectors.toList());
List<String> additionalGrants = new ArrayList<>();
if (offlineClients.contains(client)) {
additionalGrants.add("${offlineToken}");
}
return new ApplicationEntry(session, realmRolesAvailable, resourceRolesAvailable, client, clientScopesGranted, additionalGrants);
}
use of org.keycloak.models.ClientScopeModel in project keycloak by keycloak.
the class JpaRealmProvider method addClientScopes.
@Override
public void addClientScopes(RealmModel realm, ClientModel client, Set<ClientScopeModel> clientScopes, boolean defaultScope) {
// Defaults to openid-connect
String clientProtocol = client.getProtocol() == null ? OIDCLoginProtocol.LOGIN_PROTOCOL : client.getProtocol();
Map<String, ClientScopeModel> existingClientScopes = getClientScopes(realm, client, true);
existingClientScopes.putAll(getClientScopes(realm, client, false));
clientScopes.stream().filter(clientScope -> !existingClientScopes.containsKey(clientScope.getName())).filter(clientScope -> Objects.equals(clientScope.getProtocol(), clientProtocol)).forEach(clientScope -> {
ClientScopeClientMappingEntity entity = new ClientScopeClientMappingEntity();
entity.setClientScopeId(clientScope.getId());
entity.setClientId(client.getId());
entity.setDefaultScope(defaultScope);
em.persist(entity);
em.flush();
em.detach(entity);
});
}
Aggregations