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:fr.esiea.esieaddress.service.login.implementation.AuthenticationService.java

@Override
public void logout() {

    SecurityContext context = SecurityContextHolder.getContext();

    LOGGER.info(//from  w ww .  j  a  va2  s  .  c  o m
            "[Service] Querying to logout User : \"" + context.getAuthentication().getName().toString() + "\"");

    if (context.getAuthentication() != null)
        SecurityContextHolder.clearContext();
}

From source file:org.openlmis.fulfillment.security.ResourceServerSecurityConfiguration.java

@Override
public void configure(HttpSecurity http) throws Exception {
    http.addFilterAfter(new OncePerRequestFilter() {
        @Override//from  w w w .ja  v  a 2  s  .  co  m
        protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
                FilterChain filterChain) throws ServletException, IOException {
            // We don't want to allow access to a resource with no token so clear
            // the security context in case it is actually an OAuth2Authentication
            if (tokenExtractor.extract(request) == null) {
                SecurityContextHolder.clearContext();
            }
            filterChain.doFilter(request, response);
        }
    }, AbstractPreAuthenticatedProcessingFilter.class);
    http.csrf().disable();

    http.authorizeRequests()
            .antMatchers("/fulfillment", "/webjars/**", "/fulfillment/webjars/**", "/fulfillment/docs/**")
            .permitAll().antMatchers("/**").fullyAuthenticated();
}

From source file:com.devicehive.auth.rest.HttpAuthenticationFilter.java

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    HttpServletRequest httpRequest = (HttpServletRequest) request;
    HttpServletResponse httpResponse = (HttpServletResponse) response;

    Optional<String> authHeader = Optional.ofNullable(httpRequest.getHeader(HttpHeaders.AUTHORIZATION));

    String resourcePath = new UrlPathHelper().getPathWithinApplication(httpRequest);
    logger.debug("Security intercepted request to {}", resourcePath);

    try {/*from w  w w.j  a va2 s  . c o m*/
        if (authHeader.isPresent()) {
            String header = authHeader.get();
            if (header.startsWith(Constants.BASIC_AUTH_SCHEME)) {
                processBasicAuth(header);
            } else if (header.startsWith(Constants.TOKEN_SCHEME)) {
                processJwtAuth(authHeader.get().substring(6).trim());
            }
        } else {
            processAnonymousAuth();
        }

        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication != null && authentication instanceof AbstractAuthenticationToken) {
            MDC.put("usrinf", authentication.getName());
            HiveAuthentication.HiveAuthDetails details = createUserDetails(httpRequest);
            ((AbstractAuthenticationToken) authentication).setDetails(details);
        }

        chain.doFilter(request, response);
    } catch (InternalAuthenticationServiceException e) {
        SecurityContextHolder.clearContext();
        logger.error("Internal authentication service exception", e);
        httpResponse.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    } catch (AuthenticationException e) {
        SecurityContextHolder.clearContext();
        httpResponse.sendError(HttpServletResponse.SC_UNAUTHORIZED, e.getMessage());
    } finally {
        MDC.remove("usrinf");
    }
}

From source file:org.openinfinity.sso.security.spring.InjectableSecurityContextFilterBean.java

private void eraseSecurityContext(String sessionId) {
    SecurityContext context = SecurityContextHolder.getContext();
    context.setAuthentication(null);/*from  w  ww . j  a  v  a2  s  .  c o  m*/
    SecurityContextHolder.clearContext();
    LOGGER.debug("SecurityContextHolder erased.");
}

From source file:business.LargerExcerptListTests.java

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

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

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

    ExcerptListRepresentation excerptList = requestController.getExcerptList(requester, processInstanceId);
    for (ExcerptEntryRepresentation entry : excerptList.getEntries()) {
        entry.setSelected(true);/*ww  w  . ja va2 s.  co  m*/
    }
    excerptList = selectionController.updateExcerptListSelection(requester, processInstanceId, excerptList);
    representation.setExcerptList(excerptList);
    representation = selectionController.submitExcerptSelection(requester, processInstanceId, representation);

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

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

    SecurityContextHolder.clearContext();
}

From source file:org.openwms.client.security.AuthenticationTokenProcessingFilter.java

/**
 * {@inheritDoc}/* w  w w. ja  v  a2s  . com*/
 * 
 * @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)) {
        throw new RuntimeException("Expecting a http servlet request");
    }

    HttpServletRequest httpRequest = (HttpServletRequest) request;
    String authToken = httpRequest.getHeader(AUTH_TOKEN);

    String userName = TokenUtils.getUserNameFromToken(authToken);
    if (userName != null) {

        // The returned UserDetails object has credentials encoded, we rely
        // on two AuthenticationProviders here to
        // come around this issue, one with PasswordEncoder and one without
        UserDetails userDetails = this.userService.loadUserByUsername(userName);
        if (TokenUtils.validateToken(authToken, userDetails)) {
            UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(
                    userDetails.getUsername(), userDetails.getPassword());
            authentication.setDetails(
                    new WebAuthenticationDetailsSource().buildDetails((HttpServletRequest) request));
            SecurityContextHolder.getContext()
                    .setAuthentication(this.authenticationManager.authenticate(authentication));
        }
    }
    chain.doFilter(request, response);
    SecurityContextHolder.clearContext();
}

From source file:se.inera.certificate.web.controller.PageController.java

protected void invalidateSessionAndClearContext(HttpServletRequest request) {
    request.getSession().invalidate();/*from   w  w  w. ja  v  a 2 s.  c  om*/
    SecurityContextHolder.getContext().setAuthentication(null);
    SecurityContextHolder.clearContext();
}

From source file:com.vaadinspring.presenter.UserPresenterImpl.java

public void logout() {
    SecurityContextHolder.clearContext();
}

From source file:fr.mycellar.interfaces.web.services.security.SecurityWebService.java

@POST
@Produces(MediaType.APPLICATION_JSON)/*  ww  w.  j a  v  a 2 s . c  o  m*/
@Consumes(MediaType.APPLICATION_JSON)
@Path("changePassword")
public UserDto changePassword(ChangePasswordDto changePasswordDto, @Context HttpServletResponse response)
        throws BusinessException {
    User currentUser = currentUserService.getCurrentUser();
    User user = userServiceFacade.authenticateUser(currentUser.getEmail(), changePasswordDto.getOldPassword());
    userServiceFacade.saveUserPassword(user, changePasswordDto.getPassword());

    SecurityContextHolder.clearContext();

    UserDto userDto = new UserDto();
    userDto.setEmail(user.getEmail());
    userDto.setPassword(changePasswordDto.getPassword());
    return login(userDto, response);
}

From source file:eu.trentorise.smartcampus.resourceprovider.filter.ResourceFilter.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 (HttpMethod.OPTIONS.equals(HttpMethod.valueOf(request.getMethod()))) {
            chain.doFilter(request, response);
            //            throw new OAuth2Exception("options");
        } else if (tokenValue == null) {
            if (debug) {
                logger.debug("No token in request, will continue chain.");
            }
            throw new OAuth2Exception("empty token");
        } else {
            ResourceCallAuthenticationToken authentication = new ResourceCallAuthenticationToken(tokenValue,
                    "");
            request.setAttribute(OAuth2AuthenticationDetails.ACCESS_TOKEN_VALUE, tokenValue);
            authentication.setDetails(authenticationDetailsSource.buildDetails(request));
            authentication.setRequestPath(getFullURL(request));
            authentication.setHttpMethod(HttpMethod.valueOf(request.getMethod()));
            Authentication authResult = authenticationManager.authenticate(authentication);

            SecurityContextHolder.getContext().setAuthentication(authResult);

            chain.doFilter(request, response);

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

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

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

        return;
    }

}