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.akaza.openclinica.control.MainMenuServlet.java

private boolean processForceRenewAuth() throws IOException {
    logger.info("forceRenewAuth is true");
    boolean isRenewAuth = false;
    String renewAuth = (String) request.getParameter("forceRenewAuth");
    if (StringUtils.isNotEmpty(renewAuth)) {
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        if (auth != null) {
            auth.setAuthenticated(false);
            SecurityContextHolder.clearContext();
        }/*from   ww w .jav a2 s  .c  o m*/
        return true;
    }
    return isRenewAuth;
}

From source file:org.apache.ambari.server.security.authorization.jwt.JwtAuthenticationFilter.java

@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
        throws IOException, ServletException {

    if (jwtProperties == null) {
        //disable filter if not configured
        filterChain.doFilter(servletRequest, servletResponse);
        return;/*w w  w.j  a  v  a  2 s.  c o  m*/
    }

    HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
    HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse;

    String serializedJWT = getJWTFromCookie(httpServletRequest);
    if (serializedJWT != null && isAuthenticationRequired(serializedJWT)) {
        SignedJWT jwtToken;
        try {
            jwtToken = SignedJWT.parse(serializedJWT);

            boolean valid = validateToken(jwtToken);

            if (valid) {
                String userName = jwtToken.getJWTClaimsSet().getSubject();
                User user = users.getUser(userName, UserType.JWT);
                if (user == null) {

                    //TODO this is temporary check for conflicts, until /users API will change to use user_id instead of name as PK
                    User existingUser = users.getAnyUser(userName);
                    if (existingUser != null && existingUser.getUserType() != UserType.JWT) {

                        LOG.error("Access for JWT user [{}] restricted. Detected conflict with local user ",
                                userName);

                        // directly send HTTP status 500 to avoid redirect loop, as jwt token is already confirmed to be valid
                        httpServletResponse.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                                "Cannot create JWT user: conflict detected");

                        //interrupt filter chain
                        return;
                    }

                    // create user in local database on first login, usually we cannot fetch all users
                    // from external authentication provider (as we do during ldap-sync process)
                    users.createUser(userName, null, UserType.JWT, true, false);
                    user = users.getUser(userName, UserType.JWT);
                }

                Collection<AmbariGrantedAuthority> userAuthorities = users
                        .getUserAuthorities(user.getUserName(), user.getUserType());

                JwtAuthentication authentication = new JwtAuthentication(serializedJWT, user, userAuthorities);
                authentication.setAuthenticated(true);

                SecurityContextHolder.getContext().setAuthentication(authentication);

            } else {
                //clear security context if authentication was required, but failed
                SecurityContextHolder.clearContext();

                LOG.warn("JWT authentication failed");
                if (ignoreFailure) {
                    filterChain.doFilter(servletRequest, servletResponse);
                } else {
                    //used to indicate authentication failure, not used here as we have more than one filter
                    entryPoint.commence(httpServletRequest, httpServletResponse,
                            new BadCredentialsException("Invalid JWT " + "token"));
                }
            }

        } catch (ParseException e) {
            LOG.warn("Unable to parse the JWT token", e);
        }
    } else {
        LOG.trace("No JWT cookie found, do nothing");
    }

    filterChain.doFilter(servletRequest, servletResponse);
}

From source file:org.apache.rave.portal.service.impl.DefaultUserService.java

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

From source file:org.apache.syncope.core.provisioning.java.sync.AbstractProvisioningJob.java

@Override
protected String doExecute(final boolean dryRun) throws JobExecutionException {
    // PRE: grant all authorities (i.e. setup the SecurityContextHolder)
    List<GrantedAuthority> authorities = CollectionUtils.collect(Entitlement.values(),
            new Transformer<String, GrantedAuthority>() {

                @Override//from w ww .  jav  a2 s . c om
                public GrantedAuthority transform(final String entitlement) {
                    return new SyncopeGrantedAuthority(entitlement, SyncopeConstants.ROOT_REALM);
                }
            }, new ArrayList<GrantedAuthority>());

    UserDetails userDetails = new User("admin", "FAKE_PASSWORD", authorities);

    SecurityContextHolder.getContext().setAuthentication(
            new UsernamePasswordAuthenticationToken(userDetails, "FAKE_PASSWORD", authorities));

    try {
        Class<T> clazz = getTaskClassReference();
        if (!clazz.isAssignableFrom(task.getClass())) {
            throw new JobExecutionException("Task " + taskId + " isn't a SyncTask");
        }

        T provisioningTask = clazz.cast(this.task);

        Connector connector;
        try {
            connector = connFactory.getConnector(provisioningTask.getResource());
        } catch (Exception e) {
            final String msg = String.format(
                    "Connector instance bean for resource %s and connInstance %s not found",
                    provisioningTask.getResource(), provisioningTask.getResource().getConnector());

            throw new JobExecutionException(msg, e);
        }

        boolean noMapping = true;
        for (Provision provision : provisioningTask.getResource().getProvisions()) {
            Mapping mapping = provision.getMapping();
            if (mapping != null) {
                noMapping = false;
                if (mapping.getConnObjectKeyItem() == null) {
                    throw new JobExecutionException("Invalid ConnObjectKey mapping for provision " + provision);
                }
            }
        }
        if (noMapping) {
            return "No mapping configured for both users and groups: aborting...";
        }

        return executeWithSecurityContext(provisioningTask, connector, dryRun);
    } catch (Throwable t) {
        LOG.error("While executing provisioning job {}", getClass().getName(), t);
        throw t;
    } finally {
        // POST: clean up the SecurityContextHolder
        SecurityContextHolder.clearContext();
    }
}

From source file:org.apache.syncope.core.spring.security.AuthContextUtils.java

public static <T> T execWithAuthContext(final String domainKey, final Executable<T> executable) {
    SecurityContext ctx = SecurityContextHolder.getContext();
    setFakeAuth(domainKey);//  w w  w  .  jav  a2 s . co  m
    try {
        return executable.exec();
    } catch (Throwable t) {
        LOG.debug("Error during execution with domain {} context", domainKey, t);
        throw t;
    } finally {
        SecurityContextHolder.clearContext();
        SecurityContextHolder.setContext(ctx);
    }
}

From source file:org.apereo.portal.spring.security.preauth.PortalPreAuthenticatedProcessingFilter.java

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {

    // Set up some DEBUG logging for performance troubleshooting
    final long timestamp = System.currentTimeMillis();
    UUID uuid = null; // Tagging with a UUID (instead of username) because username changes in the /Login process
    if (logger.isDebugEnabled()) {
        uuid = UUID.randomUUID();
        final HttpServletRequest httpr = (HttpServletRequest) request;
        logger.debug("STARTING [" + uuid.toString() + "] for URI=" + httpr.getRequestURI() + " #milestone");
    }// w  ww  .j  av  a 2  s.co m

    HttpServletRequest httpServletRequest = (HttpServletRequest) request;
    String currentPath = httpServletRequest.getServletPath();

    /**
     * Override the base class's main filter method to bypass this filter if
     * we're currently at the login servlet.  Since that servlet sets up the 
     * user session and authentication, we need it to run before this filter
     * is useful.
     */
    if (loginPath.equals(currentPath)) {
        final org.springframework.security.core.Authentication originalAuthentication = SecurityContextHolder
                .getContext().getAuthentication();
        if (this.clearSecurityContextPriorToPortalAuthentication) {
            SecurityContextHolder.clearContext();
        }
        this.logForLoginPath(currentPath);
        this.doPortalAuthentication((HttpServletRequest) request, originalAuthentication);
        chain.doFilter(request, response);
    } else if (logoutPath.equals(currentPath)) {
        SecurityContextHolder.clearContext();
        this.logForLogoutPath(currentPath);
        chain.doFilter(request, response);
    }
    // otherwise, call the base class logic
    else {
        this.logForNonLoginOrLogoutPath(currentPath);
        super.doFilter(request, response, chain);
    }

    if (logger.isDebugEnabled()) {
        final HttpServletRequest httpr = (HttpServletRequest) request;
        logger.debug("FINISHED [" + uuid.toString() + "] for URI=" + httpr.getRequestURI() + " in "
                + Long.toString(System.currentTimeMillis() - timestamp) + "ms #milestone");
    }
}

From source file:org.artifactory.webapp.wicket.application.ArtifactoryWebSession.java

public void signOutArtifactory() {
    signOut();//from   w ww  . j  a v  a  2s .  c  o  m

    // Remove the authentication attribute early
    RequestUtils.removeAuthentication(WicketUtils.getHttpServletRequest());

    // Clear authentication and authorization data saved in this session
    // (this WICKET session will still be used in the logout page)
    roles = null;
    authentication = null;
    results = null;
    SecurityContextHolder.clearContext();
    invalidate();
}

From source file:org.artifactory.webapp.wicket.application.ArtifactoryWebSession.java

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

From source file:org.asqatasun.webapp.controller.LoginController.java

/**
 * /* w  w w .j  a  v  a  2s . com*/
 * @param request 
 */
private void logoutCurrentUser(HttpServletRequest request) {
    SecurityContextHolder.clearContext();
    HttpSession session = request.getSession(false);
    if (session != null) {
        session.invalidate();
    }
}

From source file:org.broadleafcommerce.profile.web.core.security.SessionFixationProtectionFilter.java

protected void abortUser(HttpServletRequest request, HttpServletResponse response) throws IOException {
    SecurityContextHolder.clearContext();
    cookieUtils.invalidateCookie(response, SessionFixationProtectionCookie.COOKIE_NAME);
    if (BLCRequestUtils.isOKtoUseSession(new ServletWebRequest(request))) {
        request.getSession().invalidate();
    }/*from  w  w w  .  j  av a 2 s  . c  om*/
    response.sendRedirect("/");
}