Search in sources :

Example 26 with CorsErrorResponseException

use of org.keycloak.services.CorsErrorResponseException in project keycloak by keycloak.

the class TokenEndpoint method refreshTokenGrant.

public Response refreshTokenGrant() {
    String refreshToken = formParams.getFirst(OAuth2Constants.REFRESH_TOKEN);
    if (refreshToken == null) {
        throw new CorsErrorResponseException(cors, OAuthErrorException.INVALID_REQUEST, "No refresh token", Response.Status.BAD_REQUEST);
    }
    try {
        session.clientPolicy().triggerOnEvent(new TokenRefreshContext(formParams));
    } catch (ClientPolicyException cpe) {
        event.error(cpe.getError());
        throw new CorsErrorResponseException(cors, cpe.getError(), cpe.getErrorDetail(), cpe.getErrorStatus());
    }
    AccessTokenResponse res;
    try {
        // KEYCLOAK-6771 Certificate Bound Token
        TokenManager.RefreshResult result = tokenManager.refreshAccessToken(session, session.getContext().getUri(), clientConnection, realm, client, refreshToken, event, headers, request);
        res = result.getResponse();
        if (!result.isOfflineToken()) {
            UserSessionModel userSession = session.sessions().getUserSession(realm, res.getSessionState());
            AuthenticatedClientSessionModel clientSession = userSession.getAuthenticatedClientSessionByClient(client.getId());
            updateClientSession(clientSession);
            updateUserSessionFromClientAuth(userSession);
        }
    } catch (OAuthErrorException e) {
        logger.trace(e.getMessage(), e);
        // KEYCLOAK-6771 Certificate Bound Token
        if (MtlsHoKTokenUtil.CERT_VERIFY_ERROR_DESC.equals(e.getDescription())) {
            event.error(Errors.NOT_ALLOWED);
            throw new CorsErrorResponseException(cors, e.getError(), e.getDescription(), Response.Status.UNAUTHORIZED);
        } else {
            event.error(Errors.INVALID_TOKEN);
            throw new CorsErrorResponseException(cors, e.getError(), e.getDescription(), Response.Status.BAD_REQUEST);
        }
    }
    event.success();
    return cors.builder(Response.ok(res, MediaType.APPLICATION_JSON_TYPE)).build();
}
Also used : UserSessionModel(org.keycloak.models.UserSessionModel) OAuthErrorException(org.keycloak.OAuthErrorException) TokenRefreshContext(org.keycloak.services.clientpolicy.context.TokenRefreshContext) AuthenticatedClientSessionModel(org.keycloak.models.AuthenticatedClientSessionModel) CorsErrorResponseException(org.keycloak.services.CorsErrorResponseException) TokenManager(org.keycloak.protocol.oidc.TokenManager) AccessTokenResponse(org.keycloak.representations.AccessTokenResponse) ClientPolicyException(org.keycloak.services.clientpolicy.ClientPolicyException)

Example 27 with CorsErrorResponseException

use of org.keycloak.services.CorsErrorResponseException in project keycloak by keycloak.

the class TokenRevocationEndpoint method checkUser.

private void checkUser() {
    if (token.getSessionState() == null) {
        user = TokenManager.lookupUserFromStatelessToken(session, realm, token);
    } else {
        UserSessionModel userSession = new UserSessionCrossDCManager(session).getUserSessionWithClient(realm, token.getSessionState(), false, client.getId());
        if (userSession == null) {
            userSession = new UserSessionCrossDCManager(session).getUserSessionWithClient(realm, token.getSessionState(), true, client.getId());
            if (userSession == null) {
                event.error(Errors.USER_SESSION_NOT_FOUND);
                throw new CorsErrorResponseException(cors, OAuthErrorException.INVALID_TOKEN, "Invalid token", Response.Status.OK);
            }
        }
        user = userSession.getUser();
    }
    if (user == null) {
        event.error(Errors.USER_NOT_FOUND);
        throw new CorsErrorResponseException(cors, OAuthErrorException.INVALID_TOKEN, "Invalid token", Response.Status.OK);
    }
    event.user(user);
}
Also used : UserSessionModel(org.keycloak.models.UserSessionModel) CorsErrorResponseException(org.keycloak.services.CorsErrorResponseException) UserSessionCrossDCManager(org.keycloak.services.managers.UserSessionCrossDCManager)

Example 28 with CorsErrorResponseException

use of org.keycloak.services.CorsErrorResponseException in project keycloak by keycloak.

the class TokenRevocationEndpoint method revoke.

@POST
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
public Response revoke() {
    event.event(EventType.REVOKE_GRANT);
    cors = Cors.add(request).auth().allowedMethods("POST").auth().exposedHeaders(Cors.ACCESS_CONTROL_ALLOW_METHODS);
    checkSsl();
    checkRealm();
    checkClient();
    formParams = request.getDecodedFormParameters();
    checkParameterDuplicated(formParams);
    try {
        session.clientPolicy().triggerOnEvent(new TokenRevokeContext(formParams));
    } catch (ClientPolicyException cpe) {
        event.error(cpe.getError());
        throw new CorsErrorResponseException(cors, cpe.getError(), cpe.getErrorDetail(), cpe.getErrorStatus());
    }
    checkToken();
    checkIssuedFor();
    checkUser();
    if (TokenUtil.TOKEN_TYPE_REFRESH.equals(token.getType()) || TokenUtil.TOKEN_TYPE_OFFLINE.equals(token.getType())) {
        revokeClient();
        event.detail(Details.REVOKED_CLIENT, client.getClientId());
    } else {
        revokeAccessToken();
        event.detail(Details.TOKEN_ID, token.getId());
    }
    event.success();
    session.getProvider(SecurityHeadersProvider.class).options().allowEmptyContentType();
    return cors.builder(Response.ok()).build();
}
Also used : CorsErrorResponseException(org.keycloak.services.CorsErrorResponseException) TokenRevokeContext(org.keycloak.services.clientpolicy.context.TokenRevokeContext) ClientPolicyException(org.keycloak.services.clientpolicy.ClientPolicyException) POST(javax.ws.rs.POST) Consumes(javax.ws.rs.Consumes)

Example 29 with CorsErrorResponseException

use of org.keycloak.services.CorsErrorResponseException in project keycloak by keycloak.

the class DefaultTokenExchangeProvider method exchangeClientToSAML2Client.

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();
}
Also used : AuthenticationSessionModel(org.keycloak.sessions.AuthenticationSessionModel) RootAuthenticationSessionModel(org.keycloak.sessions.RootAuthenticationSessionModel) TokenExchangeSamlProtocol(org.keycloak.protocol.oidc.endpoints.TokenEndpoint.TokenExchangeSamlProtocol) SamlProtocol(org.keycloak.protocol.saml.SamlProtocol) TokenExchangeSamlProtocol(org.keycloak.protocol.oidc.endpoints.TokenEndpoint.TokenExchangeSamlProtocol) SamlClient(org.keycloak.protocol.saml.SamlClient) SamlService(org.keycloak.protocol.saml.SamlService) AccessTokenResponse(org.keycloak.representations.AccessTokenResponse) Response(javax.ws.rs.core.Response) LoginProtocolFactory(org.keycloak.protocol.LoginProtocolFactory) ClientSessionContext(org.keycloak.models.ClientSessionContext) CorsErrorResponseException(org.keycloak.services.CorsErrorResponseException) LoginProtocol(org.keycloak.protocol.LoginProtocol) AccessTokenResponse(org.keycloak.representations.AccessTokenResponse)

Example 30 with CorsErrorResponseException

use of org.keycloak.services.CorsErrorResponseException in project keycloak by keycloak.

the class DefaultTokenExchangeProvider method exchangeClientToClient.

protected Response exchangeClientToClient(UserModel targetUser, UserSessionModel targetUserSession) {
    String requestedTokenType = formParams.getFirst(OAuth2Constants.REQUESTED_TOKEN_TYPE);
    if (requestedTokenType == null) {
        requestedTokenType = OAuth2Constants.REFRESH_TOKEN_TYPE;
    } else if (!requestedTokenType.equals(OAuth2Constants.ACCESS_TOKEN_TYPE) && !requestedTokenType.equals(OAuth2Constants.REFRESH_TOKEN_TYPE) && !requestedTokenType.equals(OAuth2Constants.SAML2_TOKEN_TYPE)) {
        event.detail(Details.REASON, "requested_token_type unsupported");
        event.error(Errors.INVALID_REQUEST);
        throw new CorsErrorResponseException(cors, OAuthErrorException.INVALID_REQUEST, "requested_token_type unsupported", Response.Status.BAD_REQUEST);
    }
    ClientModel targetClient = client;
    String audience = formParams.getFirst(OAuth2Constants.AUDIENCE);
    if (audience != null) {
        targetClient = realm.getClientByClientId(audience);
        if (targetClient == null) {
            event.detail(Details.REASON, "audience not found");
            event.error(Errors.CLIENT_NOT_FOUND);
            throw new CorsErrorResponseException(cors, OAuthErrorException.INVALID_CLIENT, "Audience not found", Response.Status.BAD_REQUEST);
        }
    }
    if (targetClient.isConsentRequired()) {
        event.detail(Details.REASON, "audience requires consent");
        event.error(Errors.CONSENT_DENIED);
        throw new CorsErrorResponseException(cors, OAuthErrorException.INVALID_CLIENT, "Client requires user consent", Response.Status.BAD_REQUEST);
    }
    if (!targetClient.equals(client) && !AdminPermissions.management(session, realm).clients().canExchangeTo(client, targetClient)) {
        event.detail(Details.REASON, "client not allowed to exchange to audience");
        event.error(Errors.NOT_ALLOWED);
        throw new CorsErrorResponseException(cors, OAuthErrorException.ACCESS_DENIED, "Client not allowed to exchange", Response.Status.FORBIDDEN);
    }
    String scope = formParams.getFirst(OAuth2Constants.SCOPE);
    switch(requestedTokenType) {
        case OAuth2Constants.ACCESS_TOKEN_TYPE:
        case OAuth2Constants.REFRESH_TOKEN_TYPE:
            return exchangeClientToOIDCClient(targetUser, targetUserSession, requestedTokenType, targetClient, audience, scope);
        case OAuth2Constants.SAML2_TOKEN_TYPE:
            return exchangeClientToSAML2Client(targetUser, targetUserSession, requestedTokenType, targetClient, audience, scope);
    }
    throw new CorsErrorResponseException(cors, OAuthErrorException.INVALID_REQUEST, "requested_token_type unsupported", Response.Status.BAD_REQUEST);
}
Also used : ClientModel(org.keycloak.models.ClientModel) CorsErrorResponseException(org.keycloak.services.CorsErrorResponseException)

Aggregations

CorsErrorResponseException (org.keycloak.services.CorsErrorResponseException)30 UserSessionModel (org.keycloak.models.UserSessionModel)13 UserModel (org.keycloak.models.UserModel)11 ClientSessionContext (org.keycloak.models.ClientSessionContext)10 ClientModel (org.keycloak.models.ClientModel)9 ClientPolicyException (org.keycloak.services.clientpolicy.ClientPolicyException)9 OAuthErrorException (org.keycloak.OAuthErrorException)8 AccessTokenResponse (org.keycloak.representations.AccessTokenResponse)8 DefaultClientSessionContext (org.keycloak.services.util.DefaultClientSessionContext)8 Response (javax.ws.rs.core.Response)7 AuthenticationSessionModel (org.keycloak.sessions.AuthenticationSessionModel)6 RootAuthenticationSessionModel (org.keycloak.sessions.RootAuthenticationSessionModel)6 AuthorizationProvider (org.keycloak.authorization.AuthorizationProvider)5 AuthenticatedClientSessionModel (org.keycloak.models.AuthenticatedClientSessionModel)5 TokenManager (org.keycloak.protocol.oidc.TokenManager)5 AccessToken (org.keycloak.representations.AccessToken)5 AuthenticationSessionManager (org.keycloak.services.managers.AuthenticationSessionManager)4 EventBuilder (org.keycloak.events.EventBuilder)3 JWSInput (org.keycloak.jose.jws.JWSInput)3 JWSInputException (org.keycloak.jose.jws.JWSInputException)3