/** * @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; }
/** * 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); } }
/** * @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; }
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(); } } }
@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(); }
@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); }
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; }
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); } }
@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"); } }
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; }
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; }
@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()); }
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; }
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; }
@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; }
/** * 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; }
@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; } }
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(); }
/** * 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; }
/** * 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(); }
/** * 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; }
/** * 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); }
/** * 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(); } } }
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; }
/** * 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(); }
@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(); }
@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; }
@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); }
@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; } }
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()); //*/ }
@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)); }
/** * 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; }
@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); }
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; }
@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); }
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()); }
/** * 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); }