Search in sources :

Example 1 with SessionAuthenticationException

use of org.springframework.security.web.authentication.session.SessionAuthenticationException in project spring-security by spring-projects.

the class SessionManagementFilterTests method strategyFailureInvokesFailureHandler.

@Test
public void strategyFailureInvokesFailureHandler() throws Exception {
    SecurityContextRepository repo = mock(SecurityContextRepository.class);
    // repo will return false to containsContext()
    SessionAuthenticationStrategy strategy = mock(SessionAuthenticationStrategy.class);
    AuthenticationFailureHandler failureHandler = mock(AuthenticationFailureHandler.class);
    SessionManagementFilter filter = new SessionManagementFilter(repo, strategy);
    filter.setAuthenticationFailureHandler(failureHandler);
    HttpServletRequest request = new MockHttpServletRequest();
    HttpServletResponse response = new MockHttpServletResponse();
    FilterChain fc = mock(FilterChain.class);
    authenticateUser();
    SessionAuthenticationException exception = new SessionAuthenticationException("Failure");
    willThrow(exception).given(strategy).onAuthentication(SecurityContextHolder.getContext().getAuthentication(), request, response);
    filter.doFilter(request, response, fc);
    verifyZeroInteractions(fc);
    verify(failureHandler).onAuthenticationFailure(request, response, exception);
}
Also used : HttpServletRequest(jakarta.servlet.http.HttpServletRequest) MockHttpServletRequest(org.springframework.mock.web.MockHttpServletRequest) SessionAuthenticationException(org.springframework.security.web.authentication.session.SessionAuthenticationException) SessionAuthenticationStrategy(org.springframework.security.web.authentication.session.SessionAuthenticationStrategy) MockHttpServletRequest(org.springframework.mock.web.MockHttpServletRequest) MockFilterChain(org.springframework.mock.web.MockFilterChain) FilterChain(jakarta.servlet.FilterChain) MockHttpServletResponse(org.springframework.mock.web.MockHttpServletResponse) HttpServletResponse(jakarta.servlet.http.HttpServletResponse) SecurityContextRepository(org.springframework.security.web.context.SecurityContextRepository) AuthenticationFailureHandler(org.springframework.security.web.authentication.AuthenticationFailureHandler) MockHttpServletResponse(org.springframework.mock.web.MockHttpServletResponse) Test(org.junit.jupiter.api.Test)

Example 2 with SessionAuthenticationException

use of org.springframework.security.web.authentication.session.SessionAuthenticationException in project spring-security by spring-projects.

the class SessionManagementFilter method doFilter.

public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
    HttpServletRequest request = (HttpServletRequest) req;
    HttpServletResponse response = (HttpServletResponse) res;
    if (request.getAttribute(FILTER_APPLIED) != null) {
        chain.doFilter(request, response);
        return;
    }
    request.setAttribute(FILTER_APPLIED, Boolean.TRUE);
    if (!securityContextRepository.containsContext(request)) {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication != null && !trustResolver.isAnonymous(authentication)) {
            // session strategy
            try {
                sessionAuthenticationStrategy.onAuthentication(authentication, request, response);
            } catch (SessionAuthenticationException e) {
                // The session strategy can reject the authentication
                logger.debug("SessionAuthenticationStrategy rejected the authentication object", e);
                SecurityContextHolder.clearContext();
                failureHandler.onAuthenticationFailure(request, response, e);
                return;
            }
            // Eagerly save the security context to make it available for any possible
            // re-entrant
            // requests which may occur before the current request completes.
            // SEC-1396.
            securityContextRepository.saveContext(SecurityContextHolder.getContext(), request, response);
        } else {
            // timeout
            if (request.getRequestedSessionId() != null && !request.isRequestedSessionIdValid()) {
                if (logger.isDebugEnabled()) {
                    logger.debug("Requested session ID " + request.getRequestedSessionId() + " is invalid.");
                }
                if (invalidSessionStrategy != null) {
                    invalidSessionStrategy.onInvalidSessionDetected(request, response);
                    return;
                }
            }
        }
    }
    chain.doFilter(request, response);
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) SessionAuthenticationException(org.springframework.security.web.authentication.session.SessionAuthenticationException) Authentication(org.springframework.security.core.Authentication) HttpServletResponse(javax.servlet.http.HttpServletResponse)

Example 3 with SessionAuthenticationException

use of org.springframework.security.web.authentication.session.SessionAuthenticationException in project molgenis by molgenis.

the class AuthenticationAuthoritiesUpdaterImpl method updateAuthentication.

@Override
public Authentication updateAuthentication(Authentication authentication, List<GrantedAuthority> updatedAuthorities) {
    Authentication newAuthentication;
    if (authentication instanceof TwoFactorAuthenticationToken) {
        TwoFactorAuthenticationToken twoFactorAuthenticationToken = (TwoFactorAuthenticationToken) authentication;
        newAuthentication = new TwoFactorAuthenticationToken(authentication.getPrincipal(), authentication.getCredentials(), updatedAuthorities, twoFactorAuthenticationToken.getVerificationCode(), twoFactorAuthenticationToken.getSecretKey());
    } else if (authentication instanceof SystemSecurityToken) {
        newAuthentication = authentication;
    } else if (authentication instanceof RestAuthenticationToken) {
        RestAuthenticationToken restAuthenticationToken = (RestAuthenticationToken) authentication;
        newAuthentication = new RestAuthenticationToken(authentication.getPrincipal(), authentication.getCredentials(), updatedAuthorities, restAuthenticationToken.getToken());
    } else if (authentication instanceof RecoveryAuthenticationToken) {
        RecoveryAuthenticationToken recoveryAuthenticationToken = (RecoveryAuthenticationToken) authentication;
        newAuthentication = new RecoveryAuthenticationToken(authentication.getPrincipal(), authentication.getCredentials(), updatedAuthorities, recoveryAuthenticationToken.getRecoveryCode());
    } else if (authentication instanceof UsernamePasswordAuthenticationToken) {
        newAuthentication = new UsernamePasswordAuthenticationToken(authentication.getPrincipal(), authentication.getCredentials(), updatedAuthorities);
    } else if (authentication instanceof RunAsUserToken) {
        RunAsUserToken runAsUserToken = (RunAsUserToken) authentication;
        newAuthentication = new RunAsUserTokenDecorator(runAsUserToken, updatedAuthorities);
    } else if (authentication instanceof AnonymousAuthenticationToken) {
        AnonymousAuthenticationToken anonymousAuthenticationToken = (AnonymousAuthenticationToken) authentication;
        newAuthentication = new AnonymousAuthenticationTokenDecorator(anonymousAuthenticationToken, updatedAuthorities);
    } else {
        throw new SessionAuthenticationException(format("Unknown authentication type '%s'", authentication.getClass().getSimpleName()));
    }
    return newAuthentication;
}
Also used : RecoveryAuthenticationToken(org.molgenis.security.twofactor.auth.RecoveryAuthenticationToken) SessionAuthenticationException(org.springframework.security.web.authentication.session.SessionAuthenticationException) RunAsUserToken(org.springframework.security.access.intercept.RunAsUserToken) Authentication(org.springframework.security.core.Authentication) UsernamePasswordAuthenticationToken(org.springframework.security.authentication.UsernamePasswordAuthenticationToken) SystemSecurityToken(org.molgenis.security.core.runas.SystemSecurityToken) AnonymousAuthenticationToken(org.springframework.security.authentication.AnonymousAuthenticationToken) RestAuthenticationToken(org.molgenis.security.token.RestAuthenticationToken) TwoFactorAuthenticationToken(org.molgenis.security.twofactor.auth.TwoFactorAuthenticationToken)

Example 4 with SessionAuthenticationException

use of org.springframework.security.web.authentication.session.SessionAuthenticationException in project BroadleafCommerce by BroadleafCommerce.

the class AdminSecurityFilter method doFilter.

@Override
public void doFilter(ServletRequest baseRequest, ServletResponse baseResponse, FilterChain chain) throws IOException, ServletException {
    try {
        super.doFilter(baseRequest, baseResponse, chain);
    } catch (ServletException e) {
        if (e.getCause() instanceof StaleStateServiceException) {
            LOG.debug("Stale state detected", e);
            ((HttpServletResponse) baseResponse).setStatus(HttpServletResponse.SC_CONFLICT);
            baseResponse.getWriter().write("Stale State Detected\n");
            baseResponse.getWriter().write(e.getMessage() + "\n");
        } else if (e.getCause() instanceof ServiceException) {
            HttpServletRequest baseHttpRequest = (HttpServletRequest) baseRequest;
            // if authentication is null and CSRF token is invalid, must be session time out
            if (SecurityContextHolder.getContext().getAuthentication() == null && failureHandler != null) {
                baseHttpRequest.setAttribute("sessionTimeout", true);
                failureHandler.onAuthenticationFailure((HttpServletRequest) baseRequest, (HttpServletResponse) baseResponse, new SessionAuthenticationException("Session Time Out"));
            } else {
                throw e;
            }
        } else {
            throw e;
        }
    }
}
Also used : ServletException(javax.servlet.ServletException) HttpServletRequest(javax.servlet.http.HttpServletRequest) SessionAuthenticationException(org.springframework.security.web.authentication.session.SessionAuthenticationException) StaleStateServiceException(org.broadleafcommerce.common.security.service.StaleStateServiceException) ServiceException(org.broadleafcommerce.common.exception.ServiceException) StaleStateServiceException(org.broadleafcommerce.common.security.service.StaleStateServiceException)

Example 5 with SessionAuthenticationException

use of org.springframework.security.web.authentication.session.SessionAuthenticationException in project spring-security by spring-projects.

the class SessionManagementFilter method doFilter.

private void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
    if (request.getAttribute(FILTER_APPLIED) != null) {
        chain.doFilter(request, response);
        return;
    }
    request.setAttribute(FILTER_APPLIED, Boolean.TRUE);
    if (!this.securityContextRepository.containsContext(request)) {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication != null && !this.trustResolver.isAnonymous(authentication)) {
            // session strategy
            try {
                this.sessionAuthenticationStrategy.onAuthentication(authentication, request, response);
            } catch (SessionAuthenticationException ex) {
                // The session strategy can reject the authentication
                this.logger.debug("SessionAuthenticationStrategy rejected the authentication object", ex);
                SecurityContextHolder.clearContext();
                this.failureHandler.onAuthenticationFailure(request, response, ex);
                return;
            }
            // Eagerly save the security context to make it available for any possible
            // re-entrant requests which may occur before the current request
            // completes. SEC-1396.
            this.securityContextRepository.saveContext(SecurityContextHolder.getContext(), request, response);
        } else {
            // timeout
            if (request.getRequestedSessionId() != null && !request.isRequestedSessionIdValid()) {
                if (this.logger.isDebugEnabled()) {
                    this.logger.debug(LogMessage.format("Request requested invalid session id %s", request.getRequestedSessionId()));
                }
                if (this.invalidSessionStrategy != null) {
                    this.invalidSessionStrategy.onInvalidSessionDetected(request, response);
                    return;
                }
            }
        }
    }
    chain.doFilter(request, response);
}
Also used : SessionAuthenticationException(org.springframework.security.web.authentication.session.SessionAuthenticationException) Authentication(org.springframework.security.core.Authentication)

Aggregations

SessionAuthenticationException (org.springframework.security.web.authentication.session.SessionAuthenticationException)5 Authentication (org.springframework.security.core.Authentication)3 HttpServletRequest (javax.servlet.http.HttpServletRequest)2 FilterChain (jakarta.servlet.FilterChain)1 HttpServletRequest (jakarta.servlet.http.HttpServletRequest)1 HttpServletResponse (jakarta.servlet.http.HttpServletResponse)1 ServletException (javax.servlet.ServletException)1 HttpServletResponse (javax.servlet.http.HttpServletResponse)1 ServiceException (org.broadleafcommerce.common.exception.ServiceException)1 StaleStateServiceException (org.broadleafcommerce.common.security.service.StaleStateServiceException)1 Test (org.junit.jupiter.api.Test)1 SystemSecurityToken (org.molgenis.security.core.runas.SystemSecurityToken)1 RestAuthenticationToken (org.molgenis.security.token.RestAuthenticationToken)1 RecoveryAuthenticationToken (org.molgenis.security.twofactor.auth.RecoveryAuthenticationToken)1 TwoFactorAuthenticationToken (org.molgenis.security.twofactor.auth.TwoFactorAuthenticationToken)1 MockFilterChain (org.springframework.mock.web.MockFilterChain)1 MockHttpServletRequest (org.springframework.mock.web.MockHttpServletRequest)1 MockHttpServletResponse (org.springframework.mock.web.MockHttpServletResponse)1 RunAsUserToken (org.springframework.security.access.intercept.RunAsUserToken)1 AnonymousAuthenticationToken (org.springframework.security.authentication.AnonymousAuthenticationToken)1