Search in sources :

Example 1 with AuthenticationProcessor

use of org.keycloak.authentication.AuthenticationProcessor in project keycloak by keycloak.

the class IdentityBrokerService method browserAuthentication.

protected Response browserAuthentication(AuthenticationSessionModel authSession, String errorMessage) {
    this.event.event(EventType.LOGIN);
    AuthenticationFlowModel flow = AuthenticationFlowResolver.resolveBrowserFlow(authSession);
    String flowId = flow.getId();
    AuthenticationProcessor processor = new AuthenticationProcessor();
    processor.setAuthenticationSession(authSession).setFlowPath(LoginActionsService.AUTHENTICATE_PATH).setFlowId(flowId).setBrowserFlow(true).setConnection(clientConnection).setEventBuilder(event).setRealm(realmModel).setSession(session).setUriInfo(session.getContext().getUri()).setRequest(request);
    if (errorMessage != null)
        processor.setForwardedErrorMessage(new FormMessage(null, errorMessage));
    try {
        CacheControlUtil.noBackButtonCacheControlHeader();
        return processor.authenticate();
    } catch (Exception e) {
        return processor.handleBrowserException(e);
    }
}
Also used : AuthenticationFlowModel(org.keycloak.models.AuthenticationFlowModel) AuthenticationProcessor(org.keycloak.authentication.AuthenticationProcessor) FormMessage(org.keycloak.models.utils.FormMessage) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) WebApplicationException(javax.ws.rs.WebApplicationException) IOException(java.io.IOException) IdentityBrokerException(org.keycloak.broker.provider.IdentityBrokerException) OAuthErrorException(org.keycloak.OAuthErrorException) NotFoundException(javax.ws.rs.NotFoundException) ErrorPageException(org.keycloak.services.ErrorPageException)

Example 2 with AuthenticationProcessor

use of org.keycloak.authentication.AuthenticationProcessor in project keycloak by keycloak.

the class LoginActionsService method brokerLoginFlow.

protected Response brokerLoginFlow(String authSessionId, String code, String execution, String clientId, String tabId, String flowPath) {
    boolean firstBrokerLogin = flowPath.equals(FIRST_BROKER_LOGIN_PATH);
    EventType eventType = firstBrokerLogin ? EventType.IDENTITY_PROVIDER_FIRST_LOGIN : EventType.IDENTITY_PROVIDER_POST_LOGIN;
    event.event(eventType);
    SessionCodeChecks checks = checksForCode(authSessionId, code, execution, clientId, tabId, flowPath);
    if (!checks.verifyActiveAndValidAction(AuthenticationSessionModel.Action.AUTHENTICATE.name(), ClientSessionCode.ActionType.LOGIN)) {
        return checks.getResponse();
    }
    event.detail(Details.CODE_ID, code);
    final AuthenticationSessionModel authSession = checks.getAuthenticationSession();
    processLocaleParam(authSession);
    String noteKey = firstBrokerLogin ? AbstractIdpAuthenticator.BROKERED_CONTEXT_NOTE : PostBrokerLoginConstants.PBL_BROKERED_IDENTITY_CONTEXT;
    SerializedBrokeredIdentityContext serializedCtx = SerializedBrokeredIdentityContext.readFromAuthenticationSession(authSession, noteKey);
    if (serializedCtx == null) {
        ServicesLogger.LOGGER.notFoundSerializedCtxInClientSession(noteKey);
        throw new WebApplicationException(ErrorPage.error(session, authSession, Response.Status.BAD_REQUEST, "Not found serialized context in authenticationSession."));
    }
    BrokeredIdentityContext brokerContext = serializedCtx.deserialize(session, authSession);
    final String identityProviderAlias = brokerContext.getIdpConfig().getAlias();
    String flowId = firstBrokerLogin ? brokerContext.getIdpConfig().getFirstBrokerLoginFlowId() : brokerContext.getIdpConfig().getPostBrokerLoginFlowId();
    if (flowId == null) {
        ServicesLogger.LOGGER.flowNotConfigForIDP(identityProviderAlias);
        throw new WebApplicationException(ErrorPage.error(session, authSession, Response.Status.BAD_REQUEST, "Flow not configured for identity provider"));
    }
    AuthenticationFlowModel brokerLoginFlow = realm.getAuthenticationFlowById(flowId);
    if (brokerLoginFlow == null) {
        ServicesLogger.LOGGER.flowNotFoundForIDP(flowId, identityProviderAlias);
        throw new WebApplicationException(ErrorPage.error(session, authSession, Response.Status.BAD_REQUEST, "Flow not found for identity provider"));
    }
    event.detail(Details.IDENTITY_PROVIDER, identityProviderAlias).detail(Details.IDENTITY_PROVIDER_USERNAME, brokerContext.getUsername());
    AuthenticationProcessor processor = new AuthenticationProcessor() {

        @Override
        public Response authenticateOnly() throws AuthenticationFlowException {
            Response challenge = super.authenticateOnly();
            if (challenge != null) {
                if ("true".equals(authenticationSession.getAuthNote(FORWARDED_PASSIVE_LOGIN))) {
                    // forwarded passive login is incompatible with challenges created by the broker flows.
                    logger.errorf("Challenge encountered when executing %s flow. Auth requests with prompt=none are incompatible with challenges", flowPath);
                    LoginProtocol protocol = session.getProvider(LoginProtocol.class, authSession.getProtocol());
                    protocol.setRealm(realm).setHttpHeaders(headers).setUriInfo(session.getContext().getUri()).setEventBuilder(event);
                    return protocol.sendError(authSession, Error.PASSIVE_INTERACTION_REQUIRED);
                }
            }
            return challenge;
        }

        @Override
        protected Response authenticationComplete() {
            if (firstBrokerLogin) {
                authSession.setAuthNote(AbstractIdpAuthenticator.FIRST_BROKER_LOGIN_SUCCESS, identityProviderAlias);
            } else {
                String authStateNoteKey = PostBrokerLoginConstants.PBL_AUTH_STATE_PREFIX + identityProviderAlias;
                authSession.setAuthNote(authStateNoteKey, "true");
            }
            return redirectToAfterBrokerLoginEndpoint(authSession, firstBrokerLogin);
        }
    };
    return processFlow(checks.isActionRequest(), execution, authSession, flowPath, brokerLoginFlow, null, processor);
}
Also used : Response(javax.ws.rs.core.Response) AuthenticationSessionModel(org.keycloak.sessions.AuthenticationSessionModel) RootAuthenticationSessionModel(org.keycloak.sessions.RootAuthenticationSessionModel) WebApplicationException(javax.ws.rs.WebApplicationException) EventType(org.keycloak.events.EventType) AuthenticationFlowModel(org.keycloak.models.AuthenticationFlowModel) SerializedBrokeredIdentityContext(org.keycloak.authentication.authenticators.broker.util.SerializedBrokeredIdentityContext) AuthenticationProcessor(org.keycloak.authentication.AuthenticationProcessor) OIDCLoginProtocol(org.keycloak.protocol.oidc.OIDCLoginProtocol) LoginProtocol(org.keycloak.protocol.LoginProtocol) BrokeredIdentityContext(org.keycloak.broker.provider.BrokeredIdentityContext) SerializedBrokeredIdentityContext(org.keycloak.authentication.authenticators.broker.util.SerializedBrokeredIdentityContext)

Example 3 with AuthenticationProcessor

use of org.keycloak.authentication.AuthenticationProcessor in project keycloak by keycloak.

the class TokenEndpoint method resourceOwnerPasswordCredentialsGrant.

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);
    }
    try {
        session.clientPolicy().triggerOnEvent(new ResourceOwnerPasswordCredentialsContext(formParams));
    } catch (ClientPolicyException cpe) {
        event.error(cpe.getError());
        throw new CorsErrorResponseException(cors, cpe.getError(), cpe.getErrorDetail(), cpe.getErrorStatus());
    }
    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) {
        // Remove authentication session as "Resource Owner Password Credentials Grant" is single-request scoped authentication
        new AuthenticationSessionManager(session).removeAuthenticationSession(realm, authSession, false);
        cors.build(httpResponse);
        return challenge;
    }
    processor.evaluateRequiredActionTriggers();
    UserModel user = authSession.getAuthenticatedUser();
    if (user.getRequiredActionsStream().count() > 0 || authSession.getRequiredActions().size() > 0) {
        // Remove authentication session as "Resource Owner Password Credentials Grant" is single-request scoped authentication
        new AuthenticationSessionManager(session).removeAuthenticationSession(realm, authSession, false);
        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();
    if (OIDCAdvancedConfigWrapper.fromClientModel(client).isUseRefreshToken()) {
        responseBuilder.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();
    AuthenticationManager.logSuccess(session, authSession);
    return cors.builder(Response.ok(res, MediaType.APPLICATION_JSON_TYPE)).build();
}
Also used : AuthenticationSessionModel(org.keycloak.sessions.AuthenticationSessionModel) RootAuthenticationSessionModel(org.keycloak.sessions.RootAuthenticationSessionModel) UserSessionModel(org.keycloak.models.UserSessionModel) ClientPolicyException(org.keycloak.services.clientpolicy.ClientPolicyException) AuthenticationSessionManager(org.keycloak.services.managers.AuthenticationSessionManager) AccessTokenResponse(org.keycloak.representations.AccessTokenResponse) Response(javax.ws.rs.core.Response) HttpResponse(org.jboss.resteasy.spi.HttpResponse) UserModel(org.keycloak.models.UserModel) DefaultClientSessionContext(org.keycloak.services.util.DefaultClientSessionContext) ClientSessionContext(org.keycloak.models.ClientSessionContext) ResourceOwnerPasswordCredentialsContext(org.keycloak.services.clientpolicy.context.ResourceOwnerPasswordCredentialsContext) RootAuthenticationSessionModel(org.keycloak.sessions.RootAuthenticationSessionModel) AuthenticationFlowModel(org.keycloak.models.AuthenticationFlowModel) CorsErrorResponseException(org.keycloak.services.CorsErrorResponseException) AuthenticationProcessor(org.keycloak.authentication.AuthenticationProcessor) TokenManager(org.keycloak.protocol.oidc.TokenManager) AccessTokenResponse(org.keycloak.representations.AccessTokenResponse)

Example 4 with AuthenticationProcessor

use of org.keycloak.authentication.AuthenticationProcessor in project keycloak by keycloak.

the class AuthorizationEndpoint method buildRegister.

private Response buildRegister() {
    authManager.expireIdentityCookie(realm, session.getContext().getUri(), clientConnection);
    AuthenticationFlowModel flow = realm.getRegistrationFlow();
    String flowId = flow.getId();
    AuthenticationProcessor processor = createProcessor(authenticationSession, flowId, LoginActionsService.REGISTRATION_PATH);
    authenticationSession.setClientNote(APP_INITIATED_FLOW, LoginActionsService.REGISTRATION_PATH);
    return processor.authenticate();
}
Also used : AuthenticationFlowModel(org.keycloak.models.AuthenticationFlowModel) AuthenticationProcessor(org.keycloak.authentication.AuthenticationProcessor)

Example 5 with AuthenticationProcessor

use of org.keycloak.authentication.AuthenticationProcessor in project keycloak by keycloak.

the class AuthorizationEndpoint method buildForgotCredential.

private Response buildForgotCredential() {
    authManager.expireIdentityCookie(realm, session.getContext().getUri(), clientConnection);
    AuthenticationFlowModel flow = realm.getResetCredentialsFlow();
    String flowId = flow.getId();
    AuthenticationProcessor processor = createProcessor(authenticationSession, flowId, LoginActionsService.RESET_CREDENTIALS_PATH);
    authenticationSession.setClientNote(APP_INITIATED_FLOW, LoginActionsService.RESET_CREDENTIALS_PATH);
    return processor.authenticate();
}
Also used : AuthenticationFlowModel(org.keycloak.models.AuthenticationFlowModel) AuthenticationProcessor(org.keycloak.authentication.AuthenticationProcessor)

Aggregations

AuthenticationProcessor (org.keycloak.authentication.AuthenticationProcessor)10 AuthenticationFlowModel (org.keycloak.models.AuthenticationFlowModel)7 Response (javax.ws.rs.core.Response)5 WebApplicationException (javax.ws.rs.WebApplicationException)3 HttpResponse (org.jboss.resteasy.spi.HttpResponse)2 ClientModel (org.keycloak.models.ClientModel)2 ErrorPageException (org.keycloak.services.ErrorPageException)2 AuthenticationSessionModel (org.keycloak.sessions.AuthenticationSessionModel)2 RootAuthenticationSessionModel (org.keycloak.sessions.RootAuthenticationSessionModel)2 IOException (java.io.IOException)1 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)1 NotFoundException (javax.ws.rs.NotFoundException)1 HttpRequest (org.jboss.resteasy.spi.HttpRequest)1 OAuthErrorException (org.keycloak.OAuthErrorException)1 SerializedBrokeredIdentityContext (org.keycloak.authentication.authenticators.broker.util.SerializedBrokeredIdentityContext)1 BrokeredIdentityContext (org.keycloak.broker.provider.BrokeredIdentityContext)1 IdentityBrokerException (org.keycloak.broker.provider.IdentityBrokerException)1 EventType (org.keycloak.events.EventType)1 ClientSessionContext (org.keycloak.models.ClientSessionContext)1 RealmModel (org.keycloak.models.RealmModel)1