Java Code Examples for org.keycloak.services.managers.AuthenticationManager#setClientScopesInSession()

The following examples show how to use org.keycloak.services.managers.AuthenticationManager#setClientScopesInSession() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: AuthenticationProcessor.java    From keycloak with Apache License 2.0 5 votes vote down vote up
protected Response authenticationComplete() {
    // attachSession(); // Session will be attached after requiredActions + consents are finished.
    AuthenticationManager.setClientScopesInSession(authenticationSession);

    String nextRequiredAction = nextRequiredAction();
    if (nextRequiredAction != null) {
        return AuthenticationManager.redirectToRequiredActions(session, realm, authenticationSession, uriInfo, nextRequiredAction);
    } else {
        event.detail(Details.CODE_ID, authenticationSession.getParentSession().getId());  // todo This should be set elsewhere.  find out why tests fail.  Don't know where this is supposed to be set
        return AuthenticationManager.finishedRequiredActions(session, authenticationSession, userSession, connection, request, uriInfo, event);
    }
}
 
Example 2
Source File: ClientScopeEvaluateResource.java    From keycloak with Apache License 2.0 5 votes vote down vote up
private AccessToken generateToken(UserModel user, String scopeParam) {
    AuthenticationSessionModel authSession = null;
    UserSessionModel userSession = null;
    AuthenticationSessionManager authSessionManager = new AuthenticationSessionManager(session);

    try {
        RootAuthenticationSessionModel rootAuthSession = authSessionManager.createAuthenticationSession(realm, false);
        authSession = rootAuthSession.createAuthenticationSession(client);

        authSession.setAuthenticatedUser(user);
        authSession.setProtocol(OIDCLoginProtocol.LOGIN_PROTOCOL);
        authSession.setClientNote(OIDCLoginProtocol.ISSUER, Urls.realmIssuer(uriInfo.getBaseUri(), realm.getName()));
        authSession.setClientNote(OIDCLoginProtocol.SCOPE_PARAM, scopeParam);

        userSession = session.sessions().createUserSession(authSession.getParentSession().getId(), realm, user, user.getUsername(),
                clientConnection.getRemoteAddr(), "example-auth", false, null, null);

        AuthenticationManager.setClientScopesInSession(authSession);
        ClientSessionContext clientSessionCtx = TokenManager.attachAuthenticationSession(session, userSession, authSession);

        TokenManager tokenManager = new TokenManager();

        TokenManager.AccessTokenResponseBuilder responseBuilder = tokenManager.responseBuilder(realm, client, null, session, userSession, clientSessionCtx)
                .generateAccessToken();

        return responseBuilder.getAccessToken();

    } finally {
        if (authSession != null) {
            authSessionManager.removeAuthenticationSession(realm, authSession, false);
        }
        if (userSession != null) {
            session.sessions().removeUserSession(realm, userSession);
        }
    }
}
 
Example 3
Source File: IdentityBrokerService.java    From keycloak with Apache License 2.0 5 votes vote down vote up
private Response finishBrokerAuthentication(BrokeredIdentityContext context, UserModel federatedUser, AuthenticationSessionModel authSession, String providerId) {
    authSession.setAuthNote(AuthenticationProcessor.BROKER_SESSION_ID, context.getBrokerSessionId());
    authSession.setAuthNote(AuthenticationProcessor.BROKER_USER_ID, context.getBrokerUserId());

    this.event.user(federatedUser);

    context.getIdp().authenticationFinished(authSession, context);
    authSession.setUserSessionNote(Details.IDENTITY_PROVIDER, providerId);
    authSession.setUserSessionNote(Details.IDENTITY_PROVIDER_USERNAME, context.getUsername());

    event.detail(Details.IDENTITY_PROVIDER, providerId)
            .detail(Details.IDENTITY_PROVIDER_USERNAME, context.getUsername());

    if (isDebugEnabled()) {
        logger.debugf("Performing local authentication for user [%s].", federatedUser);
    }

    AuthenticationManager.setClientScopesInSession(authSession);

    String nextRequiredAction = AuthenticationManager.nextRequiredAction(session, authSession, clientConnection, request, session.getContext().getUri(), event);
    if (nextRequiredAction != null) {
        if ("true".equals(authSession.getAuthNote(AuthenticationProcessor.FORWARDED_PASSIVE_LOGIN))) {
            logger.errorf("Required action %s found. Auth requests using prompt=none are incompatible with required actions", nextRequiredAction);
            return checkPassiveLoginError(authSession, OAuthErrorException.INTERACTION_REQUIRED);
        }
        return AuthenticationManager.redirectToRequiredActions(session, realmModel, authSession, session.getContext().getUri(), nextRequiredAction);
    } else {
        event.detail(Details.CODE_ID, authSession.getParentSession().getId());  // todo This should be set elsewhere.  find out why tests fail.  Don't know where this is supposed to be set
        return AuthenticationManager.finishedRequiredActions(session, authSession, null, clientConnection, request, session.getContext().getUri(), event);
    }
}
 
Example 4
Source File: CrossRealmClientAuthMapper.java    From keycloak-extension-playground with Apache License 2.0 4 votes vote down vote up
private Object fetchCrossRealmData(KeycloakSession session) {


        RealmModel targetRealm = session.realms().getRealmByName("services-demo");
        ClientModel serviceClient = targetRealm.getClientByClientId("simple-service");
        if (!serviceClient.isServiceAccountsEnabled()) {
            return null;
        }
        String loopback = "127.0.0.1";
        EventBuilder event = new EventBuilder(targetRealm, session, new ClientConnection() {
            public String getRemoteAddr() {
                return loopback;
            }

            public String getRemoteHost() {
                return loopback;
            }

            public int getRemotePort() {
                return 8080;
            }

            public String getLocalAddr() {
                return loopback;
            }

            public int getLocalPort() {
                return 8080;
            }
        });

        UserModel serviceAccountUser = session.users().getServiceAccount(serviceClient);
        if (!serviceAccountUser.isEnabled()) {
            return null;
        }

        RootAuthenticationSessionModel rootAuthSession = new AuthenticationSessionManager(session).createAuthenticationSession(targetRealm, false);
        AuthenticationSessionModel authSession = rootAuthSession.createAuthenticationSession(serviceClient);
        authSession.setAuthenticatedUser(serviceAccountUser);
        authSession.setProtocol(OIDCLoginProtocol.LOGIN_PROTOCOL);
        authSession.setClientNote(OIDCLoginProtocol.ISSUER, Urls.realmIssuer(session.getContext().getUri().getBaseUri(), targetRealm.getName()));
        authSession.setClientNote(OIDCLoginProtocol.SCOPE_PARAM, "openid profile roles");
        UserSessionModel serviceAccountUserSession = session.sessions().createUserSession(authSession.getParentSession().getId(), targetRealm, serviceAccountUser, serviceAccountUser.getUsername(),
                loopback, ServiceAccountConstants.CLIENT_AUTH, false, null, null);
        AuthenticationManager.setClientScopesInSession(authSession);
        ClientSessionContext clientSessionContext = TokenManager.attachAuthenticationSession(session, serviceAccountUserSession, authSession);

        // Notes about serviceClient details
        serviceAccountUserSession.setNote(ServiceAccountConstants.CLIENT_ID, serviceClient.getClientId());
        serviceAccountUserSession.setNote(ServiceAccountConstants.CLIENT_HOST, loopback);
        serviceAccountUserSession.setNote(ServiceAccountConstants.CLIENT_ADDRESS, loopback);

        TokenManager tokenManager = new TokenManager();
        TokenManager.AccessTokenResponseBuilder responseBuilder = tokenManager.responseBuilder(targetRealm, serviceClient, event, session, serviceAccountUserSession, clientSessionContext)
                .generateAccessToken();

        AccessTokenResponse accessTokenResponse = responseBuilder.build();

        String accessToken = accessTokenResponse.getToken();

        LOGGER.infof("AccessToken: %s", accessToken);

        return null;
    }
 
Example 5
Source File: TokenEndpoint.java    From keycloak with Apache License 2.0 4 votes vote down vote up
public Response resourceOwnerPasswordCredentialsGrant() {
    event.detail(Details.AUTH_METHOD, "oauth_credentials");

    if (!client.isDirectAccessGrantsEnabled()) {
        event.error(Errors.NOT_ALLOWED);
        throw new CorsErrorResponseException(cors, OAuthErrorException.UNAUTHORIZED_CLIENT, "Client not allowed for direct access grants", Response.Status.BAD_REQUEST);
    }

    if (client.isConsentRequired()) {
        event.error(Errors.CONSENT_DENIED);
        throw new CorsErrorResponseException(cors, OAuthErrorException.INVALID_CLIENT, "Client requires user consent", Response.Status.BAD_REQUEST);
    }
    String scope = getRequestedScopes();

    RootAuthenticationSessionModel rootAuthSession = new AuthenticationSessionManager(session).createAuthenticationSession(realm, false);
    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, scope);

    AuthenticationFlowModel flow = AuthenticationFlowResolver.resolveDirectGrantFlow(authSession);
    String flowId = flow.getId();
    AuthenticationProcessor processor = new AuthenticationProcessor();
    processor.setAuthenticationSession(authSession)
            .setFlowId(flowId)
            .setConnection(clientConnection)
            .setEventBuilder(event)
            .setRealm(realm)
            .setSession(session)
            .setUriInfo(session.getContext().getUri())
            .setRequest(request);
    Response challenge = processor.authenticateOnly();
    if (challenge != null) {
        cors.build(httpResponse);
        return challenge;
    }
    processor.evaluateRequiredActionTriggers();
    UserModel user = authSession.getAuthenticatedUser();
    if (user.getRequiredActions() != null && user.getRequiredActions().size() > 0) {
        event.error(Errors.RESOLVE_REQUIRED_ACTIONS);
        throw new CorsErrorResponseException(cors, OAuthErrorException.INVALID_GRANT, "Account is not fully set up", Response.Status.BAD_REQUEST);

    }

    AuthenticationManager.setClientScopesInSession(authSession);

    ClientSessionContext clientSessionCtx = processor.attachSession();
    UserSessionModel userSession = processor.getUserSession();
    updateUserSessionFromClientAuth(userSession);

    TokenManager.AccessTokenResponseBuilder responseBuilder = tokenManager.responseBuilder(realm, client, event, session, userSession, clientSessionCtx)
            .generateAccessToken()
            .generateRefreshToken();

    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();
}
 
Example 6
Source File: TokenEndpoint.java    From keycloak with Apache License 2.0 4 votes vote down vote up
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);

    UserSessionModel userSession = session.sessions().createUserSession(authSession.getParentSession().getId(), realm, clientUser, clientUsername,
            clientConnection.getRemoteAddr(), ServiceAccountConstants.CLIENT_AUTH, false, null, null);
    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());

    updateUserSessionFromClientAuth(userSession);

    TokenManager.AccessTokenResponseBuilder responseBuilder = tokenManager.responseBuilder(realm, client, event, session, userSession, clientSessionCtx)
            .generateAccessToken()
            .generateRefreshToken();

    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();
}
 
Example 7
Source File: TokenEndpoint.java    From keycloak with Apache License 2.0 4 votes vote down vote up
protected Response exchangeClientToOIDCClient(UserModel targetUser, UserSessionModel targetUserSession, String requestedTokenType,
                                              ClientModel targetClient, String audience, String scope) {
    RootAuthenticationSessionModel rootAuthSession = new AuthenticationSessionManager(session).createAuthenticationSession(realm, false);
    AuthenticationSessionModel authSession = rootAuthSession.createAuthenticationSession(targetClient);

    authSession.setAuthenticatedUser(targetUser);
    authSession.setProtocol(OIDCLoginProtocol.LOGIN_PROTOCOL);
    authSession.setClientNote(OIDCLoginProtocol.ISSUER, Urls.realmIssuer(session.getContext().getUri().getBaseUri(), realm.getName()));
    authSession.setClientNote(OIDCLoginProtocol.SCOPE_PARAM, scope);

    event.session(targetUserSession);

    AuthenticationManager.setClientScopesInSession(authSession);
    ClientSessionContext clientSessionCtx = TokenManager.attachAuthenticationSession(this.session, targetUserSession, authSession);

    updateUserSessionFromClientAuth(targetUserSession);

    TokenManager.AccessTokenResponseBuilder responseBuilder = tokenManager.responseBuilder(realm, targetClient, event, this.session, targetUserSession, clientSessionCtx)
            .generateAccessToken();
    responseBuilder.getAccessToken().issuedFor(client.getClientId());

    if (audience != null) {
        responseBuilder.getAccessToken().addAudience(audience);
    }

    if (requestedTokenType.equals(OAuth2Constants.REFRESH_TOKEN_TYPE)) {
        responseBuilder.generateRefreshToken();
        responseBuilder.getRefreshToken().issuedFor(client.getClientId());
    }

    String scopeParam = clientSessionCtx.getClientSession().getNote(OAuth2Constants.SCOPE);
    if (TokenUtil.isOIDCRequest(scopeParam)) {
        responseBuilder.generateIDToken().generateAccessTokenHash();
    }

    AccessTokenResponse res = responseBuilder.build();
    event.detail(Details.AUDIENCE, targetClient.getClientId());

    event.success();

    return cors.builder(Response.ok(res, MediaType.APPLICATION_JSON_TYPE)).build();
}
 
Example 8
Source File: TokenEndpoint.java    From keycloak with Apache License 2.0 4 votes vote down vote up
protected Response exchangeClientToSAML2Client(UserModel targetUser, UserSessionModel targetUserSession, String requestedTokenType,
                                              ClientModel targetClient, String audience, String scope) {
    // Create authSession with target SAML 2.0 client and authenticated user
    LoginProtocolFactory factory = (LoginProtocolFactory) session.getKeycloakSessionFactory()
            .getProviderFactory(LoginProtocol.class, SamlProtocol.LOGIN_PROTOCOL);
    SamlService samlService = (SamlService) factory.createProtocolEndpoint(realm, event);
    ResteasyProviderFactory.getInstance().injectProperties(samlService);
    AuthenticationSessionModel authSession = samlService.getOrCreateLoginSessionForIdpInitiatedSso(session, realm,
            targetClient, null);
    if (authSession == null) {
        logger.error("SAML assertion consumer url not set up");
        throw new CorsErrorResponseException(cors, OAuthErrorException.INVALID_CLIENT, "Client requires assertion consumer url set up", Response.Status.BAD_REQUEST);
    }

    authSession.setAuthenticatedUser(targetUser);

    event.session(targetUserSession);

    AuthenticationManager.setClientScopesInSession(authSession);
    ClientSessionContext clientSessionCtx = TokenManager.attachAuthenticationSession(this.session, targetUserSession,
            authSession);

    updateUserSessionFromClientAuth(targetUserSession);

    // Create SAML 2.0 Assertion Response
    SamlClient samlClient = new SamlClient(targetClient);
    SamlProtocol samlProtocol = new TokenExchangeSamlProtocol(samlClient).setEventBuilder(event).setHttpHeaders(headers).setRealm(realm)
            .setSession(session).setUriInfo(session.getContext().getUri());

    Response samlAssertion = samlProtocol.authenticated(authSession, targetUserSession, clientSessionCtx);
    if (samlAssertion.getStatus() != 200) {
        throw new CorsErrorResponseException(cors, OAuthErrorException.INVALID_REQUEST, "Can not get SAML 2.0 token", Response.Status.BAD_REQUEST);
    }
    String xmlString = (String) samlAssertion.getEntity();
    String encodedXML = Base64Url.encode(xmlString.getBytes(GeneralConstants.SAML_CHARSET));

    int assertionLifespan = samlClient.getAssertionLifespan();

    AccessTokenResponse res = new AccessTokenResponse();
    res.setToken(encodedXML);
    res.setTokenType("Bearer");
    res.setExpiresIn(assertionLifespan <= 0 ? realm.getAccessCodeLifespan() : assertionLifespan);
    res.setOtherClaims(OAuth2Constants.ISSUED_TOKEN_TYPE, requestedTokenType);

    event.detail(Details.AUDIENCE, targetClient.getClientId());
    event.success();

    return cors.builder(Response.ok(res, MediaType.APPLICATION_JSON_TYPE)).build();
}
 
Example 9
Source File: IdentityBrokerService.java    From keycloak with Apache License 2.0 4 votes vote down vote up
private Response performAccountLinking(AuthenticationSessionModel authSession, UserSessionModel userSession, BrokeredIdentityContext context, FederatedIdentityModel newModel, UserModel federatedUser) {
    logger.debugf("Will try to link identity provider [%s] to user [%s]", context.getIdpConfig().getAlias(), userSession.getUser().getUsername());

    this.event.event(EventType.FEDERATED_IDENTITY_LINK);



    UserModel authenticatedUser = userSession.getUser();
    authSession.setAuthenticatedUser(authenticatedUser);

    if (federatedUser != null && !authenticatedUser.getId().equals(federatedUser.getId())) {
        return redirectToErrorWhenLinkingFailed(authSession, Messages.IDENTITY_PROVIDER_ALREADY_LINKED, context.getIdpConfig().getAlias());
    }

    if (!authenticatedUser.hasRole(this.realmModel.getClientByClientId(Constants.ACCOUNT_MANAGEMENT_CLIENT_ID).getRole(AccountRoles.MANAGE_ACCOUNT))) {
        return redirectToErrorPage(authSession, Response.Status.FORBIDDEN, Messages.INSUFFICIENT_PERMISSION);
    }

    if (!authenticatedUser.isEnabled()) {
        return redirectToErrorWhenLinkingFailed(authSession, Messages.ACCOUNT_DISABLED);
    }



    if (federatedUser != null) {
        if (context.getIdpConfig().isStoreToken()) {
            FederatedIdentityModel oldModel = this.session.users().getFederatedIdentity(federatedUser, context.getIdpConfig().getAlias(), this.realmModel);
            if (!ObjectUtil.isEqualOrBothNull(context.getToken(), oldModel.getToken())) {
                this.session.users().updateFederatedIdentity(this.realmModel, federatedUser, newModel);
                if (isDebugEnabled()) {
                    logger.debugf("Identity [%s] update with response from identity provider [%s].", federatedUser, context.getIdpConfig().getAlias());
                }
            }
        }
    } else {
        this.session.users().addFederatedIdentity(this.realmModel, authenticatedUser, newModel);
    }
    context.getIdp().authenticationFinished(authSession, context);

    AuthenticationManager.setClientScopesInSession(authSession);
    TokenManager.attachAuthenticationSession(session, userSession, authSession);

    if (isDebugEnabled()) {
        logger.debugf("Linking account [%s] from identity provider [%s] to user [%s].", newModel, context.getIdpConfig().getAlias(), authenticatedUser);
    }

    this.event.user(authenticatedUser)
            .detail(Details.USERNAME, authenticatedUser.getUsername())
            .detail(Details.IDENTITY_PROVIDER, newModel.getIdentityProvider())
            .detail(Details.IDENTITY_PROVIDER_USERNAME, newModel.getUserName())
            .success();

    // we do this to make sure that the parent IDP is logged out when this user session is complete.
    // But for the case when userSession was previously authenticated with broker1 and now is linked to another broker2, we shouldn't override broker1 notes with the broker2 for sure.
    // Maybe broker logout should be rather always skiped in case of broker-linking
    if (userSession.getNote(Details.IDENTITY_PROVIDER) == null) {
        userSession.setNote(Details.IDENTITY_PROVIDER, context.getIdpConfig().getAlias());
        userSession.setNote(Details.IDENTITY_PROVIDER_USERNAME, context.getUsername());
    }

    return Response.status(302).location(UriBuilder.fromUri(authSession.getRedirectUri()).build()).build();
}
 
Example 10
Source File: AuthorizationTokenService.java    From keycloak with Apache License 2.0 4 votes vote down vote up
private AuthorizationResponse createAuthorizationResponse(KeycloakIdentity identity, Collection<Permission> entitlements, KeycloakAuthorizationRequest request, ClientModel targetClient) {
    KeycloakSession keycloakSession = request.getKeycloakSession();
    AccessToken accessToken = identity.getAccessToken();
    RealmModel realm = request.getRealm();
    UserSessionProvider sessions = keycloakSession.sessions();
    UserSessionModel userSessionModel = sessions.getUserSession(realm, accessToken.getSessionState());

    if (userSessionModel == null) {
        userSessionModel = sessions.getOfflineUserSession(realm, accessToken.getSessionState());
    }

    ClientModel client = realm.getClientByClientId(accessToken.getIssuedFor());
    AuthenticatedClientSessionModel clientSession = userSessionModel.getAuthenticatedClientSessionByClient(targetClient.getId());
    ClientSessionContext clientSessionCtx;

    if (clientSession == null) {
        RootAuthenticationSessionModel rootAuthSession = keycloakSession.authenticationSessions().getRootAuthenticationSession(realm, userSessionModel.getId());

        if (rootAuthSession == null) {
            if (userSessionModel.getUser().getServiceAccountClientLink() == null) {
                rootAuthSession = keycloakSession.authenticationSessions().createRootAuthenticationSession(userSessionModel.getId(), realm);
            } else {
                // if the user session is associated with a service account
                rootAuthSession = new AuthenticationSessionManager(keycloakSession).createAuthenticationSession(realm, false);
            }
        }

        AuthenticationSessionModel authSession = rootAuthSession.createAuthenticationSession(targetClient);

        authSession.setAuthenticatedUser(userSessionModel.getUser());
        authSession.setProtocol(OIDCLoginProtocol.LOGIN_PROTOCOL);
        authSession.setClientNote(OIDCLoginProtocol.ISSUER, Urls.realmIssuer(keycloakSession.getContext().getUri().getBaseUri(), realm.getName()));

        AuthenticationManager.setClientScopesInSession(authSession);
        clientSessionCtx = TokenManager.attachAuthenticationSession(keycloakSession, userSessionModel, authSession);
    } else {
        clientSessionCtx = DefaultClientSessionContext.fromClientSessionScopeParameter(clientSession, keycloakSession);
    }

    TokenManager tokenManager = request.getTokenManager();
    EventBuilder event = request.getEvent();
    AccessTokenResponseBuilder responseBuilder = tokenManager.responseBuilder(realm, client, event, keycloakSession, userSessionModel, clientSessionCtx)
            .generateAccessToken()
            .generateRefreshToken();
    AccessToken rpt = responseBuilder.getAccessToken();
    Authorization authorization = new Authorization();

    authorization.setPermissions(entitlements);

    rpt.setAuthorization(authorization);

    RefreshToken refreshToken = responseBuilder.getRefreshToken();

    refreshToken.issuedFor(client.getClientId());
    refreshToken.setAuthorization(authorization);

    if (!rpt.hasAudience(targetClient.getClientId())) {
        rpt.audience(targetClient.getClientId());
    }

    return new AuthorizationResponse(responseBuilder.build(), isUpgraded(request, authorization));
}