Search in sources :

Example 1 with TokenManager

use of org.keycloak.protocol.oidc.TokenManager in project keycloak by keycloak.

the class TokenEndpoint method tokenExchange.

public Response tokenExchange() {
    ProfileHelper.requireFeature(Profile.Feature.TOKEN_EXCHANGE);
    event.detail(Details.AUTH_METHOD, "token_exchange");
    event.client(client);
    TokenExchangeContext context = new TokenExchangeContext(session, formParams, cors, realm, event, client, clientConnection, headers, tokenManager, clientAuthAttributes);
    return session.getKeycloakSessionFactory().getProviderFactoriesStream(TokenExchangeProvider.class).sorted((f1, f2) -> f2.order() - f1.order()).map(f -> session.getProvider(TokenExchangeProvider.class, f.getId())).filter(p -> p.supports(context)).findFirst().orElseThrow(() -> new InternalServerErrorException("No token exchange provider available")).exchange(context);
}
Also used : Tokens(org.keycloak.authorization.util.Tokens) DefaultClientSessionContext(org.keycloak.services.util.DefaultClientSessionContext) Path(javax.ws.rs.Path) AuthenticationSessionManager(org.keycloak.services.managers.AuthenticationSessionManager) Metadata(org.keycloak.representations.idm.authorization.AuthorizationRequest.Metadata) AccessTokenResponse(org.keycloak.representations.AccessTokenResponse) OAuthErrorException(org.keycloak.OAuthErrorException) MediaType(javax.ws.rs.core.MediaType) ResourceOwnerPasswordCredentialsContext(org.keycloak.services.clientpolicy.context.ResourceOwnerPasswordCredentialsContext) AuthenticationManager(org.keycloak.services.managers.AuthenticationManager) Consumes(javax.ws.rs.Consumes) AccessToken(org.keycloak.representations.AccessToken) AuthenticatedClientSessionModel(org.keycloak.models.AuthenticatedClientSessionModel) Document(org.w3c.dom.Document) AppAuthManager(org.keycloak.services.managers.AppAuthManager) Map(java.util.Map) ClientConnection(org.keycloak.common.ClientConnection) AuthorizationProvider(org.keycloak.authorization.AuthorizationProvider) TokenExchangeContext(org.keycloak.protocol.oidc.TokenExchangeContext) DeviceGrantType(org.keycloak.protocol.oidc.grants.device.DeviceGrantType) AuthenticationSessionModel(org.keycloak.sessions.AuthenticationSessionModel) ClientScopeModel(org.keycloak.models.ClientScopeModel) RealmModel(org.keycloak.models.RealmModel) Context(javax.ws.rs.core.Context) AuthenticationProcessor(org.keycloak.authentication.AuthenticationProcessor) MtlsHoKTokenUtil(org.keycloak.services.util.MtlsHoKTokenUtil) SamlProtocol(org.keycloak.protocol.saml.SamlProtocol) InternalServerErrorException(javax.ws.rs.InternalServerErrorException) CorsErrorResponseException(org.keycloak.services.CorsErrorResponseException) DocumentUtil(org.keycloak.saml.common.util.DocumentUtil) Objects(java.util.Objects) ServiceAccountConstants(org.keycloak.common.constants.ServiceAccountConstants) List(java.util.List) HttpHeaders(javax.ws.rs.core.HttpHeaders) Stream(java.util.stream.Stream) Response(javax.ws.rs.core.Response) Details(org.keycloak.events.Details) RootAuthenticationSessionModel(org.keycloak.sessions.RootAuthenticationSessionModel) SamlClient(org.keycloak.protocol.saml.SamlClient) OIDCLoginProtocol(org.keycloak.protocol.oidc.OIDCLoginProtocol) OAuth2Code(org.keycloak.protocol.oidc.utils.OAuth2Code) QName(javax.xml.namespace.QName) CibaGrantType(org.keycloak.protocol.oidc.grants.ciba.CibaGrantType) OAuth2Constants(org.keycloak.OAuth2Constants) AuthorizationTokenService(org.keycloak.authorization.authorization.AuthorizationTokenService) ClientModel(org.keycloak.models.ClientModel) PkceUtils(org.keycloak.protocol.oidc.utils.PkceUtils) TokenRefreshContext(org.keycloak.services.clientpolicy.context.TokenRefreshContext) Profile(org.keycloak.common.Profile) RealmManager(org.keycloak.services.managers.RealmManager) Logger(org.jboss.logging.Logger) AuthorizeClientUtil(org.keycloak.protocol.oidc.utils.AuthorizeClientUtil) TokenManager(org.keycloak.protocol.oidc.TokenManager) ServicesLogger(org.keycloak.services.ServicesLogger) Supplier(java.util.function.Supplier) AuthenticationFlowResolver(org.keycloak.models.utils.AuthenticationFlowResolver) OAuth2CodeParser(org.keycloak.protocol.oidc.utils.OAuth2CodeParser) ResteasyProviderFactory(org.jboss.resteasy.spi.ResteasyProviderFactory) JWSInputException(org.keycloak.jose.jws.JWSInputException) TokenUtil(org.keycloak.util.TokenUtil) UserModel(org.keycloak.models.UserModel) ClientSessionContext(org.keycloak.models.ClientSessionContext) ProcessingException(org.keycloak.saml.common.exceptions.ProcessingException) ClientManager(org.keycloak.services.managers.ClientManager) EventBuilder(org.keycloak.events.EventBuilder) OIDCAdvancedConfigWrapper(org.keycloak.protocol.oidc.OIDCAdvancedConfigWrapper) AuthenticationFlowModel(org.keycloak.models.AuthenticationFlowModel) TokenExchangeProvider(org.keycloak.protocol.oidc.TokenExchangeProvider) TokenRequestContext(org.keycloak.services.clientpolicy.context.TokenRequestContext) Cors(org.keycloak.services.resources.Cors) ProfileHelper(org.keycloak.utils.ProfileHelper) Status(javax.ws.rs.core.Response.Status) JBossSAMLConstants(org.keycloak.saml.common.constants.JBossSAMLConstants) ConfigurationException(org.keycloak.saml.common.exceptions.ConfigurationException) JWSInput(org.keycloak.jose.jws.JWSInput) Errors(org.keycloak.events.Errors) POST(javax.ws.rs.POST) JaxrsSAML2BindingBuilder(org.keycloak.protocol.saml.JaxrsSAML2BindingBuilder) KeycloakUriBuilder(org.keycloak.common.util.KeycloakUriBuilder) JBossSAMLURIConstants(org.keycloak.saml.common.constants.JBossSAMLURIConstants) KeycloakSession(org.keycloak.models.KeycloakSession) HttpRequest(org.jboss.resteasy.spi.HttpRequest) EventType(org.keycloak.events.EventType) IOException(java.io.IOException) AdapterConstants(org.keycloak.constants.AdapterConstants) UserSessionModel(org.keycloak.models.UserSessionModel) OPTIONS(javax.ws.rs.OPTIONS) HttpResponse(org.jboss.resteasy.spi.HttpResponse) AuthorizationContextUtil(org.keycloak.services.util.AuthorizationContextUtil) MultivaluedHashMap(javax.ws.rs.core.MultivaluedHashMap) MultivaluedMap(javax.ws.rs.core.MultivaluedMap) Element(org.w3c.dom.Element) ClientPolicyException(org.keycloak.services.clientpolicy.ClientPolicyException) AuthorizationRequestContext(org.keycloak.rar.AuthorizationRequestContext) ServiceAccountTokenRequestContext(org.keycloak.services.clientpolicy.context.ServiceAccountTokenRequestContext) Urls(org.keycloak.services.Urls) TokenExchangeProvider(org.keycloak.protocol.oidc.TokenExchangeProvider) InternalServerErrorException(javax.ws.rs.InternalServerErrorException) TokenExchangeContext(org.keycloak.protocol.oidc.TokenExchangeContext)

Example 2 with TokenManager

use of org.keycloak.protocol.oidc.TokenManager in project keycloak by keycloak.

the class ClientScopeEvaluateResource method generateExampleAccessToken.

/**
 * Create JSON with payload of example access token
 *
 * @return
 */
@GET
@Path("generate-example-access-token")
@NoCache
@Produces(MediaType.APPLICATION_JSON)
public AccessToken generateExampleAccessToken(@QueryParam("scope") String scopeParam, @QueryParam("userId") String userId) {
    auth.clients().requireView(client);
    UserModel user = getUserModel(userId);
    logger.debugf("generateExampleAccessToken invoked. User: %s, Scope param: %s", user.getUsername(), scopeParam);
    return sessionAware(user, scopeParam, (userSession, clientSessionCtx) -> {
        TokenManager tokenManager = new TokenManager();
        return tokenManager.responseBuilder(realm, client, null, session, userSession, clientSessionCtx).generateAccessToken().getAccessToken();
    });
}
Also used : UserModel(org.keycloak.models.UserModel) TokenManager(org.keycloak.protocol.oidc.TokenManager) Path(javax.ws.rs.Path) Produces(javax.ws.rs.Produces) GET(javax.ws.rs.GET) NoCache(org.jboss.resteasy.annotations.cache.NoCache)

Example 3 with TokenManager

use of org.keycloak.protocol.oidc.TokenManager in project keycloak by keycloak.

the class ClientScopeEvaluateResource method generateExampleUserinfo.

/**
 * Create JSON with payload of example user info
 *
 * @return
 */
@GET
@Path("generate-example-userinfo")
@NoCache
@Produces(MediaType.APPLICATION_JSON)
public Map<String, Object> generateExampleUserinfo(@QueryParam("scope") String scopeParam, @QueryParam("userId") String userId) {
    auth.clients().requireView(client);
    UserModel user = getUserModel(userId);
    logger.debugf("generateExampleUserinfo invoked. User: %s", user.getUsername());
    return sessionAware(user, scopeParam, (userSession, clientSessionCtx) -> {
        AccessToken userInfo = new AccessToken();
        TokenManager tokenManager = new TokenManager();
        tokenManager.transformUserInfoAccessToken(session, userInfo, userSession, clientSessionCtx);
        return tokenManager.generateUserInfoClaims(userInfo, user);
    });
}
Also used : UserModel(org.keycloak.models.UserModel) AccessToken(org.keycloak.representations.AccessToken) TokenManager(org.keycloak.protocol.oidc.TokenManager) Path(javax.ws.rs.Path) Produces(javax.ws.rs.Produces) GET(javax.ws.rs.GET) NoCache(org.jboss.resteasy.annotations.cache.NoCache)

Example 4 with TokenManager

use of org.keycloak.protocol.oidc.TokenManager in project keycloak by keycloak.

the class ClientScopeEvaluateResource method generateExampleIdToken.

/**
 * Create JSON with payload of example id token
 *
 * @return
 */
@GET
@Path("generate-example-id-token")
@NoCache
@Produces(MediaType.APPLICATION_JSON)
public IDToken generateExampleIdToken(@QueryParam("scope") String scopeParam, @QueryParam("userId") String userId) {
    auth.clients().requireView(client);
    UserModel user = getUserModel(userId);
    logger.debugf("generateExampleIdToken invoked. User: %s, Scope param: %s", user.getUsername(), scopeParam);
    return sessionAware(user, scopeParam, (userSession, clientSessionCtx) -> {
        TokenManager tokenManager = new TokenManager();
        return tokenManager.responseBuilder(realm, client, null, session, userSession, clientSessionCtx).generateAccessToken().generateIDToken().getIdToken();
    });
}
Also used : UserModel(org.keycloak.models.UserModel) TokenManager(org.keycloak.protocol.oidc.TokenManager) Path(javax.ws.rs.Path) Produces(javax.ws.rs.Produces) GET(javax.ws.rs.GET) NoCache(org.jboss.resteasy.annotations.cache.NoCache)

Example 5 with TokenManager

use of org.keycloak.protocol.oidc.TokenManager in project keycloak by keycloak.

the class AuthorizationTokenService method createAuthorizationResponse.

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;
    if (accessToken.getSessionState() == null) {
        // Create temporary (request-scoped) transient session
        UserModel user = TokenManager.lookupUserFromStatelessToken(keycloakSession, realm, accessToken);
        userSessionModel = sessions.createUserSession(KeycloakModelUtils.generateId(), realm, user, user.getUsername(), request.getClientConnection().getRemoteAddr(), ServiceAccountConstants.CLIENT_AUTH, false, null, null, UserSessionModel.SessionPersistenceState.TRANSIENT);
    } else {
        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(realm, userSessionModel.getId());
            } 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();
    AccessToken rpt = responseBuilder.getAccessToken();
    Authorization authorization = new Authorization();
    authorization.setPermissions(entitlements);
    rpt.setAuthorization(authorization);
    if (accessToken.getSessionState() == null) {
        // Skip generating refresh token for accessToken without sessionState claim. This is "stateless" accessToken not pointing to any real persistent userSession
        rpt.setSessionState(null);
    } else {
        if (OIDCAdvancedConfigWrapper.fromClientModel(client).isUseRefreshToken()) {
            responseBuilder.generateRefreshToken();
            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));
}
Also used : UserSessionModel(org.keycloak.models.UserSessionModel) AuthenticationSessionModel(org.keycloak.sessions.AuthenticationSessionModel) RootAuthenticationSessionModel(org.keycloak.sessions.RootAuthenticationSessionModel) AuthenticatedClientSessionModel(org.keycloak.models.AuthenticatedClientSessionModel) AuthorizationResponse(org.keycloak.representations.idm.authorization.AuthorizationResponse) RealmModel(org.keycloak.models.RealmModel) UserModel(org.keycloak.models.UserModel) AuthenticationSessionManager(org.keycloak.services.managers.AuthenticationSessionManager) Authorization(org.keycloak.representations.AccessToken.Authorization) UserSessionProvider(org.keycloak.models.UserSessionProvider) ClientModel(org.keycloak.models.ClientModel) EventBuilder(org.keycloak.events.EventBuilder) RefreshToken(org.keycloak.representations.RefreshToken) DefaultClientSessionContext(org.keycloak.services.util.DefaultClientSessionContext) ClientSessionContext(org.keycloak.models.ClientSessionContext) AccessToken(org.keycloak.representations.AccessToken) KeycloakSession(org.keycloak.models.KeycloakSession) RootAuthenticationSessionModel(org.keycloak.sessions.RootAuthenticationSessionModel) AccessTokenResponseBuilder(org.keycloak.protocol.oidc.TokenManager.AccessTokenResponseBuilder) TokenManager(org.keycloak.protocol.oidc.TokenManager)

Aggregations

UserModel (org.keycloak.models.UserModel)6 TokenManager (org.keycloak.protocol.oidc.TokenManager)6 Path (javax.ws.rs.Path)4 AccessToken (org.keycloak.representations.AccessToken)4 GET (javax.ws.rs.GET)3 Produces (javax.ws.rs.Produces)3 NoCache (org.jboss.resteasy.annotations.cache.NoCache)3 ClientModel (org.keycloak.models.ClientModel)2 ClientSessionContext (org.keycloak.models.ClientSessionContext)2 KeycloakSession (org.keycloak.models.KeycloakSession)2 RealmModel (org.keycloak.models.RealmModel)2 UserSessionModel (org.keycloak.models.UserSessionModel)2 AuthenticationSessionModel (org.keycloak.sessions.AuthenticationSessionModel)2 IOException (java.io.IOException)1 List (java.util.List)1 Map (java.util.Map)1 Objects (java.util.Objects)1 Supplier (java.util.function.Supplier)1 Stream (java.util.stream.Stream)1 Consumes (javax.ws.rs.Consumes)1