Search in sources :

Example 46 with AuthenticationSessionModel

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

the class JBossLoggingEventListenerProvider method logEvent.

private void logEvent(Event event) {
    Logger.Level level = event.getError() != null ? errorLevel : successLevel;
    if (logger.isEnabled(level)) {
        StringBuilder sb = new StringBuilder();
        sb.append("type=");
        sb.append(event.getType());
        sb.append(", realmId=");
        sb.append(event.getRealmId());
        sb.append(", clientId=");
        sb.append(event.getClientId());
        sb.append(", userId=");
        sb.append(event.getUserId());
        sb.append(", ipAddress=");
        sb.append(event.getIpAddress());
        if (event.getError() != null) {
            sb.append(", error=");
            sb.append(event.getError());
        }
        if (event.getDetails() != null) {
            for (Map.Entry<String, String> e : event.getDetails().entrySet()) {
                sb.append(", ");
                sb.append(e.getKey());
                if (e.getValue() == null || e.getValue().indexOf(' ') == -1) {
                    sb.append("=");
                    sb.append(e.getValue());
                } else {
                    sb.append("='");
                    sb.append(e.getValue());
                    sb.append("'");
                }
            }
        }
        AuthenticationSessionModel authSession = session.getContext().getAuthenticationSession();
        if (authSession != null) {
            sb.append(", authSessionParentId=");
            sb.append(authSession.getParentSession().getId());
            sb.append(", authSessionTabId=");
            sb.append(authSession.getTabId());
        }
        if (logger.isTraceEnabled()) {
            setKeycloakContext(sb);
            if (StackUtil.isShortStackTraceEnabled()) {
                sb.append(", stackTrace=").append(StackUtil.getShortStackTrace());
            }
        }
        logger.log(logger.isTraceEnabled() ? Logger.Level.TRACE : level, sb.toString());
    }
}
Also used : AuthenticationSessionModel(org.keycloak.sessions.AuthenticationSessionModel) Logger(org.jboss.logging.Logger) Map(java.util.Map)

Example 47 with AuthenticationSessionModel

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

the class OIDCIdentityProvider method createAuthorizationUrl.

@Override
protected UriBuilder createAuthorizationUrl(AuthenticationRequest request) {
    UriBuilder uriBuilder = super.createAuthorizationUrl(request);
    String nonce = Base64Url.encode(SecretGenerator.getInstance().randomBytes(16));
    AuthenticationSessionModel authenticationSession = request.getAuthenticationSession();
    authenticationSession.setClientNote(BROKER_NONCE_PARAM, nonce);
    uriBuilder.queryParam(OIDCLoginProtocol.NONCE_PARAM, nonce);
    return uriBuilder;
}
Also used : AuthenticationSessionModel(org.keycloak.sessions.AuthenticationSessionModel) UriBuilder(javax.ws.rs.core.UriBuilder)

Example 48 with AuthenticationSessionModel

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

the class TwitterIdentityProvider method performLogin.

@Override
public Response performLogin(AuthenticationRequest request) {
    try (VaultStringSecret vaultStringSecret = session.vault().getStringSecret(getConfig().getClientSecret())) {
        Twitter twitter = new TwitterFactory().getInstance();
        twitter.setOAuthConsumer(getConfig().getClientId(), vaultStringSecret.get().orElse(getConfig().getClientSecret()));
        URI uri = new URI(request.getRedirectUri() + "?state=" + request.getState().getEncoded());
        RequestToken requestToken = twitter.getOAuthRequestToken(uri.toString());
        AuthenticationSessionModel authSession = request.getAuthenticationSession();
        authSession.setAuthNote(TWITTER_TOKEN, requestToken.getToken());
        authSession.setAuthNote(TWITTER_TOKENSECRET, requestToken.getTokenSecret());
        URI authenticationUrl = URI.create(requestToken.getAuthenticationURL());
        return Response.seeOther(authenticationUrl).build();
    } catch (Exception e) {
        throw new IdentityBrokerException("Could send authentication request to twitter.", e);
    }
}
Also used : AuthenticationSessionModel(org.keycloak.sessions.AuthenticationSessionModel) VaultStringSecret(org.keycloak.vault.VaultStringSecret) RequestToken(twitter4j.auth.RequestToken) IdentityBrokerException(org.keycloak.broker.provider.IdentityBrokerException) Twitter(twitter4j.Twitter) TwitterFactory(twitter4j.TwitterFactory) URI(java.net.URI) IdentityBrokerException(org.keycloak.broker.provider.IdentityBrokerException) WebApplicationException(javax.ws.rs.WebApplicationException)

Example 49 with AuthenticationSessionModel

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

the class RestartLoginCookie method restartSession.

public static AuthenticationSessionModel restartSession(KeycloakSession session, RealmModel realm, RootAuthenticationSessionModel rootSession, String expectedClientId, Cookie cook) throws Exception {
    String encodedCookie = cook.getValue();
    RestartLoginCookie cookie = session.tokens().decode(encodedCookie, RestartLoginCookie.class);
    if (cookie == null) {
        logger.debug("Failed to verify encoded RestartLoginCookie");
        return null;
    }
    ClientModel client = realm.getClientByClientId(cookie.getClientId());
    if (client == null)
        return null;
    // Restart just if client from cookie matches client from the URL.
    if (!client.getClientId().equals(expectedClientId)) {
        logger.debugf("Skip restarting from the KC_RESTART. Clients doesn't match: Cookie client: %s, Requested client: %s", client.getClientId(), expectedClientId);
        return null;
    }
    // Need to create brand new session and setup cookie
    if (rootSession == null) {
        rootSession = new AuthenticationSessionManager(session).createAuthenticationSession(realm, true);
    }
    AuthenticationSessionModel authSession = rootSession.createAuthenticationSession(client);
    authSession.setProtocol(cookie.getAuthMethod());
    authSession.setRedirectUri(cookie.getRedirectUri());
    authSession.setAction(cookie.getAction());
    for (Map.Entry<String, String> entry : cookie.getNotes().entrySet()) {
        authSession.setClientNote(entry.getKey(), entry.getValue());
    }
    return authSession;
}
Also used : AuthenticationSessionManager(org.keycloak.services.managers.AuthenticationSessionManager) ClientModel(org.keycloak.models.ClientModel) AuthenticationSessionModel(org.keycloak.sessions.AuthenticationSessionModel) RootAuthenticationSessionModel(org.keycloak.sessions.RootAuthenticationSessionModel) HashMap(java.util.HashMap) Map(java.util.Map)

Example 50 with AuthenticationSessionModel

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

the class IdentityBrokerService method afterPostBrokerLoginFlow.

// Callback from LoginActionsService after postBrokerLogin flow is finished
@GET
@NoCache
@Path("/after-post-broker-login")
public Response afterPostBrokerLoginFlow(@QueryParam(LoginActionsService.SESSION_CODE) String code, @QueryParam("client_id") String clientId, @QueryParam(Constants.TAB_ID) String tabId) {
    AuthenticationSessionModel authenticationSession = parseSessionCode(code, clientId, tabId);
    try {
        SerializedBrokeredIdentityContext serializedCtx = SerializedBrokeredIdentityContext.readFromAuthenticationSession(authenticationSession, PostBrokerLoginConstants.PBL_BROKERED_IDENTITY_CONTEXT);
        if (serializedCtx == null) {
            throw new IdentityBrokerException("Not found serialized context in clientSession. Note " + PostBrokerLoginConstants.PBL_BROKERED_IDENTITY_CONTEXT + " was null");
        }
        BrokeredIdentityContext context = serializedCtx.deserialize(session, authenticationSession);
        String wasFirstBrokerLoginNote = authenticationSession.getAuthNote(PostBrokerLoginConstants.PBL_AFTER_FIRST_BROKER_LOGIN);
        boolean wasFirstBrokerLogin = Boolean.parseBoolean(wasFirstBrokerLoginNote);
        // Ensure the post-broker-login flow was successfully finished
        String authStateNoteKey = PostBrokerLoginConstants.PBL_AUTH_STATE_PREFIX + context.getIdpConfig().getAlias();
        String authState = authenticationSession.getAuthNote(authStateNoteKey);
        if (!Boolean.parseBoolean(authState)) {
            throw new IdentityBrokerException("Invalid request. Not found the flag that post-broker-login flow was finished");
        }
        // remove notes
        authenticationSession.removeAuthNote(PostBrokerLoginConstants.PBL_BROKERED_IDENTITY_CONTEXT);
        authenticationSession.removeAuthNote(PostBrokerLoginConstants.PBL_AFTER_FIRST_BROKER_LOGIN);
        return afterPostBrokerLoginFlowSuccess(authenticationSession, context, wasFirstBrokerLogin);
    } catch (IdentityBrokerException e) {
        return redirectToErrorPage(authenticationSession, Response.Status.INTERNAL_SERVER_ERROR, Messages.IDENTITY_PROVIDER_UNEXPECTED_ERROR, e);
    }
}
Also used : AuthenticationSessionModel(org.keycloak.sessions.AuthenticationSessionModel) RootAuthenticationSessionModel(org.keycloak.sessions.RootAuthenticationSessionModel) IdentityBrokerException(org.keycloak.broker.provider.IdentityBrokerException) SerializedBrokeredIdentityContext(org.keycloak.authentication.authenticators.broker.util.SerializedBrokeredIdentityContext) BrokeredIdentityContext(org.keycloak.broker.provider.BrokeredIdentityContext) SerializedBrokeredIdentityContext(org.keycloak.authentication.authenticators.broker.util.SerializedBrokeredIdentityContext) Path(javax.ws.rs.Path) GET(javax.ws.rs.GET) NoCache(org.jboss.resteasy.annotations.cache.NoCache)

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