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.unitedinternet.cosmo.acegisecurity.context.HttpRequestContextIntegrationFilter.java

/**
 * Generates a new security context, continues the filter chain,
 * then clears the context by generating another new one.
 *
 * @param request the servlet request/*  w w  w. j a v a  2  s .com*/
 * @param response the servlet response
 * @param chain the filter chain
 * @throws IOException if an I/O error occurs
 * @throws ServletException if any other error occurs
 */
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    if (request.getAttribute(FILTER_APPLIED) != null) {
        // ensure that filter is applied only once per request
        chain.doFilter(request, response);
        return;
    }

    request.setAttribute(FILTER_APPLIED, Boolean.TRUE);

    if (LOG.isDebugEnabled()) {
        LOG.debug("New SecurityContext instance associated with SecurityContextHolder");
    }
    SecurityContextHolder.setContext(generateNewContext());

    try {
        chain.doFilter(request, response);
    } catch (IOException ioe) {
        throw ioe;
    } catch (ServletException se) {
        throw se;
    } finally {
        // do clean up, even if there was an exception
        SecurityContextHolder.clearContext();
        if (LOG.isDebugEnabled()) {
            LOG.debug("SecurityContextHolder refreshed, as request processing completed");
        }
    }
}

From source file:org.yes.cart.bulkjob.bulkimport.LocalFileShareImportListenerImpl.java

private void runRootScan(final Logger log, final File root) {

    final File[] shopDirs = root.listFiles();

    if (shopDirs != null) {

        SecurityContextHolder.getContext().setAuthentication(global);

        final String importDirPath = importDirectorService.getImportDirectory();
        log.info("Detected import directory root {}", importDirPath);

        final List<Map<String, String>> importGroupsMap = importDirectorService.getImportGroups("en");
        final Set<String> importGroupNames = new HashSet<String>();
        for (final Map<String, String> group : importGroupsMap) {
            importGroupNames.add(group.get("name"));
        }/*from w w  w  .j a  v  a2 s  .  co m*/
        log.info("Detected import groups: {}", StringUtils.join(importGroupNames, ","));

        try {

            for (final File shopDir : shopDirs) {

                runShopRootScan(log, shopDir, importDirPath, importGroupNames);

            }

        } catch (Exception exp) {

            log.error("Encountered fatal error: " + exp.getMessage() + "... stopping scheduled task", exp);

        } finally {

            SecurityContextHolder.clearContext();

        }

    }
}

From source file:org.yes.cart.domain.interceptor.AdminInterceptor.java

private Runnable createEvictCacheRunnable(final String op, final String entityName, final Long pk) {

    final AsyncContext jobContext = ThreadLocalAsyncContextUtils.getContext();
    final Authentication auth = SecurityContextHolder.getContext() != null
            ? SecurityContextHolder.getContext().getAuthentication()
            : null;/*from   www .j a va  2s  .c  o  m*/
    final String username = auth != null && auth.isAuthenticated() ? auth.getName() : null;

    return new Runnable() {

        @Override
        public void run() {

            try {

                final AsyncContext threadContext;
                if (StringUtils.isBlank(username)) {
                    threadContext = jobContext;
                } else {
                    SecurityContextHolder.getContext().setAuthentication(
                            new RunAsUserAuthentication(username, "", Collections.EMPTY_LIST));
                    final Map<String, Object> params = new HashMap<String, Object>();
                    params.put(AsyncContext.TIMEOUT_KEY,
                            AttributeNamesKeys.System.SYSTEM_BACKDOOR_CACHE_TIMEOUT_MS);
                    threadContext = asyncContextFactory.getInstance(params);
                }

                if (threadContext == null) {
                    LOG.debug("Cannot invalidate cache for entity [" + entityName + "] pk value =  [" + pk
                            + "] - no async context ");
                    return;
                }

                final List<Node> cluster = nodeService.getSfNodes();
                final List<String> targets = new ArrayList<String>();
                for (final Node node : cluster) {
                    targets.add(node.getId());
                }

                final HashMap<String, Object> payload = new HashMap<String, Object>();
                payload.put("entityOperation", op);
                payload.put("entityName", entityName);
                payload.put("pkValue", pk);

                final RspMessage message = new ContextRspMessageImpl(nodeService.getCurrentNodeId(), targets,
                        "CacheDirector.onCacheableChange", payload, threadContext);

                nodeService.broadcast(message);

            } catch (Exception exp) {
                LOG.error("Unable to perform cache eviction: " + exp.getMessage(), exp);
            } finally {
                SecurityContextHolder.clearContext();
            }

        }
    };

}

From source file:ro.nextreports.server.web.integration.IntegrationAuthenticationFilter.java

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

    if (logger.isDebugEnabled()) {
        logger.debug("Authentication request failed: " + failed.toString());
        logger.debug("Updated SecurityContextHolder to contain null Authentication");
        //            logger.debug("Delegating to authentication failure handler" + failureHandler);
    }/*from  w w w .j  a  v  a  2s .c  o  m*/

    //        failureHandler.onAuthenticationFailure(request, response, failed);
}