Search in sources :

Example 1 with Cors

use of org.keycloak.services.resources.Cors 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 Cors

use of org.keycloak.services.resources.Cors in project keycloak by keycloak.

the class DefaultTokenExchangeProvider method exchangeExternalToken.

protected Response exchangeExternalToken(String issuer, String subjectToken) {
    AtomicReference<ExchangeExternalToken> externalIdp = new AtomicReference<>(null);
    AtomicReference<IdentityProviderModel> externalIdpModel = new AtomicReference<>(null);
    realm.getIdentityProvidersStream().filter(idpModel -> {
        IdentityProviderFactory factory = IdentityBrokerService.getIdentityProviderFactory(session, idpModel);
        IdentityProvider idp = factory.create(session, idpModel);
        if (idp instanceof ExchangeExternalToken) {
            ExchangeExternalToken external = (ExchangeExternalToken) idp;
            if (idpModel.getAlias().equals(issuer) || external.isIssuer(issuer, formParams)) {
                externalIdp.set(external);
                externalIdpModel.set(idpModel);
                return true;
            }
        }
        return false;
    }).findFirst();
    if (externalIdp.get() == null) {
        event.error(Errors.INVALID_ISSUER);
        throw new CorsErrorResponseException(cors, Errors.INVALID_ISSUER, "Invalid " + OAuth2Constants.SUBJECT_ISSUER + " parameter", Response.Status.BAD_REQUEST);
    }
    if (!AdminPermissions.management(session, realm).idps().canExchangeTo(client, externalIdpModel.get())) {
        event.detail(Details.REASON, "client not allowed to exchange subject_issuer");
        event.error(Errors.NOT_ALLOWED);
        throw new CorsErrorResponseException(cors, OAuthErrorException.ACCESS_DENIED, "Client not allowed to exchange", Response.Status.FORBIDDEN);
    }
    BrokeredIdentityContext context = externalIdp.get().exchangeExternal(event, formParams);
    if (context == null) {
        event.error(Errors.INVALID_ISSUER);
        throw new CorsErrorResponseException(cors, Errors.INVALID_ISSUER, "Invalid " + OAuth2Constants.SUBJECT_ISSUER + " parameter", Response.Status.BAD_REQUEST);
    }
    UserModel user = importUserFromExternalIdentity(context);
    UserSessionModel userSession = session.sessions().createUserSession(realm, user, user.getUsername(), clientConnection.getRemoteAddr(), "external-exchange", false, null, null);
    externalIdp.get().exchangeExternalComplete(userSession, context, formParams);
    // this must exist so that we can obtain access token from user session if idp's store tokens is off
    userSession.setNote(IdentityProvider.EXTERNAL_IDENTITY_PROVIDER, externalIdpModel.get().getAlias());
    userSession.setNote(IdentityProvider.FEDERATED_ACCESS_TOKEN, subjectToken);
    return exchangeClientToClient(user, userSession);
}
Also used : BrokeredIdentityContext(org.keycloak.broker.provider.BrokeredIdentityContext) AuthenticationSessionManager(org.keycloak.services.managers.AuthenticationSessionManager) AccessTokenResponse(org.keycloak.representations.AccessTokenResponse) OAuthErrorException(org.keycloak.OAuthErrorException) MediaType(javax.ws.rs.core.MediaType) AuthenticationManager(org.keycloak.services.managers.AuthenticationManager) AccessToken(org.keycloak.representations.AccessToken) ExchangeExternalToken(org.keycloak.broker.provider.ExchangeExternalToken) Validation(org.keycloak.services.validation.Validation) Map(java.util.Map) SamlService(org.keycloak.protocol.saml.SamlService) ClientConnection(org.keycloak.common.ClientConnection) AdminPermissions(org.keycloak.services.resources.admin.permissions.AdminPermissions) AuthenticationSessionModel(org.keycloak.sessions.AuthenticationSessionModel) RealmModel(org.keycloak.models.RealmModel) IdentityProviderMapperSyncModeDelegate(org.keycloak.broker.provider.IdentityProviderMapperSyncModeDelegate) Set(java.util.Set) SamlProtocol(org.keycloak.protocol.saml.SamlProtocol) IdentityProviderModel(org.keycloak.models.IdentityProviderModel) CorsErrorResponseException(org.keycloak.services.CorsErrorResponseException) Collectors(java.util.stream.Collectors) IMPERSONATOR_ID(org.keycloak.models.ImpersonationSessionNote.IMPERSONATOR_ID) TokenExchangeSamlProtocol(org.keycloak.protocol.oidc.endpoints.TokenEndpoint.TokenExchangeSamlProtocol) AdminAuth(org.keycloak.services.resources.admin.AdminAuth) HttpHeaders(javax.ws.rs.core.HttpHeaders) Response(javax.ws.rs.core.Response) Details(org.keycloak.events.Details) RootAuthenticationSessionModel(org.keycloak.sessions.RootAuthenticationSessionModel) KeycloakSessionFactory(org.keycloak.models.KeycloakSessionFactory) SamlClient(org.keycloak.protocol.saml.SamlClient) BruteForceProtector(org.keycloak.services.managers.BruteForceProtector) OAuth2Constants(org.keycloak.OAuth2Constants) LoginProtocol(org.keycloak.protocol.LoginProtocol) ClientModel(org.keycloak.models.ClientModel) IdentityProviderFactory(org.keycloak.broker.provider.IdentityProviderFactory) IdentityProviderMapperModel(org.keycloak.models.IdentityProviderMapperModel) ExchangeTokenToIdentityProviderToken(org.keycloak.broker.provider.ExchangeTokenToIdentityProviderToken) Logger(org.jboss.logging.Logger) GeneralConstants(org.keycloak.saml.common.constants.GeneralConstants) AtomicReference(java.util.concurrent.atomic.AtomicReference) LoginProtocolFactory(org.keycloak.protocol.LoginProtocolFactory) 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) EventBuilder(org.keycloak.events.EventBuilder) Cors(org.keycloak.services.resources.Cors) Base64Url(org.keycloak.common.util.Base64Url) IdentityProvider(org.keycloak.broker.provider.IdentityProvider) IdentityProviderMapper(org.keycloak.broker.provider.IdentityProviderMapper) FederatedIdentityModel(org.keycloak.models.FederatedIdentityModel) JWSInput(org.keycloak.jose.jws.JWSInput) Errors(org.keycloak.events.Errors) IdentityBrokerService(org.keycloak.services.resources.IdentityBrokerService) KeycloakSession(org.keycloak.models.KeycloakSession) UserSessionModel(org.keycloak.models.UserSessionModel) JsonWebToken(org.keycloak.representations.JsonWebToken) MultivaluedMap(javax.ws.rs.core.MultivaluedMap) IMPERSONATOR_USERNAME(org.keycloak.models.ImpersonationSessionNote.IMPERSONATOR_USERNAME) AuthenticatorUtils.getDisabledByBruteForceEventError(org.keycloak.authentication.authenticators.util.AuthenticatorUtils.getDisabledByBruteForceEventError) Urls(org.keycloak.services.Urls) UserModel(org.keycloak.models.UserModel) UserSessionModel(org.keycloak.models.UserSessionModel) ExchangeExternalToken(org.keycloak.broker.provider.ExchangeExternalToken) AtomicReference(java.util.concurrent.atomic.AtomicReference) IdentityProvider(org.keycloak.broker.provider.IdentityProvider) IdentityProviderModel(org.keycloak.models.IdentityProviderModel) CorsErrorResponseException(org.keycloak.services.CorsErrorResponseException) IdentityProviderFactory(org.keycloak.broker.provider.IdentityProviderFactory) BrokeredIdentityContext(org.keycloak.broker.provider.BrokeredIdentityContext)

Aggregations

Map (java.util.Map)2 HttpHeaders (javax.ws.rs.core.HttpHeaders)2 MediaType (javax.ws.rs.core.MediaType)2 MultivaluedMap (javax.ws.rs.core.MultivaluedMap)2 Response (javax.ws.rs.core.Response)2 Logger (org.jboss.logging.Logger)2 ResteasyProviderFactory (org.jboss.resteasy.spi.ResteasyProviderFactory)2 OAuth2Constants (org.keycloak.OAuth2Constants)2 OAuthErrorException (org.keycloak.OAuthErrorException)2 ClientConnection (org.keycloak.common.ClientConnection)2 Details (org.keycloak.events.Details)2 Errors (org.keycloak.events.Errors)2 EventBuilder (org.keycloak.events.EventBuilder)2 JWSInput (org.keycloak.jose.jws.JWSInput)2 JWSInputException (org.keycloak.jose.jws.JWSInputException)2 ClientModel (org.keycloak.models.ClientModel)2 ClientSessionContext (org.keycloak.models.ClientSessionContext)2 KeycloakSession (org.keycloak.models.KeycloakSession)2 RealmModel (org.keycloak.models.RealmModel)2 UserModel (org.keycloak.models.UserModel)2