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:edu.zipcloud.cloudstreetmarket.core.authentication.CustomOAuth2RequestFilter.java

@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
        throws ServletException, IOException {

    final boolean debug = logger.isDebugEnabled();

    String userIdentifier = request.getHeader(SPI_HEADER);

    if (userIdentifier == null) {
        chain.doFilter(request, response);
        return;//ww  w. j a v a  2 s.c o m
    }

    try {
        SocialUser socialUser = getRegisteredUser(userIdentifier);
        if (socialUser == null) {
            response.setHeader(MUST_REGISTER_HEADER, request.getHeader(SPI_HEADER));
            chain.doFilter(request, response);
            return;
        }

        if (authenticationIsRequired(socialUser.getUserId())) {
            User registeredUser = communityService.findOne(socialUser.getUserId());

            UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(
                    registeredUser, registeredUser.getPassword(), registeredUser.getAuthorities());
            authRequest.setDetails(authenticationDetailsSource.buildDetails(request));
            Authentication authResult = authenticationManager.authenticate(authRequest);

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

            SecurityContextHolder.getContext().setAuthentication(authResult);
            rememberMeServices.loginSuccess(request, response, authResult);
            onSuccessfulAuthentication(request, response, authResult);
        }

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

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

        rememberMeServices.loginFail(request, response);

        onUnsuccessfulAuthentication(request, response, failed);

        if (ignoreFailure) {
            chain.doFilter(request, response);
        }
        return;
    }

    chain.doFilter(request, response);
}

From source file:de.forsthaus.UserWorkspace.java

@Override
public void destroy() {
    this.grantedAuthoritySet = null;
    SecurityContextHolder.clearContext();

    if (logger.isDebugEnabled()) {
        logger.debug("destroy Workspace [" + this + "]");
    }/*from w ww .  j a  va  2  s.  co  m*/
}

From source file:business.UploadTests.java

@Test(groups = "upload", dependsOnMethods = "createRequest")
public void uploadFileNoMimetype() throws IOException {
    UserAuthenticationToken requester = getRequester();
    SecurityContext securityContext = SecurityContextHolder.getContext();
    securityContext.setAuthentication(requester);

    RequestRepresentation representation = requestController.getRequestById(requester, processInstanceId);
    log.info("Status: " + representation.getStatus());
    int attachmentCount = representation.getAttachments().size();

    ClassLoader classLoader = getClass().getClassLoader();
    URL resource = classLoader.getResource("test/Utrecht_Oude_Gracht_Hamburgerbrug_(LOC).jpg");
    InputStream input = resource.openStream();
    MultipartFile file = new MockMultipartFile(resource.getFile(), input);
    //MultipartFile file = new MockMultipartFile(resource.getFile(), resource.getFile().toString(), "undefined", input);

    Integer flowTotalChunks = 1;//  w w w  .  ja  v a 2s .  co  m
    Integer flowChunkNumber = 1;
    String flowIdentifier = "flow";

    representation = requestController.uploadRequestAttachment(requester, processInstanceId, resource.getFile(),
            flowTotalChunks, flowChunkNumber, flowIdentifier, file);

    assertEquals(attachmentCount + 1, representation.getAttachments().size());
    printFiles(representation.getAttachments());

    SecurityContextHolder.clearContext();
}

From source file:org.saiku.web.service.SessionService.java

public void logout(HttpServletRequest req) {
    if (SecurityContextHolder.getContext() != null
            && SecurityContextHolder.getContext().getAuthentication() != null) {
        Object p = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        if (sessionHolder.containsKey(p)) {
            sessionHolder.remove(p);/*from www .  j  ava 2  s.co  m*/
        }
    }
    SecurityContextHolder.getContext().setAuthentication(null);
    SecurityContextHolder.clearContext();
    HttpSession session = req.getSession(false);
    if (session != null) {
        session.invalidate();
    }
}

From source file:org.vaadin.spring.security.shared.DefaultVaadinSharedSecurity.java

/**
 * Called by {@link #login(Authentication, boolean)} upon unsuccessful authentication. This implementation will
 * clear the security context holder and inform the {@code RememberMeServices} of the failed login.
 * //from   w ww  . j  a v a 2s  . c  o m
 * @param request the current request.
 * @param response the current response.
 */
protected void unsuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response) {
    LOGGER.debug("Authentication failed");
    SecurityContextHolder.clearContext();
    getRememberMeServices().loginFail(request, response);
}

From source file:com.skywell.social.custom.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. ja va  2  s .  c  o  m*/

        Authentication authentication = tokenExtractor.extract(request);

        if (authentication == null) {
            if (stateless && isAuthenticated()) {
                if (debug) {
                    logger.debug("Clearing security context.");
                }
                SecurityContextHolder.clearContext();
            }
            if (debug) {
                logger.debug("No token in request, will continue chain.");
            }
        } else {
            request.setAttribute(OAuth2AuthenticationDetails.ACCESS_TOKEN_VALUE, authentication.getPrincipal());
            if (authentication instanceof AbstractAuthenticationToken) {
                AbstractAuthenticationToken needsDetails = (AbstractAuthenticationToken) authentication;
                needsDetails.setDetails(authenticationDetailsSource.buildDetails(request));
            }
            User user = userRepository.findByAccessToken(authentication.getName());
            UsernamePasswordAuthenticationToken authenticate = new UsernamePasswordAuthenticationToken(
                    user.getProviderUserId(), user.getAccessToken(), user.getAuthorities());
            authenticate.setDetails(authentication.getDetails());

            SecurityContextHolder.getContext().setAuthentication(authenticate);

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

        if (debug) {
            logger.debug("Authentication request failed: " + failed);
        }
        eventPublisher.publishAuthenticationFailure(new BadCredentialsException(failed.getMessage(), failed),
                new PreAuthenticatedAuthenticationToken("access-token", "N/A"));

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

        return;
    }

    chain.doFilter(request, response);
}

From source file:org.apache.cxf.fediz.service.idp.kerberos.KerberosAuthenticationProcessingFilter.java

public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
        throws IOException, ServletException {
    HttpServletRequest request = (HttpServletRequest) req;
    HttpServletResponse response = (HttpServletResponse) res;
    if (skipIfAlreadyAuthenticated) {
        Authentication existingAuth = SecurityContextHolder.getContext().getAuthentication();
        if (existingAuth != null && existingAuth.isAuthenticated()
                && !(existingAuth instanceof AnonymousAuthenticationToken)) {
            chain.doFilter(request, response);
            return;
        }//from  w  w  w.j ava2 s. c om
    }
    String header = request.getHeader("Authorization");
    if ((header != null) && header.startsWith("Negotiate ")) {
        if (logger.isDebugEnabled()) {
            logger.debug("Received Negotiate Header for request " + request.getRequestURL() + ": " + header);
        }
        byte[] base64Token = header.substring(10).getBytes("UTF-8");
        byte[] kerberosTicket = Base64.decode(base64Token);
        KerberosServiceRequestToken authenticationRequest = new KerberosServiceRequestToken(kerberosTicket);
        authenticationRequest.setDetails(authenticationDetailsSource.buildDetails(request));
        Authentication authentication;
        try {
            authentication = authenticationManager.authenticate(authenticationRequest);
        } catch (AuthenticationException e) {
            //That shouldn't happen, as it is most likely a wrong
            //configuration on the server side
            logger.warn("Negotiate Header was invalid: " + header, e);
            SecurityContextHolder.clearContext();
            if (failureHandler != null) {
                failureHandler.onAuthenticationFailure(request, response, e);
            } else {
                response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                response.flushBuffer();
            }
            return;
        }
        sessionStrategy.onAuthentication(authentication, request, response);
        SecurityContextHolder.getContext().setAuthentication(authentication);
        if (successHandler != null) {
            successHandler.onAuthenticationSuccess(request, response, authentication);
        }
    }
    chain.doFilter(request, response);
}

From source file:business.SmallExcerptListTests.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());

    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   w w w.  j  a  v  a  2  s  .com*/
    assertEquals(3, pathologyCount);

    assertEquals(3, ((MockMailSender) mailSender).getMessages().size());

    SecurityContextHolder.clearContext();
}

From source file:com.sibvisions.rad.server.security.spring.SpringSecurityManager.java

/**
 * {@inheritDoc}//from  w  w  w  . j  a v a  2s . c  om
 */
public void logout(ISession pSession) {
    if (Boolean.valueOf((String) pSession.getProperty("userlogout")).booleanValue()
            && pSession.getProperty(LOGOUT_PROCESS_URL) == null) {
        SecurityContextHolder.getContext().setAuthentication(null);
        SecurityContextHolder.clearContext();
    }
}

From source file:cz.zcu.kiv.eegdatabase.wui.app.session.EEGDataBaseSession.java

@Override
public boolean authenticate(String username, String password) {

    if (password.equalsIgnoreCase(SOCIAL_PASSWD)) {
        this.setLoggedUser(facade.getPerson(username));
        this.createShoppingCart();
        this.createExperimentLicenseMap();
        reloadPurchasedItemCache();/*from   ww  w. j av  a 2  s  . c  o  m*/
        return true;
    }

    boolean authenticated = false;
    try {
        Authentication authentication = authenticationManager
                .authenticate(new UsernamePasswordAuthenticationToken(username, password));
        SecurityContextHolder.getContext().setAuthentication(authentication);
        authenticated = authentication.isAuthenticated();
        this.setLoggedUser(facade.getPerson(username));
        reloadPurchasedItemCache();
        this.createShoppingCart();
        this.createExperimentLicenseMap();

    } catch (AuthenticationException e) {
        error((String.format("User '%s' failed to login. Reason: %s", username, e.getMessage())));
        authenticated = false;
    }

    if (getLoggedUser() != null && getLoggedUser().isLock()) {
        this.setLoggedUser(null);
        SecurityContextHolder.clearContext();
        this.shoppingCart = null;
        error(ResourceUtils.getString("text.user.lock.login", username));
        return false;
    }

    return authenticated;
}