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:de.thm.arsnova.controller.LoginController.java

@RequestMapping(value = { "/auth/logout", "/logout" }, method = { RequestMethod.POST, RequestMethod.GET })
public View doLogout(final HttpServletRequest request) {
    final Authentication auth = SecurityContextHolder.getContext().getAuthentication();
    userService.removeUserFromMaps(userService.getCurrentUser());
    request.getSession().invalidate();/*from  w  ww .j  a  va 2s  . c  om*/
    SecurityContextHolder.clearContext();
    if (auth instanceof CasAuthenticationToken) {
        if ("".equals(apiPath)) {
            apiPath = request.getContextPath();
        }
        return new RedirectView(apiPath + "/j_spring_cas_security_logout");
    }
    return new RedirectView(request.getHeader("referer") != null ? request.getHeader("referer") : "/");
}

From source file:org.codehaus.groovy.grails.plugins.springsecurity.SpringSecurityUtils.java

/**
 * Execute a closure with the current authentication. Assumes that there's an authentication in the
 * http session and that the closure is running in a separate thread from the web request, so the
 * context and authentication aren't available to the standard ThreadLocal.
 *
 * @param closure the code to run//w  ww.  j  a v  a 2  s .  c  o m
 * @return the closure's return value
 */
public static Object doWithAuth(@SuppressWarnings("rawtypes") final Closure closure) {
    boolean set = false;
    if (SecurityContextHolder.getContext().getAuthentication() == null) {
        HttpSession httpSession = SecurityRequestHolder.getRequest().getSession(false);
        SecurityContext context = null;
        if (httpSession != null) {
            context = (SecurityContext) httpSession
                    .getAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY);
            if (context != null) {
                SecurityContextHolder.setContext(context);
                set = true;
            }
        }
    }

    try {
        return closure.call();
    } finally {
        if (set) {
            SecurityContextHolder.clearContext();
        }
    }
}

From source file:org.duracloud.account.app.controller.UserController.java

@RequestMapping(value = { "/redeem/{redemptionCode}" }, method = RequestMethod.GET)
public ModelAndView redeemUser(HttpServletRequest request, @PathVariable String redemptionCode)
        throws DBNotFoundException {
    log.info("getting redeem invitation {}", redemptionCode);

    // force logout
    request.getSession().invalidate();// ww  w  .  ja v  a 2s  .  co m
    SecurityContextHolder.clearContext();

    // add the redemption code to the session
    request.getSession(true).setAttribute("redemptionCode", redemptionCode);
    ModelAndView mav = new ModelAndView(HomeController.HOME_VIEW_ID);
    mav.addObject("redemptionCode", redemptionCode);
    return mav;
}

From source file:grails.plugin.springsecurity.SpringSecurityUtils.java

/**
 * Execute a closure with the current authentication. Assumes that there's an authentication in the
 * http session and that the closure is running in a separate thread from the web request, so the
 * context and authentication aren't available to the standard ThreadLocal.
 *
 * @param closure the code to run//from  ww w  . j  a va2  s. c  om
 * @return the closure's return value
 */
public static Object doWithAuth(@SuppressWarnings("rawtypes") final Closure closure) {
    boolean set = false;
    if (SecurityContextHolder.getContext().getAuthentication() == null
            && SecurityRequestHolder.getRequest() != null) {
        HttpSession httpSession = SecurityRequestHolder.getRequest().getSession(false);
        SecurityContext securityContext = null;
        if (httpSession != null) {
            securityContext = (SecurityContext) httpSession
                    .getAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY);
            if (securityContext != null) {
                SecurityContextHolder.setContext(securityContext);
                set = true;
            }
        }
    }

    try {
        return closure.call();
    } finally {
        if (set) {
            SecurityContextHolder.clearContext();
        }
    }
}

From source file:grails.plugin.springsecurity.SpringSecurityUtils.java

/**
 * Authenticate as the specified user and execute the closure with that authentication. Restores
 * the authentication to the one that was active if it exists, or clears the context otherwise.
 * <p/>/*from   ww w . j  av  a  2  s.  co m*/
 * This is similar to run-as and switch-user but is only local to a Closure.
 *
 * @param username the username to authenticate as
 * @param closure the code to run
 * @return the closure's return value
 */
public static Object doWithAuth(final String username, @SuppressWarnings("rawtypes") final Closure closure) {
    Authentication previousAuth = SecurityContextHolder.getContext().getAuthentication();
    reauthenticate(username, null);

    try {
        return closure.call();
    } finally {
        if (previousAuth == null) {
            SecurityContextHolder.clearContext();
        } else {
            SecurityContextHolder.getContext().setAuthentication(previousAuth);
        }
    }
}

From source file:edu.cmu.cs.lti.discoursedb.api.browsing.controller.BrowsingRestController.java

@Deprecated
@CrossOrigin(origins = "*", maxAge = 3600)
@RequestMapping(value = "/tokensigningoogle_deprecated", method = RequestMethod.POST, headers = "content-type=application/x-www-form-urlencoded")
public String processRegistration(@RequestParam("idtoken") String idTokenString) //, ModelMap model)
        throws GeneralSecurityException, IOException {
    logger.info("Doing tokensigningoogle");
    GoogleIdTokenVerifier verifier = new GoogleIdTokenVerifier.Builder(new NetHttpTransport(),
            new GsonFactory()).setAudience(Arrays.asList(environment.getRequiredProperty("google.client_id")))
                    .setIssuer("accounts.google.com").build();

    GoogleIdToken idToken = verifier.verify(idTokenString);
    if (idToken != null) {
        Payload payload = idToken.getPayload();
        // Print user identifier
        String userId = payload.getSubject();
        // Get profile information from payload
        String email = payload.getEmail();
        logger.info("Logged in " + userId + " " + email);
        boolean emailVerified = Boolean.valueOf(payload.getEmailVerified());
        //List<User> users = DbFunction.listHqlNew("FROM User WHERE email = :email", "email", email);

        if (!emailVerified) { //|| users.isEmpty()) {
            return "/error.html";
        } else {/*from   w ww. j a  va 2  s . com*/
            //List<String> roles = DbFunction.listSQLNew(
            //        "SELECT role.name FROM user_role_association JOIN role ON role.id = role_id JOIN user on user.id = user_id WHERE user.email = :email",
            //        "email", email);

            List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
            //for (String role : roles) {
            //    authorities.add(new SimpleGrantedAuthority(role));
            //}
            authorities.add(new SimpleGrantedAuthority("USER_AUTH0RITY"));

            UserDetails userDetails = new org.springframework.security.core.userdetails.User(userId, "xxy",
                    true, true, true, true, authorities);
            Authentication authentication = new UsernamePasswordAuthenticationToken(userId, null,
                    userDetails.getAuthorities());
            //UserDetails userDetails = new org.springframework.security.core.userdetails.User(users.get(0).getName(),
            //        "xx", users.get(0).isEnabled(), true, true, true, authorities);
            //Authentication authentication = new UsernamePasswordAuthenticationToken(users.get(0).getName(), null,
            //        userDetails.getAuthorities());
            SecurityContextHolder.clearContext();
            SecurityContextHolder.getContext().setAuthentication(authentication);
            httpSession.setAttribute("sch", userDetails);
            logger.info("first check " + httpSession.getAttribute("sch"));

            return "/browsing/databases";
        }
    } else {
        System.out.println("Invalid ID token.");
    }
    return "/error.html";
}

From source file:hudson.plugins.copyartifact.CopyArtifactTest.java

/**
 * When the source project name is parameterized, cannot check at configure
 * time whether the project is accessible. In this case, permission check is
 * done when the build runs. Only jobs accessible to all authenticated users
 * are allowed./*from   w  w w .  j a  v  a 2  s . c  om*/
 */
@LocalData
public void testPermissionWhenParameterized() throws Exception {
    FreeStyleProject p = createProject("test$JOB", "", "", false, false, false);
    // Build step should succeed when this parameter expands to a job accessible
    // to authenticated users (even if triggered by anonymous, as in this case):
    SecurityContextHolder.clearContext();
    FreeStyleBuild b = p
            .scheduleBuild2(0, new UserCause(), new ParametersAction(new StringParameterValue("JOB", "Job2")))
            .get();
    assertFile(true, "foo2.txt", b);
    assertBuildStatusSuccess(b);
    // Build step should fail for a job not accessible to all authenticated users,
    // even when accessible to the user starting the job, as in this case:
    SecurityContextHolder.getContext().setAuthentication(new UsernamePasswordAuthenticationToken("joe", "joe"));
    b = p.scheduleBuild2(0, new UserCause(), new ParametersAction(new StringParameterValue("JOB", "Job")))
            .get();
    assertFile(false, "foo.txt", b);
    assertBuildStatus(Result.FAILURE, b);
}

From source file:com.edgenius.wiki.security.service.SecurityServiceImpl.java

public void proxyLogout() {
    try {/*  ww  w.  j  a v a  2 s  .c o  m*/
        SecurityContextHolder.getContext().setAuthentication(null);
        SecurityContextHolder.clearContext();
        ProxyLoginUtil.setRequester(null);
    } catch (Exception e) {
        log.error("Proxy logout failed", e);
    }
}

From source file:hudson.plugins.copyartifact.CopyArtifactTest.java

public void testFieldValidation() throws Exception {
    FreeStyleProject p = createFreeStyleProject();
    CopyArtifact.DescriptorImpl descriptor = hudson.getDescriptorByType(CopyArtifact.DescriptorImpl.class);
    assertNotNull(descriptor);/*from  w  ww  .  java  2  s.com*/
    // Valid value
    assertSame(FormValidation.Kind.OK, descriptor.doCheckProjectName(p, p.getFullName()).kind);
    // Empty value
    assertSame(FormValidation.Kind.ERROR, descriptor.doCheckProjectName(p, "").kind);
    // Parameterized value
    assertSame(FormValidation.Kind.WARNING, descriptor.doCheckProjectName(p, "$FOO").kind);
    // Filter
    p.scheduleBuild2(0, new UserCause()).get();
    assertSame(FormValidation.Kind.OK,
            descriptor.doCheckProjectName(p, p.getFullName() + "/BUILD_NUMBER=1").kind);
    // Filter with invalid param
    assertSame(FormValidation.Kind.ERROR, descriptor.doCheckProjectName(p, p.getFullName() + "/FOO=1").kind);
    // Unparseable filter
    assertSame(FormValidation.Kind.ERROR, descriptor.doCheckProjectName(p, p.getFullName() + "/FOO-1").kind);
    // Just returns OK if no permission
    hudson.setAuthorizationStrategy(new GlobalMatrixAuthorizationStrategy());
    SecurityContextHolder.clearContext();
    assertSame(FormValidation.Kind.OK, descriptor.doCheckProjectName(p, "").kind);
    // Other descriptor methods
    assertTrue(descriptor.isApplicable(null));
    assertTrue(descriptor.getDisplayName().length() > 0);
    assertTrue(descriptor.getBuildSelectors().size() > 0);
}