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.encuestame.core.security.web.SecurityUtils.java

/**
 * Authenticate {@link UserAccount}.// ww w . j a v  a2  s  .c om
 * @param account {@link UserAccount}.
 */
public static void authenticate(final UserAccount account) {
    final EnMeUserAccountDetails details = SecurityUtils.convertUserAccountToUserDetails(account, true);
    //log.debug("+++++++++++ authenticate +++++++++++++");
    //final Collection<GrantedAuthority> authorities = ConvertDomainsToSecurityContext
    //.convertEnMePermission(account.getSecUserPermissions());
    final EnMeSecurityToken securityToken = new EnMeSecurityToken(account);
    //clear the context.
    SecurityContextHolder.clearContext();
    //set new authentication.
    SecurityContextHolder.getContext().setAuthentication(securityToken);
    if (log.isInfoEnabled()) {
        log.info("{authenticate} Username " + account.getUsername() + " is logged at " + new Date());
        log.debug("created EnMeUserAccountDetails" + details);
        //log.debug("created EnMeUserAccountDetails" +details.getAuthorities());
    }
    //log.debug("+++++++++++ end authenticate +++++++++++++");
}

From source file:org.finra.dm.app.AbstractAppTest.java

/**
 * Invalidated the user in session and also clears the spring security context.
 *///www.ja  v  a  2s .  c  o  m
protected void invalidateApplicationUser(HttpServletRequest request) {
    if (request != null) {
        HttpSession session = request.getSession(false);
        if (session != null) {
            session.invalidate();
        }
    }

    SecurityContextHolder.clearContext();
}

From source file:org.finra.dm.app.security.HttpHeaderAuthenticationFilter.java

/**
 * Invalidates a user by invalidating their session and removing them from the security context holder.
 *
 * @param servletRequest the servlet request.
 * @param invalidateSession flag to indicate whether the Http Session should be invalidated or not.
 *///from  ww  w  . j a va  2 s  .c o m
protected void invalidateUser(HttpServletRequest servletRequest, boolean invalidateSession) {
    if (invalidateSession) {
        HttpSession session = servletRequest.getSession(false);
        if (session != null) {
            LOGGER.debug("Invalidating the session.");
            session.invalidate();
        }
    }
    LOGGER.debug("Clearing the security context.");
    SecurityContextHolder.clearContext();
}

From source file:org.geoserver.test.GeoServerSystemTestSupport.java

/**
 * Clears the authentication context.
 * <p>
 * This method is called after each test case 
 * </p>
 */
protected void logout() {
    SecurityContextHolder.clearContext();
}

From source file:org.jamwiki.servlets.ServletUtil.java

/**
 * Retrieve the current <code>WikiUser</code> using the
 * <code>WikiUserDetails</code> from Spring Security
 * <code>SecurityContextHolder</code>. If there is no current user (the user
 * is not logged in) then this method will return an empty WikiUser. The
 * method will never return <code>null</code>.
 * //from www. j a  v a 2s  .c om
 * @return The current logged-in <code>WikiUser</code>, or an empty WikiUser
 *         if there is no user currently logged in.
 */
public static WikiUser currentWikiUser() throws AuthenticationCredentialsNotFoundException {
    WikiUserDetails userDetails = ServletUtil.currentUserDetails();
    WikiUser user = new WikiUser();
    String username = userDetails.getUsername();
    if (username.equals(WikiUserDetails.ANONYMOUS_USER_USERNAME)) {
        return user;
    }
    if (!WikiUtil.isFirstUse() && !WikiUtil.isUpgrade()) {
        try {
            // FIXME - do not lookup the user every time this method is called, that
            // will kill performance
            user = WikiBase.getDataHandler().lookupWikiUser(username);
        } catch (DataAccessException e) {
            logger.severe("Failure while retrieving user from database with login: " + username, e);
            return user;
        }
        if (user == null) {
            // invalid user. someone has either spoofed a cookie or the user account
            // is no longer in
            // the database.
            logger.warning(
                    "No user exists for principal found in security context authentication: " + username);
            SecurityContextHolder.clearContext();
            throw new AuthenticationCredentialsNotFoundException("Invalid user credentials found - username "
                    + username + " does not exist in this wiki installation");
        }
    }
    return user;
}

From source file:org.jamwiki.servlets.SetupServlet.java

/**
  *//from  w  ww .j av  a2  s .c  o  m
  */
private boolean initialize(HttpServletRequest request, ModelAndView next, WikiPageInfo pageInfo)
        throws Exception {
    setProperties(request, next);
    WikiUser user = setAdminUser(request);
    List<WikiMessage> errors = validate(request, user);
    if (!errors.isEmpty()) {
        this.view(request, next, pageInfo);
        next.addObject("errors", errors);
        next.addObject("username", user.getUsername());
        next.addObject("newPassword", request.getParameter("newPassword"));
        next.addObject("confirmPassword", request.getParameter("confirmPassword"));
        return false;
    }
    if (previousInstall() && request.getParameter("override") == null) {
        // user is trying to do a new install when a previous installation exists
        next.addObject("upgrade", "true");
        next.addObject("username", user.getUsername());
        next.addObject("newPassword", request.getParameter("newPassword"));
        next.addObject("confirmPassword", request.getParameter("confirmPassword"));
        return false;
    }
    Environment.setBooleanValue(Environment.PROP_BASE_INITIALIZED, true);
    Environment.setValue(Environment.PROP_BASE_WIKI_VERSION, WikiVersion.CURRENT_WIKI_VERSION);
    String username = request.getParameter("username");
    String newPassword = request.getParameter("newPassword");
    String encryptedPassword = Encryption.encrypt(newPassword);
    WikiBase.reset(request.getLocale(), user, username, encryptedPassword);
    JAMWikiAuthenticationConfiguration.resetJamwikiAnonymousAuthorities();
    JAMWikiAuthenticationConfiguration.resetDefaultGroupRoles();
    // Environment.saveProperties();
    // the setup process does not add new topics to the index (currently)
    // TODO - remove this once setup uses safe connection handling
    // WikiBase.getSearchEngine().refreshIndex();
    // force current user credentials to be removed and re-validated.
    SecurityContextHolder.clearContext();
    return true;
}

From source file:org.jamwiki.servlets.UpgradeServlet.java

/**
 *
 *//*w w w . ja v  a2s .  c  o m*/
private void upgrade(HttpServletRequest request, ModelAndView next, WikiPageInfo pageInfo) {
    if (pageInfo.getErrors().isEmpty()) {
        // success
        WikiMessage wm = new WikiMessage("upgrade.caption.upgradecomplete");
        VirtualWiki virtualWiki = VirtualWiki.defaultVirtualWiki();
        WikiLink wikiLink = new WikiLink(request.getContextPath(), virtualWiki.getName(),
                virtualWiki.getRootTopicName());
        try {
            String htmlLink = LinkUtil.buildInternalLinkHtml(wikiLink, virtualWiki.getRootTopicName(), null,
                    null, true);
            // do not escape the HTML link
            wm.setParamsWithoutEscaping(new String[] { htmlLink });
        } catch (DataAccessException e) {
            // building a link to the start page shouldn't fail, but if it does display a message
            wm = new WikiMessage("upgrade.error.nonfatal", e.toString());
            logger.warn("Upgrade complete, but unable to build redirect link to the start page.", e);
        }
        next.addObject("successMessage", wm);
        // force logout to ensure current user will be re-validated.  this is
        // necessary because the upgrade may have changed underlying data structures.
        SecurityContextHolder.clearContext();
    } else {
        // failure
        pageInfo.addError(new WikiMessage("upgrade.caption.upgradefailed"));
        next.addObject("failure", "true");
    }
    this.view(request, next, pageInfo);
}

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

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

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

    /**//from www .ja  va2  s . co m
     * 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)) {
        // clear out the current security context so we can re-establish
        // it once the new session is established
        SecurityContextHolder.clearContext();
        this.doPortalAuthentication((HttpServletRequest) request);
        chain.doFilter(request, response);
    }

    else if (logoutPath.equals(currentPath)) {
        // clear out the current security context so we can re-establish
        // it once the new session is established
        SecurityContextHolder.clearContext();
        chain.doFilter(request, response);
    }

    // otherwise, call the base class logic
    else {
        super.doFilter(request, response, chain);
    }

}

From source file:org.orcid.frontend.web.controllers.HomeController.java

@RequestMapping(value = "/userStatus.json")
@Produces(value = { MediaType.APPLICATION_JSON })
public @ResponseBody Object getUserStatusJson(HttpServletRequest request, HttpServletResponse response,
        @RequestParam(value = "logUserOut", required = false) Boolean logUserOut)
        throws NoSuchRequestHandlingMethodException {

    String orcid = getCurrentUserOrcid();

    if (logUserOut != null && logUserOut.booleanValue()) {
        SecurityContextHolder.clearContext();

        if (request.getSession(false) != null) {
            request.getSession().invalidate();
        }/*from   w w  w .  j a  v  a 2s.  c  o  m*/

        logoutCurrentUser(request, response);

        UserStatus us = new UserStatus();
        us.setLoggedIn(false);
        return us;
    } else {
        UserStatus us = new UserStatus();
        us.setLoggedIn((orcid != null));
        if (internalSSOManager.enableCookie()) {
            Cookie[] cookies = request.getCookies();
            //Update cookie 
            if (cookies != null) {
                for (Cookie cookie : cookies) {
                    if (InternalSSOManager.COOKIE_NAME.equals(cookie.getName())) {
                        //If there are no user, just delete the cookie and token
                        if (PojoUtil.isEmpty(orcid)) {
                            cookie.setMaxAge(0);
                            cookie.setValue(StringUtils.EMPTY);
                            response.addCookie(cookie);
                        } else if (internalSSOManager.verifyToken(orcid, cookie.getValue())) {
                            internalSSOManager.updateCookie(orcid, request, response);
                        }
                        break;
                    }
                }
            }
        }
        return us;
    }
}

From source file:org.slc.sli.api.jersey.PostProcessFilter.java

@Override
public ContainerResponse filter(ContainerRequest request, ContainerResponse response) {
    if (isRead(request.getMethod()) && isSuccessfulRead(response.getStatus())) {
        if (contextValidator.isUrlBlocked(request)) {
            throw new APIAccessDeniedException(
                    String.format("url %s is not accessible.", request.getAbsolutePath().toString()));
        }//w w w.j  a v a2  s .c  o  m

        SLIPrincipal principal = (SLIPrincipal) SecurityContextHolder.getContext().getAuthentication()
                .getPrincipal();
        principal.setSubEdOrgHierarchy(edOrgHelper.getStaffEdOrgsAndChildren());
        contextValidator.validateContextToUri(request, principal);
    }

    SecurityContextHolder.clearContext();

    if ("true".equals(apiPerformanceTracking)) {
        logApiDataToDb(request, response);
    }
    TenantContext.cleanup();
    printElapsed(request);
    expireCache();

    String queryString = "";
    if (null != request.getRequestUri().getQuery()) {
        queryString = "?" + request.getRequestUri().getQuery();
    }
    String executedPath = request.getPath() + queryString;

    // Truncate the executed path to avoid issues with response header length being too long for the servlet container
    if (executedPath != null && executedPath.length() > maxResponseHeaderXexecutedPath) {
        executedPath = executedPath.substring(0,
                Math.min(executedPath.length(), maxResponseHeaderXexecutedPath));
    }

    response.getHttpHeaders().add("X-RequestedPath", request.getProperties().get("requestedPath"));
    response.getHttpHeaders().add("X-ExecutedPath", executedPath);

    //        Map<String,Object> body = (Map<String, Object>) response.getEntity();
    //        body.put("requestedPath", request.getProperties().get("requestedPath"));
    //        body.put("executedPath", request.getPath());

    return response;
}