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:com.github.peholmst.springsecuritydemo.ui.SpringSecurityDemoApp.java

@Override
@PreDestroy//from  ww  w .ja  va 2 s  .  c  o m
// In case the application is destroyed by the container
public void close() {
    if (logger.isDebugEnabled()) {
        logger.debug("Closing application [" + this + "]");
    }
    // Clear the authentication property to log the user out
    setUser(null);
    // Also clear the security context
    SecurityContextHolder.clearContext();
    getContext().removeTransactionListener(this);
    super.close();
}

From source file:fr.treeptik.cloudunit.infinity.SimpleLongRunnerTestMR.java

@After
public void teardown() {
    logger.info("teardown");
    SecurityContextHolder.clearContext();
    session.invalidate();
}

From source file:business.LargerExcerptListTests.java

@Test(groups = "request", dependsOnMethods = "selectExcerpts")
public void approveSelection() {
    UserAuthenticationToken requester = getRequester();
    UserAuthenticationToken palga = getPalga();
    SecurityContext securityContext = SecurityContextHolder.getContext();
    securityContext.setAuthentication(requester);

    ((MockMailSender) mailSender).clear();

    RequestRepresentation representation = requestController.getRequestById(requester, processInstanceId);

    log.info("Status: " + representation.getStatus());

    securityContext.setAuthentication(palga);

    representation.setSelectionApproved(true);
    representation = selectionController.setExcerptSelectionApproval(palga, processInstanceId, representation);

    assertEquals(RequestStatus.LAB_REQUEST, representation.getStatus());

    assertEquals(2, labRequestService.count());
    List<LabRequest> labRequests = labRequestService.findAllByProcessInstanceId(processInstanceId);
    assertEquals(2, labRequests.size());

    int pathologyCount = 0;
    for (LabRequest labRequest : labRequests) {
        LabRequestRepresentation labRequestRepresentation = new LabRequestRepresentation(labRequest);
        labRequestService.transferLabRequestData(labRequestRepresentation, false);
        labRequestService.transferExcerptListData(labRequestRepresentation);
        labRequestService.transferLabRequestDetails(labRequestRepresentation, false);
        pathologyCount += labRequestRepresentation.getPathologyCount();
    }//from  ww  w  .ja v a  2 s  .  com
    long pathologyCount2 = pathologyItemRepository.count();
    assertEquals(6, pathologyCount);
    assertEquals(6, pathologyCount2);

    // fails because contact data for labs is not set
    //assertEquals(2, ((MockMailSender)mailSender).getMessages().size());

    SecurityContextHolder.clearContext();
}

From source file:org.juiser.spring.security.web.authentication.HeaderAuthenticationFilter.java

/**
 * Clears the {@link SecurityContextHolder} and returns {@code true}.
 *///ww  w.jav  a  2 s .co  m
protected boolean unsuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response,
        FilterChain chain, AuthenticationException failed) throws IOException, ServletException {

    SecurityContextHolder.clearContext();

    if (log.isDebugEnabled()) {
        log.debug("Authentication request failed: " + failed.toString(), failed);
        log.debug("Updated SecurityContextHolder to contain null Authentication");
        log.debug("Continuing filter chain with null Authentication");
    }

    return true;
}

From source file:org.cloudfoundry.identity.uaa.authentication.manager.LoginAuthenticationFilter.java

@Override
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  ww  w.j a va2s.c  om
        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 requestingPrincipal = SecurityContextHolder.getContext().getAuthentication();
            if (requestingPrincipal == null) {
                throw new BadCredentialsException(
                        "No client authentication found. Remember to put a filter upstream of the LoginAuthenticationFilter.");
            }

            String clientId = request.getParameter("client_id");
            if (null == clientId) {
                logger.error("No client_id in the request");
                throw new BadCredentialsException("No client_id in the request");
            }

            // Check that the client exists
            ClientDetails authenticatingClient = clientDetailsService.loadClientByClientId(clientId);
            if (authenticatingClient == null) {
                throw new BadCredentialsException("No client " + clientId + " found");
            }

            DefaultAuthorizationRequest authorizationRequest = new DefaultAuthorizationRequest(
                    getSingleValueMap(request), null, authenticatingClient.getClientId(), getScope(request));
            if (requestingPrincipal.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:bjerne.gallery.service.impl.GalleryAuthorizationServiceSSImpl.java

@Override
public void logoutAdminUser() {
    SecurityContextHolder.clearContext();
}

From source file:ch.silviowangler.dox.AbstractIntegrationTest.java

@After
public void clearSecurityContext() {
    SecurityContextHolder.clearContext();
}

From source file:com.example.AzureADAuthenticationFilter.java

@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
        FilterChain filterChain) throws ServletException, IOException {
    try {//from w  w  w. j  av  a 2  s  . c om

        String currentUri = AuthHelper.getCurrentUri(request);

        // Check if current session contains user authentication info.
        if (!AuthHelper.isAuthenticated(request)) {

            if (log.isTraceEnabled()) {
                log.trace("AuthHelper.isAuthenticated = false");
            }

            if (AuthHelper.containsAuthenticationData(request)) {
                // The request contains authentication data, which means this request is returned from AzureAD login page
                // after authentication process is completed.  The result should have been processed by AzureADResponseFilter.
            } else {
                if (log.isTraceEnabled()) {
                    log.trace("AuthHelper.containsAuthenticationData = false");
                }

                // when not authenticated and request does not contains authentication data (not come from Azure AD login process),
                // redirect to Azure login page.

                // get csrf token
                CsrfToken token = (CsrfToken) request.getAttribute("_csrf");
                if (log.isDebugEnabled()) {
                    log.debug("Current csrf token before going to AzureAD login {} {} = {}",
                            token.getHeaderName(), token.getParameterName(), token.getToken());
                }

                // add the csrf token to login request and go login...
                response.setStatus(302);
                String redirectTo = getRedirectUrl(currentUri) + "&state=" + token.getToken();

                if (log.isDebugEnabled()) {
                    log.debug("302 redirect to " + redirectTo);
                }
                response.sendRedirect(redirectTo);
                return;
            }
        } else {
            if (log.isTraceEnabled()) {
                log.trace("AuthHelper.isAuthenticated = true");
            }

            // if authenticated, how to check for valid session?
            AuthenticationResult result = AuthHelper.getAuthSessionObject(request);

            if (request.getParameter("refresh") != null) {
                result = getAccessTokenFromRefreshToken(result.getRefreshToken(), currentUri);
            } else {
                if (request.getParameter("cc") != null) {
                    result = getAccessTokenFromClientCredentials();
                } else {
                    if (result.getExpiresOnDate().before(new Date())) {
                        result = getAccessTokenFromRefreshToken(result.getRefreshToken(), currentUri);
                    }
                }
            }

            AuthHelper.setAuthSessionObject(request, result);

            // Handle logout
            if (logout.equals(request.getRequestURI())) {
                if (log.isTraceEnabled()) {
                    log.trace("Logout...");
                }

                // Clear spring security context so spring thinks this user is gone.
                request.logout();
                SecurityContextHolder.clearContext();

                // Clear Azure principal
                AuthHelper.remoteAuthSessionObject(request);

                // Go to AzureAD and logout.
                response.setStatus(302);
                String logoutPage = "https://login.windows.net/" + tenant + "/oauth2/logout";
                if (log.isDebugEnabled()) {
                    log.debug("302 redirect to " + logoutPage);
                }

                response.sendRedirect(logoutPage);
                return;
            } else {
                if (log.isTraceEnabled()) {
                    log.trace("URI: " + request.getRequestURI() + " does not match " + logout
                            + ".  It is not a logout request");
                }
            }
        }
    } catch (Throwable exc) {
        response.setStatus(500);
        request.setAttribute("error", exc.getMessage());
        response.sendRedirect(((HttpServletRequest) request).getContextPath() + error);
    }

    filterChain.doFilter(request, response);
}

From source file:de.theit.jenkins.crowd.CrowdServletFilter.java

/**
 * {@inheritDoc}/*from   ww  w  . ja v a  2 s. co m*/
 * 
 * @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest,
 *      javax.servlet.ServletResponse, javax.servlet.FilterChain)
 */
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    if (request instanceof HttpServletRequest && response instanceof HttpServletResponse) {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse res = (HttpServletResponse) response;

        // check if we have a token
        // if it is not present, we are not / no longer authenticated
        boolean isValidated = false;
        try {
            isValidated = this.configuration.crowdHttpAuthenticator.isAuthenticated(req, res);
        } catch (OperationFailedException ex) {
            LOG.log(Level.SEVERE, operationFailed(), ex);
        }

        if (!isValidated) {
            if (LOG.isLoggable(Level.FINE)) {
                LOG.fine("User is not logged in (anymore) via Crowd => logout user");
            }
            SecurityContext sc = SecurityContextHolder.getContext();
            sc.setAuthentication(null);
            // close the SSO session
            if (null != this.rememberMe) {
                this.rememberMe.logout(req, res);
            }

            // invalidate the current session
            // (see SecurityRealm#doLogout())
            HttpSession session = req.getSession(false);
            if (session != null) {
                session.invalidate();
            }
            SecurityContextHolder.clearContext();

            // reset remember-me cookie
            Cookie cookie = new Cookie(SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY, "");
            cookie.setPath(req.getContextPath().length() > 0 ? req.getContextPath() : "/");
            res.addCookie(cookie);
        } else {
            SecurityContext sc = SecurityContextHolder.getContext();

            if (!(sc.getAuthentication() instanceof CrowdAuthenticationToken)) {
                // user logged in via Crowd, but no Crowd-specific
                // authentication token available
                // => try to auto-login the user
                if (null != this.rememberMe) {
                    if (LOG.isLoggable(Level.FINE)) {
                        LOG.fine(
                                "User is logged in via Crowd, but no authentication token available; trying auto-login...");
                    }
                    Authentication auth = this.rememberMe.autoLogin(req, res);
                    if (null != auth) {
                        if (LOG.isLoggable(Level.FINE)) {
                            LOG.fine("User sucessfully logged in");
                        }
                        sc.setAuthentication(auth);
                    }
                }
            }
        }
    }

    this.defaultFilter.doFilter(request, response, chain);
}