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:org.runway.utils.AuthenticationUtils.java

public static void autoLogin(User user, HttpServletRequest request,
        AuthenticationManager authenticationManager) {

    //           GrantedAuthority[] grantedAuthorities = new GrantedAuthority[] { new GrantedAuthorityImpl(
    //             user.getAuthority()) };

    UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(user.getUsername(),
            user.getPassword(), user.getAuthorities());

    // generate session if one doesn't exist
    HttpSession session = request.getSession();

    token.setDetails(new WebAuthenticationDetails(request));
    Authentication authenticatedUser = authenticationManager.authenticate(token);

    SecurityContextHolder.getContext().setAuthentication(authenticatedUser);
    // setting role to the session
    session.setAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY,
            SecurityContextHolder.getContext());

}

From source file:com.excilys.ebi.bank.web.controller.LoginController.java

@RequestMapping("/public/login.html")
public String login(ModelMap model, HttpSession session) {

    // hack : can't check SecurityContextHolder as login.html is not protected by Spring Security
    if (session.getAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY) != null) {
        return "redirect:" + loginSuccessHandler.getHomeUrl();
    }//  w  ww .  j ava2s  .c om

    return "public/login";
}

From source file:se.kth.csc.config.WebSecurityConfigurationAware.java

public MockHttpSession signInAs(final String principalName, final String... roles) {
    MockHttpSession session = new MockHttpSession();

    final List<GrantedAuthority> authorities = Lists.newArrayList();

    for (String role : roles) {
        authorities.add(new SimpleGrantedAuthority(role));
    }/*from  ww w.j av a 2s  . c o m*/

    session.setAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY,
            new MockSecurityContext(new AbstractAuthenticationToken(authorities) {
                @Override
                public Object getCredentials() {
                    return null;
                }

                @Override
                public Object getPrincipal() {
                    return principalName;
                }
            }));

    return session;
}

From source file:com.vdenotaris.spring.boot.security.saml.web.CommonTestSupport.java

public MockHttpSession mockHttpSession(boolean secured) {
    MockHttpSession mockSession = new MockHttpSession();
    SecurityContext mockSecurityContext = mock(SecurityContext.class);

    if (secured) {
        ExpiringUsernameAuthenticationToken principal = new ExpiringUsernameAuthenticationToken(null,
                USER_DETAILS, USER_NAME, AUTHORITIES);
        principal.setDetails(USER_DETAILS);
        when(mockSecurityContext.getAuthentication()).thenReturn(principal);
    }/*from   www. j  a va  2  s .c o  m*/

    SecurityContextHolder.setContext(mockSecurityContext);
    mockSession.setAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY,
            mockSecurityContext);

    return mockSession;
}

From source file:de.iew.web.utils.WebAutoLogin.java

public void autoLogin(UserDetails userDetails, HttpServletRequest request) {
    SecurityContext securityContext = SecurityContextHolder.getContext();

    HttpSession session = request.getSession(true);
    session.setAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY, securityContext);
    try {/*from  w  ww  . ja v  a 2s. co  m*/
        // @TODO Das funktioniert so nicht direkt. Habe es ohne Passwort Angabe nicht hinbekommen.
        UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(
                userDetails.getUsername(), "test", userDetails.getAuthorities());

        token.setDetails(new WebAuthenticationDetails(request));
        Authentication authentication = this.authenticationManager.authenticate(token);

        securityContext.setAuthentication(authentication);
    } catch (Exception e) {
        if (log.isInfoEnabled()) {
            log.info("Fehler whrend des Einlog-Versuchs.", e);
        }
        securityContext.setAuthentication(null);
    }
}

From source file:seava.j4e.web.controller.session.SessionController.java

/**
 * Show login page/*w w  w. j  a v a  2  s.co m*/
 * 
 * @return
 * @throws Exception
 */
@RequestMapping(value = "/" + Constants.SESSION_ACTION_SHOW_LOGIN)
public ModelAndView showLogin(HttpServletRequest request, HttpServletResponse response) throws Exception {

    // if user already authenticated redirect
    SecurityContext ctx = (SecurityContext) request.getSession()
            .getAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY);
    if (ctx != null && ctx.getAuthentication() != null) {
        Object su = ctx.getAuthentication().getPrincipal();
        if (su != null && (su instanceof ISessionUser) && (!((ISessionUser) su).isSessionLocked())) {
            response.sendRedirect(this.getSettings().get(Constants.PROP_CTXPATH));
            return null;
        }

    }

    Map<String, Object> model = new HashMap<String, Object>();
    model.put("loginPageCss", this.getSettings().get(Constants.PROP_LOGIN_PAGE_CSS));
    model.put("loginPageLogo", this.getSettings().get(Constants.PROP_LOGIN_PAGE_LOGO));
    model.put("currentYear", Calendar.getInstance().get(Calendar.YEAR) + "");

    model.put("productName", this.getSettings().getProductName());
    model.put("productDescription", this.getSettings().getProductDescription());
    model.put("productVersion", this.getSettings().getProductVersion());
    model.put("productUrl", this.getSettings().getProductUrl());
    model.put("productVendor", this.getSettings().getProductVendor());

    model.put("ctxpath", this.getSettings().get(Constants.PROP_CTXPATH));

    return new ModelAndView(this.loginViewName, model);

}

From source file:net.nan21.dnet.core.web.controller.session.SessionController.java

/**
 * Show login page//from ww  w . j  a  va 2 s  . c o m
 * 
 * @return
 * @throws Exception
 */
@RequestMapping(value = "/" + Constants.SESSION_ACTION_SHOW_LOGIN)
public ModelAndView showLogin(HttpServletRequest request, HttpServletResponse response) throws Exception {

    // if user already authenticated redirect
    SecurityContext ctx = (SecurityContext) request.getSession()
            .getAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY);
    if (ctx != null && ctx.getAuthentication() != null) {
        response.sendRedirect(Constants.URL_DNET_WEB);
        return null;
    }

    Map<String, Object> model = new HashMap<String, Object>();
    model.put("loginPageCss", this.getSettings().get(Constants.PROP_LOGIN_PAGE_CSS));
    model.put("loginPageLogo", this.getSettings().get(Constants.PROP_LOGIN_PAGE_LOGO));

    return new ModelAndView("login", model);

}

From source file:com.hillert.botanic.controller.AuthenticationController.java

@RequestMapping(value = "/authenticate", method = { RequestMethod.POST })
public AuthenticationToken authorize(@RequestBody AuthenticationRequest authenticationRequest,
        HttpServletRequest request) {/*  www.  ja  va 2s .  co m*/

    UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(
            authenticationRequest.getUsername(), authenticationRequest.getPassword());
    Authentication authentication = this.authenticationManager.authenticate(token);
    SecurityContextHolder.getContext().setAuthentication(authentication);
    HttpSession session = request.getSession(true);
    session.setAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY,
            SecurityContextHolder.getContext());

    UserDetails details = this.userDetailsService.loadUserByUsername(authenticationRequest.getUsername());

    final Map<String, Boolean> roles = new HashMap<String, Boolean>();

    for (GrantedAuthority authority : details.getAuthorities()) {
        roles.put(authority.toString(), Boolean.TRUE);
    }

    return new AuthenticationToken(details.getUsername(), roles, session.getId());
}

From source file:org.statefulj.webapp.services.impl.UserSessionServiceImpl.java

@Override
public void login(HttpSession session, User user) {
    UserDetails userDetails = this.getDetails(user);
    UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken(userDetails,
            user.getPassword(), userDetails.getAuthorities());
    SecurityContextHolder.getContext().setAuthentication(auth);
    session.setAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY,
            SecurityContextHolder.getContext());
}

From source file:ltistarter.BaseApplicationTest.java

/**
 * Makes a new session which contains authentication roles,
 * this allows us to test requests with varying types of security
 *
 * @param username the username to set for the session
 * @param roles    all the roles to grant for this session
 * @return the session object to pass to mockMvc (e.g. mockMvc.perform(get("/").session(session))
 *///from  w w w .j  a  v a  2 s .  co m
public MockHttpSession makeAuthSession(String username, String... roles) {
    if (StringUtils.isEmpty(username)) {
        username = "azeckoski";
    }
    MockHttpSession session = new MockHttpSession();
    session.setAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY,
            SecurityContextHolder.getContext());
    Collection<GrantedAuthority> authorities = new HashSet<>();
    if (roles != null && roles.length > 0) {
        for (String role : roles) {
            authorities.add(new SimpleGrantedAuthority(role));
        }
    }
    //Authentication authToken = new UsernamePasswordAuthenticationToken("azeckoski", "password", authorities); // causes a NPE when it tries to access the Principal
    Principal principal = new MyOAuthAuthenticationHandler.NamedOAuthPrincipal(username, authorities, "key",
            "signature", "HMAC-SHA-1", "signaturebase", "token");
    Authentication authToken = new UsernamePasswordAuthenticationToken(principal, null, authorities);
    SecurityContextHolder.getContext().setAuthentication(authToken);
    return session;
}