Java 类org.springframework.security.web.context.HttpSessionSecurityContextRepository 实例源码

项目:esup-ecandidat    文件:RecoverSecurityContextAtmosphereInterceptor.java   
/**
 * @see org.atmosphere.cpr.AtmosphereInterceptor#inspect(org.atmosphere.cpr.AtmosphereResource)
 */
@Override
public Action inspect(final AtmosphereResource atmosphereResource) {
    try {
        SecurityContext context = (SecurityContext) atmosphereResource.getRequest().getSession().getAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY);
        final Authentication auth = context.getAuthentication();
        if (auth instanceof Authentication) {
            MDC.put(UserMdcServletFilter.USER_KEY, auth.getName());
            logger.trace("Username set in MDC");
        }   
    } catch (final NullPointerException e) {}
    return Action.CONTINUE;
}
项目:esup-ecandidat    文件:UserController.java   
/**
 * Alimente la session pour un compte local
 * 
 * @param cptMin
 *            le compte a minima a connecter
 */
public void alimenteSecurityUserCptMin(CompteMinima cptMin) {
    SecurityUser user = (SecurityUser) getCurrentUser();
    if (user != null) {
        List<GrantedAuthority> authoritiesListe = new ArrayList<GrantedAuthority>();
        SimpleGrantedAuthority sga = new SimpleGrantedAuthority(ConstanteUtils.ROLE_CANDIDAT);
        authoritiesListe.add(sga);

        SecurityUserCandidat securityUserCandidat = new SecurityUserCandidat(user.getUsername(),
                user.getDisplayName(), authoritiesListe, cptMin.getIdCptMin(), cptMin.getNumDossierOpiCptMin(),
                cptMin.getTemValidCptMin(), cptMin.getTemValidMailCptMin(), null);
        UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(
                securityUserCandidat, securityUserCandidat.getUsername(), securityUserCandidat.getAuthorities());
        Authentication authentication = authenticationManagerCandidat.authenticate(authRequest);
        SecurityContext context = SecurityContextHolder.createEmptyContext();
        context.setAuthentication(authentication);
        SecurityContextHolder.setContext(context);
        UI.getCurrent().getSession().getSession()
                .setAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY, context);
    }
}
项目:esup-ecandidat    文件:UiController.java   
/**
 * @param user
 * @return un user
 */
public UserDetails getUser(SessionPresentation user){
    for (MainUI ui : getUis()){
        try{
            VaadinSession session = ui.getSession();
            if (session == null || session.getSession()==null){
                return null;
            }
            SecurityContext securityContext = (SecurityContext) session.getSession().getAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY);

            if (securityContext==null || securityContext.getAuthentication()==null){
                return null;
            }else{
                UserDetails details = (UserDetails) securityContext.getAuthentication().getPrincipal();
                if (details!=null && details.getUsername().equals(user.getId())){
                    return details;
                }
            }               
        }catch (Exception e){}  
    }
    return null;
}
项目:esup-ecandidat    文件:TestController.java   
public void deleteCandidat() {
    SecurityUserCandidat cand = userController.getSecurityUserCandidat();
    if (cand != null) {
        CompteMinima cpt = compteMinimaRepository.findOne(cand.getIdCptMin());
        if (cpt != null) {
            logger.debug("Delete compte NoDossier = " + cpt.getNumDossierOpiCptMin());
            compteMinimaRepository.delete(cpt);
            uiController.unregisterUiCandidat(MainUI.getCurrent());
            SecurityContext context = SecurityContextHolder.createEmptyContext();
            SecurityContextHolder.setContext(context);
            UI.getCurrent().getSession().getSession()
                    .setAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY, context);
            MainUI current = (MainUI) UI.getCurrent();
            uiController.registerUiCandidat(current);
            current.navigateToAccueilView();
        }
    }
}
项目:spring-cloud-dashboard    文件:LoginController.java   
@RequestMapping(value = "/authenticate", method = { RequestMethod.POST })
@ResponseBody
public String authorize(
        @RequestBody AuthenticationRequest authenticationRequest,
        HttpServletRequest request) {

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

    return session.getId();
}
项目:spring-security-adfs-saml2    文件:MockFilterSecurityInterceptor.java   
@Override
public void doFilter(final ServletRequest servletRequest,
                     final ServletResponse servletResponse,
                     final FilterChain filterChain) throws IOException, ServletException {

    // To be consistent with SAML configuration, the `userDetails` is set as `principal` too
    final UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(
            user,
            null,
            user.getAuthorities());

    // setting user details
    authentication.setDetails(user);

    // setting `authentication` to security context
    final SecurityContext securityContext = SecurityContextHolder.getContext();
    securityContext.setAuthentication(authentication);

    // setting `authentication` to HTTP session
    ((HttpServletRequest) servletRequest)
            .getSession(true)
            .setAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY, securityContext);

    filterChain.doFilter(servletRequest, servletResponse);
}
项目:SparkCommerce    文件:SparkResourceHttpRequestHandler.java   
protected SecurityContext readSecurityContextFromSession(HttpSession httpSession) {
    if (httpSession == null) {
        return null;
    }

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

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

    return (SecurityContext) ctxFromSession;
}
项目:hawkbit    文件:DelayedEventBusPushStrategy.java   
private void doDispatch(final List<TenantAwareEvent> events, final WrappedSession wrappedSession) {
    final SecurityContext userContext = (SecurityContext) wrappedSession
            .getAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY);
    final SecurityContext oldContext = SecurityContextHolder.getContext();
    try {
        SecurityContextHolder.setContext(userContext);

        final List<EventContainer<TenantAwareEvent>> groupedEvents = groupEvents(events, userContext,
                eventProvider);

        vaadinUI.access(() -> {
            if (vaadinSession.getState() != State.OPEN) {
                return;
            }
            LOG.debug("UI EventBus aggregator of UI {} got lock on session.", vaadinUI.getUIId());
            groupedEvents.forEach(holder -> eventBus.publish(vaadinUI, holder));
            LOG.debug("UI EventBus aggregator of UI {} left lock on session.", vaadinUI.getUIId());
        }).get();
    } catch (InterruptedException | ExecutionException e) {
        LOG.warn("Wait for Vaadin session for UI {} interrupted!", vaadinUI.getUIId(), e);
    } finally {
        SecurityContextHolder.setContext(oldContext);
    }
}
项目:blcdemo    文件:BroadleafContextUtil.java   
protected SecurityContext readSecurityContextFromSession(HttpSession httpSession) {
    if (httpSession == null) {
        return null;
    }

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

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

    return (SecurityContext) ctxFromSession;
}
项目:motech    文件:PasswordRecoveryServiceImpl.java   
@Override
@Transactional
public void validateTokenAndLoginUser(String token, HttpServletRequest request, HttpServletResponse response) throws IOException {
    PasswordRecovery recovery = findForToken(token);
    if (validateRecovery(recovery)) {
        MotechUser user = motechUsersDao.findUserByEmail(recovery.getEmail());
        OpenIDAuthenticationToken openIDToken = new OpenIDAuthenticationToken(OpenIDAuthenticationStatus.SUCCESS, user.getOpenId(), "one time login ", new ArrayList<>());
        Authentication authentication = authenticationManager.authenticate(openIDToken);
        SecurityContextHolder.getContext().setAuthentication(authentication);
        request.getSession(true).setAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY, SecurityContextHolder.getContext());
        passwordRecoveriesDataService.delete(recovery);
        redirectStrategy.sendRedirect(request, response, "/server/home");
    } else {
        redirectStrategy.sendRedirect(request, response, "/server/login");
    }
}
项目:motech    文件:SecurityRuleBuilder.java   
private List<Filter> addFilters(MotechURLSecurityRule securityRule) throws ServletException {
    List<Filter> filters = new ArrayList<>();

    SecurityContextRepository contextRepository = new HttpSessionSecurityContextRepository();
    RequestCache requestCache = new HttpSessionRequestCache();

    addSecureChannel(filters, securityRule.getProtocol());
    addSecurityContextPersistenceFilter(filters, contextRepository);
    addLogoutFilter(filters, securityRule);
    addAuthenticationFilters(filters, securityRule);
    addRequestCacheFilter(filters, requestCache);
    addSecurityContextHolderAwareRequestFilter(filters);
    addAnonymousAuthenticationFilter(filters);
    addSessionManagementFilter(filters, contextRepository);
    addExceptionTranslationFilter(filters, requestCache, securityRule.isRest());
    addFilterSecurityInterceptor(filters, securityRule);

    return filters;
}
项目:springfield    文件:AbstractContextWebmvcSecurityTestRoot.java   
protected MockHttpSession login() throws Exception {
    MockHttpSession httpSession = new MockHttpSession(); 

        String principal = "a";
    String credentials = "a";
    List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
    authorities.add(new SimpleGrantedAuthority("ROLE_ANONYMOUS"));
    authorities.add(new SimpleGrantedAuthority("ROLE_USER"));
    authorities.add(new SimpleGrantedAuthority("ROLE_ADMIN"));


    UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(principal, credentials, authorities);
    httpSession.setAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY,  SecurityContextHolder.getContext());
    SecurityContextHolder.getContext().setAuthentication(authentication);
    logger.debug("===========================================================");
    logger.debug(""+SecurityContextHolder.getContext().getAuthentication());
    logger.debug("===========================================================");

    return httpSession;
}
项目:orchidae    文件:_PictureController.java   
@Before
public void setup() {
    controller = new PictureController();
    controller.userUtil = userUtil;
    controller.factory = factory;
    controller.fileUtil = fileUtil;
    controller.latestPictureLimit = 10;
    controller.hookHandler = hookHandler;

    mvc = MockMvcBuilders.standaloneSetup(controller).setMessageConverters(new EntityConverter(factory),
            new StringHttpMessageConverter(), new ResourceHttpMessageConverter()).build();

    setAuthentication(owner);

    // TODO this information should be pulled out from somewhere else
    factory.create(User.class).setUsername(ownr).setPassword("1").setMemberSince(DateTime.now()).setPictureCount(
            new AtomicInteger(0)).save();

    session = new MockHttpSession();
    session.setAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY,
            SecurityContextHolder.getContext());
}
项目:spring-boot-security-saml-sample    文件: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);
    }

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

    return mockSession;
}
项目:spring-boot-security-saml-sample    文件:CommonTestSupport.java   
public MockHttpSession mockAnonymousHttpSession() {
    MockHttpSession mockSession = new MockHttpSession();

    SecurityContext mockSecurityContext = mock(SecurityContext.class);

    AnonymousAuthenticationToken principal =
            new AnonymousAuthenticationToken(
                    ANONYMOUS_USER_KEY,
                    ANONYMOUS_USER_PRINCIPAL,
                    AUTHORITIES);

    when(mockSecurityContext.getAuthentication()).thenReturn(principal);

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

    return mockSession;
}
项目:wicket-spring-jpa-bootstrap-boilerplate    文件:SSAuthenticatedWebSession.java   
@Override
public boolean authenticate(String username, String password) {
    boolean authenticated;
    try {
        Authentication authentication = authenticationManager.authenticate(
                new UsernamePasswordAuthenticationToken(username, password));
        SecurityContextHolder.getContext().setAuthentication(authentication);      
        httpSession.setAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY,
                SecurityContextHolder.getContext());
        authenticated = authentication.isAuthenticated();
    } catch (AuthenticationException e) {
        log.warn("User '{}' failed to login. Reason: {}", username, e.getMessage());
        authenticated = false;
    }
    return authenticated;
}
项目:lti_starter    文件: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))
 */
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;
}
项目:jdal    文件:SpringAuthManager.java   
@Override
public boolean validate(String username, String password) {
    UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(username, password);
    try {
        Authentication auth = this.authenticationManager.authenticate(token);
        if (auth.isAuthenticated()) {
            // execute session authentication strategy
            if (this.sessionStrategy != null)
                this.sessionStrategy.onAuthentication(auth, VaadinServletService.getCurrentServletRequest(),
                        VaadinServletService.getCurrentResponse());
            SecurityContextHolder.getContext().setAuthentication(auth);
            // save request in context session
            VaadinSession.getCurrent().getSession().setAttribute(
                    HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY,
                    SecurityContextHolder.getContext());

            return  true;
        }
        SecurityContextHolder.clearContext();
        return false;
    }
    catch(AuthenticationException ae) {
        SecurityContextHolder.clearContext();
        return false;
    }
}
项目:spring-microservice-sample    文件:AuthenticationController.java   
private AuthenticationResult handleAuthentication(
    String username,
    String password,
    HttpServletRequest request) {

    final UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(
        username,
        password
    );

    final Authentication authentication = this.authenticationManager
        .authenticate(token);

    SecurityContextHolder.getContext().setAuthentication(authentication);

    final HttpSession session = request.getSession(true);

    session.setAttribute(
        HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY,
        SecurityContextHolder.getContext());

    return AuthenticationResult.builder()
        .name(authentication.getName())
        .roles(authentication.getAuthorities().stream().map(r -> r.getAuthority()).collect(Collectors.toList()))
        .token(session.getId())
        .build();
}
项目:esup-ecandidat    文件:UserController.java   
/**
 * Récupère le securityContext dans la session.
 * 
 * @return securityContext associé à la session
 */
public SecurityContext getSecurityContextFromSession() {
    if (UI.getCurrent() != null && UI.getCurrent().getSession() != null
            && UI.getCurrent().getSession().getSession() != null) {
        return (SecurityContext) UI.getCurrent().getSession().getSession()
                .getAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY);
    }
    return null;
}
项目:esup-ecandidat    文件:UserController.java   
/**
 * Nettoie la session
 */
private void disconnectUser() {
    SecurityContext context = SecurityContextHolder.createEmptyContext();
    SecurityContextHolder.setContext(context);
    UI.getCurrent().getSession().getSession()
            .setAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY, context);
    UI.getCurrent().getSession().close();
}
项目:esup-ecandidat    文件:LockController.java   
/**
 * Retourne le nom de l'utilisateur pour le lock passé en paramètre
 * @param obj
 * @return userName
 */
private String getUserNameFromLock(Object obj){
    UI lockUi = locks.get(obj);
    if (lockUi != null) {
        SecurityContext securityContext = (SecurityContext) lockUi.getSession().getSession().getAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY);
        return securityContext.getAuthentication().getName();
    }
    return null;
}
项目:esup-ecandidat    文件:UiController.java   
/**
 * Ajoute une UI à la liste des UIs connectées
 * @param ui l'UI a ajouter
 */
public synchronized void registerUI(final MainUI ui) {
    VaadinSession session = ui.getSession();
    if (session==null || session.getSession()==null){
        return;
    }
    SecurityContext securityContext = (SecurityContext) session.getSession().getAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY);

    if (securityContext==null || securityContext.getAuthentication()==null){
        return;
    }
    uis.add(ui);
}
项目:esup-ecandidat    文件:UiController.java   
/**
 * Ferme toutes les sessions associées à un utilisateur
 * @param user le user a kill
 */
public synchronized void killUser(UserDetails user) {
    for (MainUI mainUI : uis) {
        SecurityContext securityContext = (SecurityContext) mainUI.getSession().getSession().getAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY);            
        if (user.getUsername().equals(securityContext.getAuthentication().getName())) {
            mainUI.close();
        }
    }
}
项目:dhis2-core    文件:DhisWebSpringTest.java   
public MockHttpSession getSession( String... authorities )
{
    SecurityContextHolder.getContext().setAuthentication( getPrincipal( authorities ) );
    MockHttpSession session = new MockHttpSession();

    session.setAttribute(
        HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY,
        SecurityContextHolder.getContext() );

    return session;
}
项目:spring-boot-security-saml-samples    文件:WebSecurityConfig.java   
/**
 * Defines the web based security configuration.
 *
 * @param http It allows configuring web based security for specific http requests.
 */
@Override
protected void configure(HttpSecurity http) throws Exception {
    HttpSessionSecurityContextRepository securityContextRepository = new HttpSessionSecurityContextRepository();
    securityContextRepository.setSpringSecurityContextKey("SPRING_SECURITY_CONTEXT_SAML");
    http
            .securityContext()
            .securityContextRepository(securityContextRepository);
    http
            .httpBasic()
            .disable();
    http
            .csrf()
            .disable();
    http
            .addFilterAfter(metadataGeneratorFilter, BasicAuthenticationFilter.class)
            .addFilterAfter(metadataDisplayFilter, MetadataGeneratorFilter.class)
            .addFilterAfter(samlEntryPoint, MetadataDisplayFilter.class)
            .addFilterAfter(samlWebSSOProcessingFilter, SAMLEntryPoint.class)
            .addFilterAfter(samlWebSSOHoKProcessingFilter, SAMLProcessingFilter.class)
            .addFilterAfter(samlLogoutProcessingFilter, SAMLWebSSOHoKProcessingFilter.class)
            .addFilterAfter(samlIDPDiscovery, SAMLLogoutProcessingFilter.class)
            .addFilterAfter(samlLogoutFilter, LogoutFilter.class);
    http
            .authorizeRequests()
            .antMatchers("/", "/error", "/saml/**", "/idpselection").permitAll()
            .anyRequest().authenticated();
    http
            .exceptionHandling()
            .authenticationEntryPoint(samlEntryPoint);
    http
            .logout()
            .disable();
}
项目:spring-cloud-dataflow    文件:LoginController.java   
@RequestMapping(value = "/authenticate", method = { RequestMethod.POST })
@ResponseBody
public String authorize(@RequestBody AuthenticationRequest authenticationRequest, HttpServletRequest request) {

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

    return session.getId();
}
项目:metaworks_framework    文件:BroadleafResourceHttpRequestHandler.java   
protected SecurityContext readSecurityContextFromSession(HttpSession httpSession) {
    if (httpSession == null) {
        return null;
    }

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

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

    return (SecurityContext) ctxFromSession;
}
项目:hawkbit    文件:SpringSecurityAtmosphereInterceptor.java   
@Override
public Action inspect(final AtmosphereResource r) {
    final SecurityContext context = (SecurityContext) r.getRequest().getSession()
            .getAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY);
    SecurityContextHolder.setContext(context);
    return Action.CONTINUE;
}
项目:hawkbit    文件:SpringSecurityAtmosphereInterceptorTest.java   
@Test
public void inspectRetrievesSetsSecurityContextFromRequestToThreadLocal() {

    when(atmosphereResourceMock.getRequest()).thenReturn(atmosphereRequestMock);
    when(atmosphereRequestMock.getSession()).thenReturn(httpSessionMock);
    when(httpSessionMock.getAttribute(Mockito.eq(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY)))
            .thenReturn(sessionSecurityContextMock);
    underTest.inspect(atmosphereResourceMock);
    // verify
    assertThat(SecurityContextHolder.getContext()).isEqualTo(sessionSecurityContextMock);
}
项目:webanno    文件:SpringAuthenticatedWebSession.java   
@Override
public boolean authenticate(String username, String password)
{
    // If already signed in (in Spring Security), then sign out there first
    // signOut();

    try {
        Authentication authentication = authenticationManager
                .authenticate(new UsernamePasswordAuthenticationToken(username, password));

        MDC.put(Logging.KEY_USERNAME, username);

        SecurityContextHolder.getContext().setAuthentication(authentication);
        log.debug("Stored authentication for user [{}] in security context",
                authentication.getName());

        HttpSession session = ((ServletWebRequest) RequestCycle.get().getRequest())
                .getContainerRequest().getSession();
        session.setAttribute(
                HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY,
                SecurityContextHolder.getContext());
        log.debug("Stored security context in session");

        return true;
    }
    catch (AuthenticationException e) {
        log.warn("User [{}] failed to login. Reason: {}", username, e.getMessage());
        return false;
    }
}
项目:AgileAlligators    文件:FredSpringWebTest.java   
public MockHttpSession getSession( String... authorities )
{
    SecurityContextHolder.getContext().setAuthentication( getPrincipal( authorities ) );
    MockHttpSession session = new MockHttpSession();

    session.setAttribute(
        HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY,
        SecurityContextHolder.getContext() );

    return session;
}
项目:egd-web    文件:WebappTestEnvironment.java   
protected void setSession(String username) throws Exception {
    principal = getPrincipal(username);

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

    UserDetails user = userDetailsService.loadUserByUsername(username);
    Authentication newAuth = new UsernamePasswordAuthenticationToken(user, username, user.getAuthorities());
    SecurityContextHolder.getContext().setAuthentication(newAuth);


    TestCase.assertTrue(SecurityUtils.isAuthenticated());
    TestCase.assertEquals(SecurityUtils.getUserUuid(), username);
    TestCase.assertTrue(SecurityUtils.isUserInRole(AuthoritiesConstants.ADMIN));


    /*
    MvcResult mvcresult = mockMvc
        .perform(
            get("/oauth/token")
                .principal(principal)).andDo(print())
        .andExpect(status().isOk()).andReturn();
    MockHttpServletRequest mockhttp = mvcresult.getRequest();
    System.out.println(mockhttp.toString());
    //*/
}
项目:eHMP    文件:UserTimeoutIntegrationSessionAttributeListenerTest.java   
@Test
public void testAttributeAddedForXUProgOnly() throws Exception {
    reset(mockUser);
    when(mockUser.hasVistaKey("XUPROG")).thenReturn(true);
    when(mockEnvironment.getProperty("session.timeoutSec", Integer.class)).thenReturn(6000);
    listener.attributeAdded(new HttpSessionBindingEvent(mockSession, HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY, mockSecurityContext));
    // XU PROG users should get something else
    assertThat(mockSession.getMaxInactiveInterval(), is(86400));
}
项目:members_cuacfm    文件:WebSecurityConfigurationAware.java   
/**
 * Gets the default session.
 *
 * @param nickName
 *            the nick name
 * @return the default session
 */
protected MockHttpSession getDefaultSession(String nickName) {
    UsernamePasswordAuthenticationToken principal = this
            .getPrincipal(nickName);
    SecurityContextHolder.getContext().setAuthentication(principal);

    MockHttpSession session = new MockHttpSession();
    session.setAttribute(
            HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY,
            SecurityContextHolder.getContext());
    return session;
}
项目:spring-session    文件:SpringSessionRememberMeServicesTests.java   
@Test
public void loginFailRemoveSecurityContext() {
    HttpServletRequest request = mock(HttpServletRequest.class);
    HttpServletResponse response = mock(HttpServletResponse.class);
    HttpSession session = mock(HttpSession.class);
    given(request.getSession(eq(false))).willReturn(session);
    this.rememberMeServices = new SpringSessionRememberMeServices();
    this.rememberMeServices.loginFail(request, response);
    verify(request, times(1)).getSession(eq(false));
    verify(session, times(1)).removeAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY);
    verifyZeroInteractions(request, response, session);
}
项目:adjule    文件:TestUtils.java   
public static MockHttpSession getAdminSession() {
    Authentication authentication =
            new UsernamePasswordAuthenticationToken("admin", "password");
    SecurityContext securityContext = SecurityContextHolder.getContext();
    securityContext.setAuthentication(authentication);

    MockHttpSession session = new MockHttpSession();
    session.setAttribute(
            HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY,
            securityContext);
    return session;
}
项目:glassmaker    文件:OAuth2AuthenticationFilter.java   
@Override
 public void doFilter(ServletRequest request, ServletResponse response,
         FilterChain chain) throws IOException, ServletException {

    if(request.getParameter("code") != null ) {
AuthorizationCodeFlow flow = oAuth2Util.newAuthorizationCodeFlow();
TokenResponse tokenResponse = oAuth2Util.newTokenRequest(flow,request.getParameter("code")).execute();

// Extract the Google User ID from the ID token in the auth
// response
//String userId = ((GoogleTokenResponse) tokenResponse).parseIdToken().getPayload().getUserId();
String subject = ((GoogleTokenResponse) tokenResponse).parseIdToken().getPayload().getSubject();
//String email = (String) ((GoogleTokenResponse) tokenResponse).parseIdToken().getPayload().get("email");

logger.info("Code exchange worked. User " + subject + " logged in.");
flow.createAndStoreCredential(tokenResponse, subject);


Authentication auth = new UsernamePasswordAuthenticationToken(subject, tokenResponse.getAccessToken(), (Collection<? extends GrantedAuthority>) new ArrayList<GrantedAuthority>());
authManager.authenticate(auth);
SecurityContextHolder.getContext().setAuthentication(authManager.authenticate(auth)); 
((HttpServletRequest)request).getSession().setAttribute(
        HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY,
        SecurityContextHolder.getContext());

if(auth != null){
    onAuthenticationSuccess((HttpServletRequest)request,(HttpServletResponse)response,auth);
}

     }
    chain.doFilter(request, response);

 }
项目:brainbox    文件:HomeController.java   
private void login(HttpServletRequest request, String name, String password) {
    Authentication req = new UsernamePasswordAuthenticationToken(name,
            password);
    Authentication res = this.authenticationManager.authenticate(req);
    SecurityContextHolder.getContext().setAuthentication(res);
    request.getSession()
            .setAttribute(
                    HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY,
                    SecurityContextHolder.getContext());
}
项目:carewebframework-core    文件:AbstractSecurityService.java   
/**
 * Returns the security context from the execution context.
 *
 * @return The security context, or null if one cannot be determined.
 */
public static SecurityContext getSecurityContext() {
    Session session = ExecutionContext.getSession();
    @SuppressWarnings("resource")
    WebSocketSession ws = session == null ? null : session.getSocket();
    return ws == null ? null
            : (SecurityContext) ws.getAttributes().get(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY);
}