Example usage for org.springframework.security.core.context SecurityContextHolder clearContext

List of usage examples for org.springframework.security.core.context SecurityContextHolder clearContext

Introduction

In this page you can find the example usage for org.springframework.security.core.context SecurityContextHolder clearContext.

Prototype

public static void clearContext() 

Source Link

Document

Explicitly clears the context value from the current thread.

Usage

From source file:org.springframework.security.extensions.portlet.PortletSessionContextIntegrationInterceptor.java

private void afterCompletion(PortletRequest request, PortletResponse response, Object handler, Exception ex)
        throws Exception {

    PortletSession portletSession = null;

    // retrieve the attributes that remember if the session existed and the hashcode of the contextClass
    boolean portletSessionExistedAtStartOfRequest = ((Boolean) request.getAttribute(SESSION_EXISTED))
            .booleanValue();//from  www .  j  av a2  s .c  o  m
    int oldContextHashCode = ((Integer) request.getAttribute(CONTEXT_HASHCODE)).intValue();

    // try to retrieve an existing portlet session
    try {
        portletSession = request.getPortletSession(false);
    } catch (IllegalStateException ignored) {
    }

    // if there is now no session but there was one at the beginning then it must have been invalidated
    if ((portletSession == null) && portletSessionExistedAtStartOfRequest) {
        if (logger.isDebugEnabled())
            logger.debug("PortletSession is now null, but was not null at start of request; "
                    + "session was invalidated, so do not create a new session");
    }

    // create a new portlet session if we need to
    if ((portletSession == null) && !portletSessionExistedAtStartOfRequest) {

        // if we're not allowed to create a new session, then report that
        if (!allowSessionCreation) {
            if (logger.isDebugEnabled())
                logger.debug("The PortletSession is currently null, and the "
                        + "PortletSessionContextIntegrationInterceptor is prohibited from creating a PortletSession "
                        + "(because the allowSessionCreation property is false) - SecurityContext thus not "
                        + "stored for next request");
        }
        // if the contextClass was changed during the request, then go ahead and create a session
        else if (!contextObject.equals(SecurityContextHolder.getContext())) {
            if (logger.isDebugEnabled())
                logger.debug("PortletSession being created as SecurityContextHolder contents are non-default");
            try {
                portletSession = request.getPortletSession(true);
            } catch (IllegalStateException ignored) {
            }
        }
        // if nothing in the contextClass changed, then don't bother to create a session
        else {
            if (logger.isDebugEnabled())
                logger.debug(
                        "PortletSession is null, but SecurityContextHolder has not changed from default: ' "
                                + SecurityContextHolder.getContext()
                                + "'; not creating PortletSession or storing SecurityContextHolder contents");
        }
    }

    // if the session exists and the contextClass has changes, then store the contextClass back into the session
    if ((portletSession != null) && (SecurityContextHolder.getContext().hashCode() != oldContextHashCode)) {
        portletSession.setAttribute(SPRING_SECURITY_CONTEXT_KEY, SecurityContextHolder.getContext(),
                portletSessionScope());
        if (logger.isDebugEnabled())
            logger.debug(
                    "SecurityContext stored to PortletSession: '" + SecurityContextHolder.getContext() + "'");
    }

    // remove the contents of the holder
    SecurityContextHolder.clearContext();
    if (logger.isDebugEnabled())
        logger.debug("SecurityContextHolder set to new contextClass, as request processing completed");

}

From source file:org.springframework.security.oauth2.provider.authentication.OAuth2AuthenticationProcessingFilter.java

public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
        throws IOException, ServletException {

    final boolean debug = logger.isDebugEnabled();
    final HttpServletRequest request = (HttpServletRequest) req;
    final HttpServletResponse response = (HttpServletResponse) res;

    try {//from   w w w.jav  a  2  s.  c  om

        String tokenValue = parseToken(request);
        if (tokenValue == null) {
            if (debug) {
                logger.debug("No token in request, will continue chain.");
            }
        } else {
            PreAuthenticatedAuthenticationToken authentication = new PreAuthenticatedAuthenticationToken(
                    tokenValue, "");
            request.setAttribute(OAuth2AuthenticationDetails.ACCESS_TOKEN_VALUE, tokenValue);
            authentication.setDetails(authenticationDetailsSource.buildDetails(request));
            Authentication authResult = authenticationManager.authenticate(authentication);

            if (debug) {
                logger.debug("Authentication success: " + authResult);
            }

            SecurityContextHolder.getContext().setAuthentication(authResult);

        }
    } catch (OAuth2Exception failed) {
        SecurityContextHolder.clearContext();

        if (debug) {
            logger.debug("Authentication request failed: " + failed);
        }

        authenticationEntryPoint.commence(request, response,
                new InsufficientAuthenticationException(failed.getMessage(), failed));

        return;
    }

    chain.doFilter(request, response);
}

From source file:org.springframework.security.oauth2.provider.endpoint.TokenEndpointAuthenticationFilter.java

public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
        throws IOException, ServletException {

    final boolean debug = logger.isDebugEnabled();
    final HttpServletRequest request = (HttpServletRequest) req;
    final HttpServletResponse response = (HttpServletResponse) res;

    try {/*w w  w .  j a va  2  s .c  o  m*/
        Authentication credentials = extractCredentials(request);

        if (credentials != null) {

            if (debug) {
                logger.debug("Authentication credentials found for '" + credentials.getName() + "'");
            }

            Authentication authResult = authenticationManager.authenticate(credentials);

            if (debug) {
                logger.debug("Authentication success: " + authResult.getName());
            }

            Authentication clientAuth = SecurityContextHolder.getContext().getAuthentication();
            if (clientAuth == null) {
                throw new BadCredentialsException(
                        "No client authentication found. Remember to put a filter upstream of the TokenEndpointAuthenticationFilter.");
            }
            DefaultAuthorizationRequest authorizationRequest = new DefaultAuthorizationRequest(
                    getSingleValueMap(request), null, clientAuth.getName(), getScope(request));
            if (clientAuth.isAuthenticated()) {
                // Ensure the OAuth2Authentication is authenticated
                authorizationRequest.setApproved(true);
            }

            SecurityContextHolder.getContext()
                    .setAuthentication(new OAuth2Authentication(authorizationRequest, authResult));

            onSuccessfulAuthentication(request, response, authResult);

        }

    } catch (AuthenticationException failed) {
        SecurityContextHolder.clearContext();

        if (debug) {
            logger.debug("Authentication request for failed: " + failed);
        }

        onUnsuccessfulAuthentication(request, response, failed);

        authenticationEntryPoint.commence(request, response, failed);

        return;
    }

    chain.doFilter(request, response);
}

From source file:org.springframework.security.remoting.rmi.ContextPropagatingRemoteInvocation.java

/**
 * Invoked on the server-side.//from   ww w  . j a  va 2s . c  o m
 * <p>
 * The transmitted principal and credentials will be used to create an unauthenticated
 * {@code Authentication} instance for processing by the {@code AuthenticationManager}.
 *
 * @param targetObject the target object to apply the invocation to
 *
 * @return the invocation result
 *
 * @throws NoSuchMethodException if the method name could not be resolved
 * @throws IllegalAccessException if the method could not be accessed
 * @throws InvocationTargetException if the method invocation resulted in an exception
 */
public Object invoke(Object targetObject)
        throws NoSuchMethodException, IllegalAccessException, InvocationTargetException {

    if (principal != null) {
        Authentication request = createAuthenticationRequest(principal, credentials);
        request.setAuthenticated(false);
        SecurityContextHolder.getContext().setAuthentication(request);

        if (logger.isDebugEnabled()) {
            logger.debug("Set SecurityContextHolder to contain: " + request);
        }
    }

    try {
        return super.invoke(targetObject);
    } finally {
        SecurityContextHolder.clearContext();

        if (logger.isDebugEnabled()) {
            logger.debug("Cleared SecurityContextHolder.");
        }
    }
}

From source file:org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilterTests.java

@Before
public void setUp() throws Exception {
    successHandler = new SavedRequestAwareAuthenticationSuccessHandler();
    successHandler.setDefaultTargetUrl("/logged_in.jsp");
    failureHandler = new SimpleUrlAuthenticationFailureHandler();
    failureHandler.setDefaultFailureUrl("/failed.jsp");
    SecurityContextHolder.clearContext();
}

From source file:org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler.java

/**
 * Requires the request to be passed in.
 *
 * @param request from which to obtain a HTTP session (cannot be null)
 * @param response not used (can be <code>null</code>)
 * @param authentication not used (can be <code>null</code>)
 *///from  www .ja  va  2s  .c  om
public void logout(HttpServletRequest request, HttpServletResponse response, Authentication authentication) {
    Assert.notNull(request, "HttpServletRequest required");
    if (invalidateHttpSession) {
        HttpSession session = request.getSession(false);
        if (session != null) {
            logger.debug("Invalidating session: " + session.getId());
            session.invalidate();
        }
    }

    if (clearAuthentication) {
        SecurityContext context = SecurityContextHolder.getContext();
        context.setAuthentication(null);
    }

    SecurityContextHolder.clearContext();
}

From source file:org.springframework.security.web.authentication.www.BasicAuthenticationFilterTests.java

@Before
public void setUp() throws Exception {
    SecurityContextHolder.clearContext();
    UsernamePasswordAuthenticationToken rodRequest = new UsernamePasswordAuthenticationToken("rod", "koala");
    rodRequest.setDetails(new WebAuthenticationDetails(new MockHttpServletRequest()));
    Authentication rod = new UsernamePasswordAuthenticationToken("rod", "koala",
            AuthorityUtils.createAuthorityList("ROLE_1"));

    manager = mock(AuthenticationManager.class);
    when(manager.authenticate(rodRequest)).thenReturn(rod);
    when(manager.authenticate(not(eq(rodRequest)))).thenThrow(new BadCredentialsException(""));

    filter = new BasicAuthenticationFilter(manager, new BasicAuthenticationEntryPoint());
}

From source file:org.springframework.security.web.authentication.www.DigestAuthenticationFilterTests.java

@Before
public void setUp() {
    SecurityContextHolder.clearContext();

    // Create User Details Service
    UserDetailsService uds = new UserDetailsService() {

        public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
            return new User("rod,ok", "koala", AuthorityUtils.createAuthorityList("ROLE_ONE", "ROLE_TWO"));
        }/*from ww w.  j a  va  2s .  com*/
    };

    DigestAuthenticationEntryPoint ep = new DigestAuthenticationEntryPoint();
    ep.setRealmName(REALM);
    ep.setKey(KEY);

    filter = new DigestAuthenticationFilter();
    filter.setUserDetailsService(uds);
    filter.setAuthenticationEntryPoint(ep);

    request = new MockHttpServletRequest("GET", REQUEST_URI);
    request.setServletPath(REQUEST_URI);
}

From source file:org.springframework.security.web.FilterChainProxy.java

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    boolean clearContext = request.getAttribute(FILTER_APPLIED) == null;
    if (clearContext) {
        try {/*from  w ww.  j ava2s . c  o m*/
            request.setAttribute(FILTER_APPLIED, Boolean.TRUE);
            doFilterInternal(request, response, chain);
        } finally {
            SecurityContextHolder.clearContext();
            request.removeAttribute(FILTER_APPLIED);
        }
    } else {
        doFilterInternal(request, response, chain);
    }
}

From source file:org.thingsboard.server.service.security.auth.jwt.RefreshTokenProcessingFilter.java

@Override
protected void unsuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response,
        AuthenticationException failed) throws IOException, ServletException {
    SecurityContextHolder.clearContext();
    failureHandler.onAuthenticationFailure(request, response, failed);
}