Search in sources :

Example 81 with Session

use of org.apache.catalina.Session in project keycloak by keycloak.

the class CatalinaSessionTokenStore method checkCurrentToken.

@Override
public void checkCurrentToken() {
    Session catalinaSession = request.getSessionInternal(false);
    if (catalinaSession == null)
        return;
    SerializableKeycloakAccount account = (SerializableKeycloakAccount) catalinaSession.getSession().getAttribute(SerializableKeycloakAccount.class.getName());
    if (account == null) {
        return;
    }
    RefreshableKeycloakSecurityContext session = account.getKeycloakSecurityContext();
    if (session == null)
        return;
    // just in case session got serialized
    if (session.getDeployment() == null)
        session.setCurrentRequestInfo(deployment, this);
    if (session.isActive() && !session.getDeployment().isAlwaysRefreshToken()) {
        request.setAttribute(KeycloakSecurityContext.class.getName(), session);
        request.setUserPrincipal(account.getPrincipal());
        request.setAuthType("KEYCLOAK");
        return;
    }
    // FYI: A refresh requires same scope, so same roles will be set.  Otherwise, refresh will fail and token will
    // not be updated
    boolean success = session.refreshExpiredToken(false);
    if (success && session.isActive()) {
        request.setAttribute(KeycloakSecurityContext.class.getName(), session);
        request.setUserPrincipal(account.getPrincipal());
        request.setAuthType("KEYCLOAK");
        return;
    }
    // Refresh failed, so user is already logged out from keycloak. Cleanup and expire our session
    log.fine("Cleanup and expire session " + catalinaSession.getId() + " after failed refresh");
    request.setUserPrincipal(null);
    request.setAuthType(null);
    cleanSession(catalinaSession);
    catalinaSession.expire();
}
Also used : RefreshableKeycloakSecurityContext(org.keycloak.adapters.RefreshableKeycloakSecurityContext) RefreshableKeycloakSecurityContext(org.keycloak.adapters.RefreshableKeycloakSecurityContext) KeycloakSecurityContext(org.keycloak.KeycloakSecurityContext) Session(org.apache.catalina.Session)

Example 82 with Session

use of org.apache.catalina.Session in project keycloak by keycloak.

the class CatalinaSamlSessionStore method saveAccount.

@Override
public void saveAccount(SamlSession account) {
    Session session = request.getSessionInternal(true);
    session.getSession().setAttribute(SamlSession.class.getName(), account);
    GenericPrincipal principal = (GenericPrincipal) session.getPrincipal();
    // in clustered environment in JBossWeb, principal is not serialized or saved
    if (principal == null) {
        principal = principalFactory.createPrincipal(request.getContext().getRealm(), account.getPrincipal(), account.getRoles());
        session.setPrincipal(principal);
        session.setAuthType("KEYCLOAK-SAML");
    }
    request.setUserPrincipal(principal);
    request.setAuthType("KEYCLOAK-SAML");
    String newId = changeSessionId(session);
    idMapperUpdater.map(idMapper, account.getSessionIndex(), account.getPrincipal().getSamlSubject(), newId);
}
Also used : GenericPrincipal(org.apache.catalina.realm.GenericPrincipal) HttpSession(javax.servlet.http.HttpSession) Session(org.apache.catalina.Session)

Example 83 with Session

use of org.apache.catalina.Session in project keycloak by keycloak.

the class CatalinaSamlSessionStore method isLoggedIn.

@Override
public boolean isLoggedIn() {
    Session session = request.getSessionInternal(false);
    if (session == null) {
        log.debug("session was null, returning null");
        return false;
    }
    final SamlSession samlSession = SamlUtil.validateSamlSession(session.getSession().getAttribute(SamlSession.class.getName()), deployment);
    if (samlSession == null) {
        return false;
    }
    GenericPrincipal principal = (GenericPrincipal) session.getPrincipal();
    // in clustered environment in JBossWeb, principal is not serialized or saved
    if (principal == null) {
        principal = principalFactory.createPrincipal(request.getContext().getRealm(), samlSession.getPrincipal(), samlSession.getRoles());
        session.setPrincipal(principal);
        session.setAuthType("KEYCLOAK-SAML");
    } else if (samlSession.getPrincipal().getName().equals(principal.getName())) {
        if (!principal.getUserPrincipal().getName().equals(samlSession.getPrincipal().getName())) {
            throw new RuntimeException("Unknown State");
        }
        log.debug("************principal already in");
        if (log.isDebugEnabled()) {
            for (String role : principal.getRoles()) {
                log.debug("principal role: " + role);
            }
        }
    }
    request.setUserPrincipal(principal);
    request.setAuthType("KEYCLOAK-SAML");
    restoreRequest();
    return true;
}
Also used : GenericPrincipal(org.apache.catalina.realm.GenericPrincipal) HttpSession(javax.servlet.http.HttpSession) Session(org.apache.catalina.Session)

Example 84 with Session

use of org.apache.catalina.Session in project tomcat by apache.

the class AuthenticatorBase method register.

/**
 * Register an authenticated Principal and authentication type in our
 * request, in the current session (if there is one), and with our
 * SingleSignOn valve, if there is one. Set the appropriate cookie to be
 * returned.
 *
 * @param request
 *            The servlet request we are processing
 * @param response
 *            The servlet response we are generating
 * @param principal
 *            The authenticated Principal to be registered
 * @param authType
 *            The authentication type to be registered
 * @param username
 *            Username used to authenticate (if any)
 * @param password
 *            Password used to authenticate (if any)
 * @param alwaysUseSession
 *            Should a session always be used once a user is authenticated?
 * @param cache
 *            Should we cache authenticated Principals if the request is part of an
 *            HTTP session?
 */
protected void register(Request request, HttpServletResponse response, Principal principal, String authType, String username, String password, boolean alwaysUseSession, boolean cache) {
    if (log.isDebugEnabled()) {
        String name = (principal == null) ? "none" : principal.getName();
        log.debug("Authenticated '" + name + "' with type '" + authType + "'");
    }
    // Cache the authentication information in our request
    request.setAuthType(authType);
    request.setUserPrincipal(principal);
    if (sendAuthInfoResponseHeaders && Boolean.TRUE.equals(request.getAttribute(Globals.REQUEST_FORWARDED_ATTRIBUTE))) {
        response.setHeader("remote-user", request.getRemoteUser());
        response.setHeader("auth-type", request.getAuthType());
    }
    Session session = request.getSessionInternal(false);
    if (session != null) {
        // the session ID. See BZ 59043.
        if (getChangeSessionIdOnAuthentication() && principal != null) {
            String newSessionId = changeSessionID(request, session);
            // If the current session ID is being tracked, update it.
            if (session.getNote(Constants.SESSION_ID_NOTE) != null) {
                session.setNote(Constants.SESSION_ID_NOTE, newSessionId);
            }
        }
    } else if (alwaysUseSession) {
        session = request.getSessionInternal(true);
    }
    // Cache the authentication information in our session, if any
    if (session != null && cache) {
        session.setAuthType(authType);
        session.setPrincipal(principal);
    }
    // Construct a cookie to be returned to the client
    if (sso == null) {
        return;
    }
    // Only create a new SSO entry if the SSO did not already set a note
    // for an existing entry (as it would do with subsequent requests
    // for DIGEST and SSL authenticated contexts)
    String ssoId = (String) request.getNote(Constants.REQ_SSOID_NOTE);
    if (ssoId == null) {
        // Construct a cookie to be returned to the client
        ssoId = sessionIdGenerator.generateSessionId();
        Cookie cookie = new Cookie(sso.getCookieName(), ssoId);
        cookie.setMaxAge(-1);
        cookie.setPath("/");
        // Bugzilla 41217
        cookie.setSecure(request.isSecure());
        // Bugzilla 34724
        String ssoDomain = sso.getCookieDomain();
        if (ssoDomain != null) {
            cookie.setDomain(ssoDomain);
        }
        // cookies
        if (request.getServletContext().getSessionCookieConfig().isHttpOnly() || request.getContext().getUseHttpOnly()) {
            cookie.setHttpOnly(true);
        }
        response.addCookie(cookie);
        // Register this principal with our SSO valve
        sso.register(ssoId, principal, authType, username, password);
        request.setNote(Constants.REQ_SSOID_NOTE, ssoId);
    } else {
        if (principal == null) {
            // Registering a programmatic logout
            sso.deregister(ssoId);
            request.removeNote(Constants.REQ_SSOID_NOTE);
            return;
        } else {
            // Update the SSO session with the latest authentication data
            sso.update(ssoId, principal, authType, username, password);
        }
    }
    // SSO entry will never be cleared if we don't associate the session
    if (session == null) {
        session = request.getSessionInternal(true);
    }
    sso.associate(ssoId, session);
}
Also used : Cookie(jakarta.servlet.http.Cookie) Session(org.apache.catalina.Session)

Example 85 with Session

use of org.apache.catalina.Session in project tomcat by apache.

the class FormAuthenticator method matchRequest.

/**
 * Does this request match the saved one (so that it must be the redirect
 * we signaled after successful authentication?
 *
 * @param request The request to be verified
 * @return <code>true</code> if the requests matched the saved one
 */
protected boolean matchRequest(Request request) {
    // Has a session been created?
    Session session = request.getSessionInternal(false);
    if (session == null) {
        return false;
    }
    // Is there a saved request?
    SavedRequest sreq = (SavedRequest) session.getNote(Constants.FORM_REQUEST_NOTE);
    if (sreq == null) {
        return false;
    }
    // Is there a saved principal?
    if (cache && session.getPrincipal() == null || !cache && request.getPrincipal() == null) {
        return false;
    }
    // Does session id match?
    if (getChangeSessionIdOnAuthentication()) {
        String expectedSessionId = (String) session.getNote(Constants.SESSION_ID_NOTE);
        if (expectedSessionId == null || !expectedSessionId.equals(request.getRequestedSessionId())) {
            return false;
        }
    }
    // Does the request URI match?
    String decodedRequestURI = request.getDecodedRequestURI();
    if (decodedRequestURI == null) {
        return false;
    }
    return decodedRequestURI.equals(sreq.getDecodedRequestURI());
}
Also used : Session(org.apache.catalina.Session)

Aggregations

Session (org.apache.catalina.Session)106 IOException (java.io.IOException)24 Manager (org.apache.catalina.Manager)22 Context (org.apache.catalina.Context)16 HttpSession (javax.servlet.http.HttpSession)13 StringManager (org.apache.tomcat.util.res.StringManager)13 HttpServletRequest (javax.servlet.http.HttpServletRequest)9 HttpSession (jakarta.servlet.http.HttpSession)7 GenericPrincipal (org.apache.catalina.realm.GenericPrincipal)7 Principal (java.security.Principal)6 Realm (org.apache.catalina.Realm)6 StandardContext (org.apache.catalina.core.StandardContext)6 ClusterSession (org.apache.catalina.ha.ClusterSession)6 DeltaSession (org.apache.catalina.ha.session.DeltaSession)6 Container (org.apache.catalina.Container)5 ArrayList (java.util.ArrayList)4 StandardSession (org.apache.catalina.session.StandardSession)4 BufferedOutputStream (java.io.BufferedOutputStream)3 File (java.io.File)3 ObjectOutputStream (java.io.ObjectOutputStream)3