Example usage for org.springframework.security.web.context HttpSessionSecurityContextRepository SPRING_SECURITY_CONTEXT_KEY

List of usage examples for org.springframework.security.web.context HttpSessionSecurityContextRepository SPRING_SECURITY_CONTEXT_KEY

Introduction

In this page you can find the example usage for org.springframework.security.web.context HttpSessionSecurityContextRepository SPRING_SECURITY_CONTEXT_KEY.

Prototype

String SPRING_SECURITY_CONTEXT_KEY

To view the source code for org.springframework.security.web.context HttpSessionSecurityContextRepository SPRING_SECURITY_CONTEXT_KEY.

Click Source Link

Document

The default key under which the security context will be stored in the session.

Usage

From source file:com.company.project.web.controller.LoginTest.java

public void testCreateAuthentication() throws Exception {
    // http://spring.io/blog/2014/05/23/preview-spring-security-test-web-security
    // code to run as a specific user for every request to run a test with any of the approaches described in Method Based Security Testing
    //        mockMvc = MockMvcBuilders.webAppContextSetup(wac)
    //                .defaultRequest(get("/").with(userAdmin()))
    //                .addFilters(springSecurityFilterChain)
    //                .build();

    mockMvc = MockMvcBuilders.webAppContextSetup(wac).addFilter(springSecurityFilterChain, "/login*").build();

    // run as a user (which does not need to exist) 
    session = (MockHttpSession) mockMvc//  www .  j av  a2 s  .  c  om
            .perform(post("/login").with(user("admin").password("admin").roles("USER", "ADMIN")).with(csrf()))
            .andExpect(status().isOk())
            //.andExpect(redirectedUrl("/admin"))
            .andReturn().getRequest().getSession();

    assertNotNull(session);

    assertNotNull(session.getAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY));
    assertNotNull(SecurityContextHolder.getContext().getAuthentication());

    Authentication auth = ((SecurityContextImpl) session
            .getAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY))
                    .getAuthentication();

    assertNotNull(auth);

    assertEquals("admin", ((UserDetails) auth.getPrincipal()).getUsername());
    assertEquals("ROLE_ADMIN", ((UserDetails) auth.getPrincipal()).getAuthorities().toArray()[0].toString());
    assertEquals("ROLE_USER", ((UserDetails) auth.getPrincipal()).getAuthorities().toArray()[1].toString());
}

From source file:com.company.project.web.controller.LoginTest.java

@Test
public void itShouldAllowAccessToSecuredPageForPermittedUser() throws Exception {
    Authentication authentication = new UsernamePasswordAuthenticationToken("admin", "admin");
    SecurityContext securityContext = SecurityContextHolder.getContext();
    securityContext.setAuthentication(authentication);

    MockHttpSession session = new MockHttpSession();
    session.setAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY, securityContext);

    mockMvc.perform(get("/admin").session(session)).andExpect(status().isOk());
}

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  w w . ja  v  a  2 s  .co 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:info.raack.appliancelabeler.web.MainController.java

private String getUserId(HttpServletRequest request, HttpServletResponse response, boolean trueId) {
    // extract userid from spring security
    Authentication auth = SecurityContextHolder.getContext().getAuthentication();

    if ((trueId && userDetails.getTrueUserId() == null)
            || (!trueId && userDetails.getEffectiveUserId() == null)) {
        if (auth != null && auth.isAuthenticated() && !(auth instanceof AnonymousAuthenticationToken)) {
            // user is already logged in via spring security
            String userId = null;
            if (auth instanceof RememberMeAuthenticationToken) {
                userId = ((OAuthUserDetails) auth.getPrincipal()).getUsername();
            } else {
                userId = (String) auth.getPrincipal();
            }//from   w w  w.j  ava  2 s  .  co  m
            userDetails.setUserId(userId);
            return userId;

        } else if (auth == null || !auth.isAuthenticated() || auth instanceof AnonymousAuthenticationToken) {
            logger.info(
                    "User is not logged in, so let's get their info by accessing the stepgreen service userinfo uri and forcing a login");
            StepgreenUserDetails capturedDetails = null;
            try {
                capturedDetails = dataService.getStepgreenUserInfo();
                logger.debug("Got user id: " + capturedDetails.getTrueUserId());
                OAuthAutomaticAuthenticationToken token = new OAuthAutomaticAuthenticationToken(
                        capturedDetails.getTrueUserId());

                // generate session if one does not exist
                request.getSession();
                SecurityContextHolder.getContext().setAuthentication(token);
                request.getSession().setAttribute(
                        HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY,
                        SecurityContextHolder.getContext());

                // add email to session, so that the remember me services can remember it
                request.getSession().setAttribute(HttpSessionAndDatabaseOAuthRemeberMeServices.EMAIL_ATTRIBUTE,
                        capturedDetails.getEmail());

                // remember the new authentication
                rememberMeServices.loginSuccess(request, response, token);

                userDetails.setUserId(capturedDetails.getTrueUserId());
                return capturedDetails.getTrueUserId();

            } catch (Exception e) {
                throw new RuntimeException("Could not get user id from stepgreen", e);
            }
        } else {
            throw new RuntimeException("Could not get user id");
        }
    } else {
        return userDetails.getEffectiveUserId();
    }
}

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  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
            && 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

public static SecurityContext getSecurityContext(final HttpSession session) {
    Object securityContext = session
            .getAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY);
    if (securityContext instanceof SecurityContext) {
        return (SecurityContext) securityContext;
    }/*w  w w. j a va 2  s  .  c om*/
    return null;
}

From source file:org.broadleafcommerce.common.web.resource.BroadleafResourceHttpRequestHandler.java

protected SecurityContext readSecurityContextFromSession(HttpSession httpSession) {
    if (httpSession == null) {
        return null;
    }// ww  w. j a v  a2 s .  co  m

    Object ctxFromSession = httpSession
            .getAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY);
    if (ctxFromSession == null) {
        return null;
    }

    if (!(ctxFromSession instanceof SecurityContext)) {
        return null;
    }

    return (SecurityContext) ctxFromSession;
}

From source file:org.cloudfoundry.identity.uaa.mock.token.TokenMvcMockTests.java

public void setAuthentication(MockHttpSession session, ScimUser developer) {
    UaaPrincipal p = new UaaPrincipal(developer.getId(), developer.getUserName(), developer.getPrimaryEmail(),
            OriginKeys.UAA, "", IdentityZoneHolder.get().getId());
    UaaAuthentication auth = new UaaAuthentication(p, UaaAuthority.USER_AUTHORITIES,
            new UaaAuthenticationDetails(false, "clientId", OriginKeys.ORIGIN, "sessionId"));
    Assert.assertTrue(auth.isAuthenticated());
    SecurityContextHolder.getContext().setAuthentication(auth);
    session.setAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY,
            new MockSecurityContext(auth));
}

From source file:org.cloudfoundry.identity.uaa.mock.util.MockMvcUtils.java

public static String getUserOAuthAccessTokenAuthCode(MockMvc mockMvc, String clientId, String clientSecret,
        String userId, String username, String password, String scope) throws Exception {
    String basicDigestHeaderValue = "Basic " + new String(
            org.apache.commons.codec.binary.Base64.encodeBase64((clientId + ":" + clientSecret).getBytes()));
    UaaPrincipal p = new UaaPrincipal(userId, username, "test@test.org", OriginKeys.UAA, "",
            IdentityZoneHolder.get().getId());
    UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken(p, "",
            UaaAuthority.USER_AUTHORITIES);
    Assert.assertTrue(auth.isAuthenticated());

    SecurityContextHolder.getContext().setAuthentication(auth);
    MockHttpSession session = new MockHttpSession();
    session.setAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY,
            new MockSecurityContext(auth));

    String state = new RandomValueStringGenerator().generate();
    MockHttpServletRequestBuilder authRequest = get("/oauth/authorize")
            .header("Authorization", basicDigestHeaderValue).header("Accept", MediaType.APPLICATION_JSON_VALUE)
            .session(session).param(OAuth2Utils.GRANT_TYPE, "authorization_code")
            .param(OAuth2Utils.RESPONSE_TYPE, "code")
            .param(TokenConstants.REQUEST_TOKEN_FORMAT, TokenConstants.OPAQUE).param(OAuth2Utils.STATE, state)
            .param(OAuth2Utils.CLIENT_ID, clientId).param(OAuth2Utils.REDIRECT_URI, "http://localhost/test");
    if (StringUtils.hasText(scope)) {
        authRequest.param(OAuth2Utils.SCOPE, scope);
    }/*from   ww  w. j  av  a  2  s  .c o  m*/

    MvcResult result = mockMvc.perform(authRequest).andExpect(status().is3xxRedirection()).andReturn();
    String location = result.getResponse().getHeader("Location");
    UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(location);
    String code = builder.build().getQueryParams().get("code").get(0);

    authRequest = post("/oauth/token").header("Authorization", basicDigestHeaderValue)
            .header("Accept", MediaType.APPLICATION_JSON_VALUE)
            .param(OAuth2Utils.GRANT_TYPE, "authorization_code").param(OAuth2Utils.RESPONSE_TYPE, "token")
            .param("code", code).param(OAuth2Utils.CLIENT_ID, clientId)
            .param(OAuth2Utils.REDIRECT_URI, "http://localhost/test");
    if (StringUtils.hasText(scope)) {
        authRequest.param(OAuth2Utils.SCOPE, scope);
    }
    result = mockMvc.perform(authRequest).andExpect(status().is2xxSuccessful()).andReturn();
    InjectedMockContextTest.OAuthToken oauthToken = JsonUtils
            .readValue(result.getResponse().getContentAsString(), InjectedMockContextTest.OAuthToken.class);
    return oauthToken.accessToken;

}

From source file:org.dataconservancy.ui.stripes.AddCollectionActionBeanTest.java

/**
 * Initialize the mock http session with authenticated user credentials. Tests that re-use this mock session will be
 * already logged in./*from  ww w . ja v  a 2 s  . com*/
 */
@Before
public void setUpMockttpSessions() throws Exception {

    // Mock a session for a registered, authorized user.
    userSession = new MockHttpSession(servletCtx);
    MockRoundtrip rt = new MockRoundtrip(servletCtx, "/j_spring_security_check", userSession);
    rt.setParameter("j_username", user.getEmailAddress());
    rt.setParameter("j_password", user.getPassword());
    rt.execute();
    SecurityContext ctx = (SecurityContext) userSession
            .getAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY);
    assertNotNull("Spring Security Context was null!", ctx);
    assertEquals(user.getEmailAddress(), ((UserDetails) ctx.getAuthentication().getPrincipal()).getUsername());

    // Mock a session for a system-wide admin user
    adminSession = new MockHttpSession(servletCtx);
    rt = new MockRoundtrip(servletCtx, "/j_spring_security_check", adminSession);
    rt.setParameter("j_username", admin.getEmailAddress());
    rt.setParameter("j_password", admin.getPassword());
    rt.execute();
    ctx = (SecurityContext) adminSession
            .getAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY);
    assertNotNull("Spring Security Context was null!", ctx);
    assertEquals(admin.getEmailAddress(), ((UserDetails) ctx.getAuthentication().getPrincipal()).getUsername());

    modifiedCollection = new Collection();
    modifiedCollection.setId("collectionWithData:/1");
    modifiedCollection.setTitle("Star Wars 2.0");
    modifiedCollection.setSummary("In space...");
    modifiedCollection.setCitableLocator("Nowhere");
    modifiedCollection.setPublicationDate(DateTime.now());
    modifiedCollection.getAlternateIds().add("iWars");
    modifiedCollection.getAlternateIds().add("ID:/2");
    modifiedCollection.addContactInfo(contactInfoOne);
    modifiedCollection.addCreator(creatorOne);

    collectionOne.setId("newID");
    collectionOne.addContactInfo(contactInfoOne);
    collectionOne.addCreator(creatorOne);

    subCollection = new Collection();
    subCollection.setId("SubCollectionId");
    subCollection.setTitle("Child collection title");
    subCollection.setSummary("Child collection summary.");
    subCollection.addCreator(creatorOne);

    // Put the collection attribute on both sessions
    userSession.setAttribute("collection", new Collection(collectionOne));
    adminSession.setAttribute("collection", new Collection(collectionOne));
}