Search in sources :

Example 81 with AuthenticationSessionModel

use of org.keycloak.sessions.AuthenticationSessionModel 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 82 with AuthenticationSessionModel

use of org.keycloak.sessions.AuthenticationSessionModel in project keycloak by keycloak.

the class DefaultTokenExchangeProvider method exchangeClientToOIDCClient.

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) && OIDCAdvancedConfigWrapper.fromClientModel(client).isUseRefreshToken()) {
        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();
}
Also used : AuthenticationSessionManager(org.keycloak.services.managers.AuthenticationSessionManager) AuthenticationSessionModel(org.keycloak.sessions.AuthenticationSessionModel) RootAuthenticationSessionModel(org.keycloak.sessions.RootAuthenticationSessionModel) ClientSessionContext(org.keycloak.models.ClientSessionContext) RootAuthenticationSessionModel(org.keycloak.sessions.RootAuthenticationSessionModel) AccessTokenResponse(org.keycloak.representations.AccessTokenResponse)

Example 83 with AuthenticationSessionModel

use of org.keycloak.sessions.AuthenticationSessionModel in project keycloak by keycloak.

the class IdpEmailVerificationAuthenticator method authenticateImpl.

@Override
protected void authenticateImpl(AuthenticationFlowContext context, SerializedBrokeredIdentityContext serializedCtx, BrokeredIdentityContext brokerContext) {
    KeycloakSession session = context.getSession();
    RealmModel realm = context.getRealm();
    AuthenticationSessionModel authSession = context.getAuthenticationSession();
    if (realm.getSmtpConfig().isEmpty()) {
        ServicesLogger.LOGGER.smtpNotConfigured();
        context.attempted();
        return;
    }
    if (Objects.equals(authSession.getAuthNote(VERIFY_ACCOUNT_IDP_USERNAME), brokerContext.getUsername())) {
        UserModel existingUser = getExistingUser(session, realm, authSession);
        logger.debugf("User '%s' confirmed that wants to link with identity provider '%s' . Identity provider username is '%s' ", existingUser.getUsername(), brokerContext.getIdpConfig().getAlias(), brokerContext.getUsername());
        context.setUser(existingUser);
        context.success();
        return;
    }
    UserModel existingUser = getExistingUser(session, realm, authSession);
    // Do not allow resending e-mail by simple page refresh
    if (!Objects.equals(authSession.getAuthNote(Constants.VERIFY_EMAIL_KEY), existingUser.getEmail())) {
        authSession.setAuthNote(Constants.VERIFY_EMAIL_KEY, existingUser.getEmail());
        sendVerifyEmail(session, context, existingUser, brokerContext);
    } else {
        showEmailSentPage(context, brokerContext);
    }
}
Also used : RealmModel(org.keycloak.models.RealmModel) UserModel(org.keycloak.models.UserModel) AuthenticationSessionModel(org.keycloak.sessions.AuthenticationSessionModel) KeycloakSession(org.keycloak.models.KeycloakSession)

Example 84 with AuthenticationSessionModel

use of org.keycloak.sessions.AuthenticationSessionModel in project keycloak by keycloak.

the class IdpEmailVerificationAuthenticator method sendVerifyEmail.

private void sendVerifyEmail(KeycloakSession session, AuthenticationFlowContext context, UserModel existingUser, BrokeredIdentityContext brokerContext) throws UriBuilderException, IllegalArgumentException {
    RealmModel realm = session.getContext().getRealm();
    UriInfo uriInfo = session.getContext().getUri();
    AuthenticationSessionModel authSession = context.getAuthenticationSession();
    int validityInSecs = realm.getActionTokenGeneratedByUserLifespan(IdpVerifyAccountLinkActionToken.TOKEN_TYPE);
    int absoluteExpirationInSecs = Time.currentTime() + validityInSecs;
    EventBuilder event = context.getEvent().clone().event(EventType.SEND_IDENTITY_PROVIDER_LINK).user(existingUser).detail(Details.USERNAME, existingUser.getUsername()).detail(Details.EMAIL, existingUser.getEmail()).detail(Details.CODE_ID, authSession.getParentSession().getId()).removeDetail(Details.AUTH_METHOD).removeDetail(Details.AUTH_TYPE);
    String authSessionEncodedId = AuthenticationSessionCompoundId.fromAuthSession(authSession).getEncodedId();
    IdpVerifyAccountLinkActionToken token = new IdpVerifyAccountLinkActionToken(existingUser.getId(), existingUser.getEmail(), absoluteExpirationInSecs, authSessionEncodedId, brokerContext.getUsername(), brokerContext.getIdpConfig().getAlias(), authSession.getClient().getClientId());
    UriBuilder builder = Urls.actionTokenBuilder(uriInfo.getBaseUri(), token.serialize(session, realm, uriInfo), authSession.getClient().getClientId(), authSession.getTabId());
    String link = builder.queryParam(Constants.EXECUTION, context.getExecution().getId()).build(realm.getName()).toString();
    long expirationInMinutes = TimeUnit.SECONDS.toMinutes(validityInSecs);
    try {
        context.getSession().getProvider(EmailTemplateProvider.class).setRealm(realm).setAuthenticationSession(authSession).setUser(existingUser).setAttribute(EmailTemplateProvider.IDENTITY_PROVIDER_BROKER_CONTEXT, brokerContext).sendConfirmIdentityBrokerLink(link, expirationInMinutes);
        event.success();
    } catch (EmailException e) {
        event.error(Errors.EMAIL_SEND_FAILED);
        ServicesLogger.LOGGER.confirmBrokerEmailFailed(e);
        Response challenge = context.form().setError(Messages.EMAIL_SENT_ERROR).createErrorPage(Response.Status.INTERNAL_SERVER_ERROR);
        context.failure(AuthenticationFlowError.INTERNAL_ERROR, challenge);
        return;
    }
    showEmailSentPage(context, brokerContext);
}
Also used : RealmModel(org.keycloak.models.RealmModel) Response(javax.ws.rs.core.Response) AuthenticationSessionModel(org.keycloak.sessions.AuthenticationSessionModel) EventBuilder(org.keycloak.events.EventBuilder) EmailTemplateProvider(org.keycloak.email.EmailTemplateProvider) EmailException(org.keycloak.email.EmailException) IdpVerifyAccountLinkActionToken(org.keycloak.authentication.actiontoken.idpverifyemail.IdpVerifyAccountLinkActionToken) UriBuilder(javax.ws.rs.core.UriBuilder)

Example 85 with AuthenticationSessionModel

use of org.keycloak.sessions.AuthenticationSessionModel in project keycloak by keycloak.

the class CookieAuthenticator method authenticate.

@Override
public void authenticate(AuthenticationFlowContext context) {
    AuthenticationManager.AuthResult authResult = AuthenticationManager.authenticateIdentityCookie(context.getSession(), context.getRealm(), true);
    if (authResult == null) {
        context.attempted();
    } else {
        AuthenticationSessionModel authSession = context.getAuthenticationSession();
        LoginProtocol protocol = context.getSession().getProvider(LoginProtocol.class, authSession.getProtocol());
        authSession.setAuthNote(Constants.LEVEL_OF_AUTHENTICATION, authResult.getSession().getNote(Constants.LEVEL_OF_AUTHENTICATION));
        context.setUser(authResult.getUser());
        // Cookie re-authentication is skipped if re-authentication is required
        if (protocol.requireReauthentication(authResult.getSession(), authSession)) {
            // Full re-authentication, so we start with no loa
            authSession.setAuthNote(Constants.LEVEL_OF_AUTHENTICATION, String.valueOf(Constants.NO_LOA));
            context.setForwardedInfoMessage(Messages.REAUTHENTICATE);
            context.attempted();
        } else if (!AuthenticatorUtil.isLevelOfAuthenticationSatisfied(authSession)) {
            // Step-up authentication, we keep the loa from the existing user session.
            // The cookie alone is not enough and other authentications must follow.
            context.attempted();
        } else {
            // Cookie only authentication, no loa is returned
            authSession.setAuthNote(Constants.LEVEL_OF_AUTHENTICATION, String.valueOf(Constants.NO_LOA));
            authSession.setAuthNote(AuthenticationManager.SSO_AUTH, "true");
            context.attachUserSession(authResult.getSession());
            context.success();
        }
    }
}
Also used : AuthenticationManager(org.keycloak.services.managers.AuthenticationManager) AuthenticationSessionModel(org.keycloak.sessions.AuthenticationSessionModel) LoginProtocol(org.keycloak.protocol.LoginProtocol)

Aggregations

AuthenticationSessionModel (org.keycloak.sessions.AuthenticationSessionModel)89 RootAuthenticationSessionModel (org.keycloak.sessions.RootAuthenticationSessionModel)48 ClientModel (org.keycloak.models.ClientModel)27 UserModel (org.keycloak.models.UserModel)24 Response (javax.ws.rs.core.Response)23 RealmModel (org.keycloak.models.RealmModel)20 UserSessionModel (org.keycloak.models.UserSessionModel)20 AuthenticationSessionManager (org.keycloak.services.managers.AuthenticationSessionManager)18 KeycloakSession (org.keycloak.models.KeycloakSession)16 ClientSessionContext (org.keycloak.models.ClientSessionContext)13 LoginFormsProvider (org.keycloak.forms.login.LoginFormsProvider)10 URI (java.net.URI)9 UriBuilder (javax.ws.rs.core.UriBuilder)9 EventBuilder (org.keycloak.events.EventBuilder)9 LoginProtocol (org.keycloak.protocol.LoginProtocol)9 GET (javax.ws.rs.GET)8 Path (javax.ws.rs.Path)8 AuthenticationFlowException (org.keycloak.authentication.AuthenticationFlowException)8 OIDCLoginProtocol (org.keycloak.protocol.oidc.OIDCLoginProtocol)8 Map (java.util.Map)7