use of org.keycloak.protocol.oidc.TokenManager in project keycloak by keycloak.
the class PolicyEvaluationService method createIdentity.
private CloseableKeycloakIdentity createIdentity(PolicyEvaluationRequest representation) {
KeycloakSession keycloakSession = this.authorization.getKeycloakSession();
RealmModel realm = keycloakSession.getContext().getRealm();
AccessToken accessToken = null;
String subject = representation.getUserId();
UserSessionModel userSession = null;
if (subject != null) {
UserModel userModel = keycloakSession.users().getUserById(realm, subject);
if (userModel == null) {
userModel = keycloakSession.users().getUserByUsername(realm, subject);
}
if (userModel != null) {
String clientId = representation.getClientId();
if (clientId == null) {
clientId = resourceServer.getId();
}
if (clientId != null) {
ClientModel clientModel = realm.getClientById(clientId);
AuthenticationSessionModel authSession = keycloakSession.authenticationSessions().createRootAuthenticationSession(realm).createAuthenticationSession(clientModel);
authSession.setProtocol(OIDCLoginProtocol.LOGIN_PROTOCOL);
authSession.setAuthenticatedUser(userModel);
userSession = keycloakSession.sessions().createUserSession(authSession.getParentSession().getId(), realm, userModel, userModel.getUsername(), "127.0.0.1", "passwd", false, null, null, UserSessionModel.SessionPersistenceState.PERSISTENT);
AuthenticationManager.setClientScopesInSession(authSession);
ClientSessionContext clientSessionCtx = TokenManager.attachAuthenticationSession(keycloakSession, userSession, authSession);
accessToken = new TokenManager().createClientAccessToken(keycloakSession, realm, clientModel, userModel, userSession, clientSessionCtx);
}
}
}
if (accessToken == null) {
accessToken = new AccessToken();
accessToken.subject(representation.getUserId());
ClientModel client = null;
String clientId = representation.getClientId();
if (clientId != null) {
client = realm.getClientById(clientId);
}
if (client == null) {
client = realm.getClientById(resourceServer.getId());
}
accessToken.issuedFor(client.getClientId());
accessToken.audience(client.getId());
accessToken.issuer(Urls.realmIssuer(keycloakSession.getContext().getUri().getBaseUri(), realm.getName()));
accessToken.setRealmAccess(new AccessToken.Access());
}
if (representation.getRoleIds() != null && !representation.getRoleIds().isEmpty()) {
if (accessToken.getRealmAccess() == null) {
accessToken.setRealmAccess(new AccessToken.Access());
}
AccessToken.Access realmAccess = accessToken.getRealmAccess();
representation.getRoleIds().forEach(realmAccess::addRole);
}
return new CloseableKeycloakIdentity(accessToken, keycloakSession, userSession);
}
Aggregations