org.springframework.security.web.context.HttpSessionSecurityContextRepository Java Examples
The following examples show how to use
org.springframework.security.web.context.HttpSessionSecurityContextRepository.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: SpringLdapController.java From Spring-5.0-Projects with MIT License | 6 votes |
@PostMapping("/ldapLogin") public String ldapAuthenticate(HttpServletRequest req,@RequestParam(value = "username",required = true) String username, @RequestParam(value = "password", required = true) String password,RedirectAttributes redirectAttributes) { UsernamePasswordAuthenticationToken authReq = new UsernamePasswordAuthenticationToken(username, password); Authentication auth = customLdapAuthProvider.authenticate(authReq); if(auth !=null) { logger.info(" If user is authenticated .... "+auth.isAuthenticated()); SecurityContext sc = SecurityContextHolder.getContext(); sc.setAuthentication(auth); HttpSession session = req.getSession(true); session.setAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY, sc); if(auth.isAuthenticated() == true) { return "redirect:/privatePage"; }else { redirectAttributes.addAttribute("error", "true"); return "redirect:/login"; } }else { // failed authentication - either username or password fails. redirectAttributes.addAttribute("error", "true"); return "redirect:/login"; } }
Example #2
Source File: SpringAuthManager.java From jdal with Apache License 2.0 | 6 votes |
@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; } }
Example #3
Source File: LoginController.java From spring-cloud-dashboard with Apache License 2.0 | 6 votes |
@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(); }
Example #4
Source File: AuthenticationController.java From botanic-ng with Apache License 2.0 | 6 votes |
@RequestMapping(value = "/api/authenticate", method = { RequestMethod.POST }) public AuthenticationToken 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()); final UserDetails details = this.userDetailsService.loadUserByUsername(authenticationRequest.getUsername()); final List<String> roles = new ArrayList<>(); for (GrantedAuthority authority : details.getAuthorities()) { roles.add(authority.toString()); } return new AuthenticationToken(details.getUsername(), roles); }
Example #5
Source File: CommonTestSupport.java From spring-boot-security-saml-sample with Apache License 2.0 | 6 votes |
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; }
Example #6
Source File: CommonTestSupport.java From spring-boot-security-saml-sample with Apache License 2.0 | 6 votes |
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; }
Example #7
Source File: DelayedEventBusPushStrategy.java From hawkbit with Eclipse Public License 1.0 | 6 votes |
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); Thread.currentThread().interrupt(); } finally { SecurityContextHolder.setContext(oldContext); } }
Example #8
Source File: UserDetailsFormatter.java From hawkbit with Eclipse Public License 1.0 | 6 votes |
public static UserDetails getCurrentUser() { final SecurityContext context = (SecurityContext) VaadinService.getCurrentRequest().getWrappedSession() .getAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY); Authentication authentication = context.getAuthentication(); if (authentication instanceof OAuth2AuthenticationToken) { OidcUser oidcUser = (OidcUser) authentication.getPrincipal(); Object details = authentication.getDetails(); String tenant = "DEFAULT"; if (details instanceof TenantAwareAuthenticationDetails) { tenant = ((TenantAwareAuthenticationDetails) details).getTenant(); } return new UserPrincipal(oidcUser.getPreferredUsername(), "***", oidcUser.getGivenName(), oidcUser.getFamilyName(), oidcUser.getPreferredUsername(), oidcUser.getEmail(), tenant, oidcUser.getAuthorities()); } else { return (UserDetails) authentication.getPrincipal(); } }
Example #9
Source File: VaadinUtils.java From jdal with Apache License 2.0 | 5 votes |
/** * Exit application */ public static void exit() { VaadinSession.getCurrent().getSession().removeAttribute( HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY); UI.getCurrent().close(); VaadinSession.getCurrent().close(); Page page = Page.getCurrent(); page.setLocation(VaadinService.getCurrentRequest().getContextPath() + "/logout"); }
Example #10
Source File: ManualTests.java From Spring with Apache License 2.0 | 5 votes |
@Test public void indexWhenSetSessionThenUnauthorized() throws Exception { SecurityContext context = SecurityContextHolder.createEmptyContext(); context.setAuthentication(this.authentication); this.request.getSession().setAttribute( HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY, context); this.springSecurityFilterChain.doFilter(this.request, this.response, this.chain); assertThat(this.response.getStatus()).isEqualTo(HttpServletResponse.SC_OK); }
Example #11
Source File: LoginFieldsSimpleIntegrationTest.java From tutorials with MIT License | 5 votes |
@Test public void givenAccessSecuredResource_whenAuthenticated_thenAuthHasExtraFields() throws Exception { MockHttpServletRequestBuilder securedResourceAccess = get("/user/index"); MvcResult unauthenticatedResult = mockMvc.perform(securedResourceAccess) .andExpect(status().is3xxRedirection()) .andReturn(); MockHttpSession session = (MockHttpSession) unauthenticatedResult.getRequest() .getSession(); String loginUrl = unauthenticatedResult.getResponse() .getRedirectedUrl(); User user = getUser(); mockMvc.perform(post(loginUrl) .param("username", user.getUsername()) .param("password", user.getPassword()) .param("domain", user.getDomain()) .session(session) .with(csrf())) .andExpect(status().is3xxRedirection()) .andExpect(redirectedUrlPattern("**/user/index")) .andReturn(); mockMvc.perform(securedResourceAccess.session(session)) .andExpect(status().isOk()); SecurityContext securityContext = (SecurityContext) session.getAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY); Authentication auth = securityContext.getAuthentication(); assertEquals(((User)auth.getPrincipal()).getDomain(), user.getDomain()); }
Example #12
Source File: LoginFieldsFullIntegrationTest.java From tutorials with MIT License | 5 votes |
@Test public void givenAccessSecuredResource_whenAuthenticated_thenAuthHasExtraFields() throws Exception { MockHttpServletRequestBuilder securedResourceAccess = get("/user/index"); MvcResult unauthenticatedResult = mockMvc.perform(securedResourceAccess) .andExpect(status().is3xxRedirection()) .andReturn(); MockHttpSession session = (MockHttpSession) unauthenticatedResult.getRequest() .getSession(); String loginUrl = unauthenticatedResult.getResponse() .getRedirectedUrl(); User user = getUser(); mockMvc.perform(post(loginUrl) .param("username", user.getUsername()) .param("password", user.getPassword()) .param("domain", user.getDomain()) .session(session) .with(csrf())) .andExpect(status().is3xxRedirection()) .andExpect(redirectedUrlPattern("**/user/index")) .andReturn(); mockMvc.perform(securedResourceAccess.session(session)) .andExpect(status().isOk()); SecurityContext securityContext = (SecurityContext) session.getAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY); Authentication auth = securityContext.getAuthentication(); assertEquals(((User)auth.getPrincipal()).getDomain(), user.getDomain()); }
Example #13
Source File: SpringSessionRememberMeServicesTests.java From spring-session with Apache License 2.0 | 5 votes |
@Test 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); }
Example #14
Source File: SpringSessionRememberMeServices.java From spring-session with Apache License 2.0 | 5 votes |
private void logout(HttpServletRequest request) { logger.debug("Interactive login attempt was unsuccessful."); HttpSession session = request.getSession(false); if (session != null) { session.removeAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY); } }
Example #15
Source File: SpringAuthenticatedWebSession.java From webanno with Apache License 2.0 | 5 votes |
@Override public boolean authenticate(String username, String password) { // If already signed in (in Spring Security), then sign out there first // signOut(); try { // Kill current session and create a new one as part of the authentication ((ServletWebRequest) RequestCycle.get().getRequest()).getContainerRequest().getSession() .invalidate(); 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; } }
Example #16
Source File: SpringSecurityAtmosphereInterceptorTest.java From hawkbit with Eclipse Public License 1.0 | 5 votes |
@Test @Description("Verify that Security Context is set from Request to thread local when calling inspect") 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); }
Example #17
Source File: SpringSecurityAtmosphereInterceptor.java From hawkbit with Eclipse Public License 1.0 | 5 votes |
@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; }
Example #18
Source File: WebSecurityConfig.java From spring-boot-security-saml-samples with MIT License | 5 votes |
/** * 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(); }
Example #19
Source File: DhisWebSpringTest.java From dhis2-core with BSD 3-Clause "New" or "Revised" License | 5 votes |
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; }
Example #20
Source File: AuthenticationController.java From spring-microservice-sample with GNU General Public License v3.0 | 5 votes |
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(GrantedAuthority::getAuthority) .collect(Collectors.toList()) ) .token(session.getId()) .build(); }
Example #21
Source File: SecurityConfig.java From Spring with Apache License 2.0 | 5 votes |
@Bean public SecurityContextPersistenceFilter securityContextPersistenceFilter() { final HttpSessionSecurityContextRepository sCRepo = new HttpSessionSecurityContextRepository(); sCRepo.setAllowSessionCreation(true); //by default true return new SecurityContextPersistenceFilter(sCRepo); }
Example #22
Source File: SecurityTestUtils.java From onetwo with Apache License 2.0 | 4 votes |
public static SecurityContext getSecurityContext(MvcResult result){ SecurityContext securityContext = (SecurityContext)result.getRequest().getSession().getAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY); return securityContext; }
Example #23
Source File: SessionsTag.java From unitime with Apache License 2.0 | 4 votes |
/** * Default method to handle start of tag. */ public int doStartTag() throws JspException { // Check Access UserContext user = getUser(); if (user == null || user.getCurrentAuthority() == null || !user.getCurrentAuthority().hasRight(Right.IsAdmin)) throw new PageAccessException("Access Denied."); StringBuffer html = new StringBuffer(""); Formats.Format<Date> sdf = Formats.getDateFormat(Formats.Pattern.DATE_TIME_STAMP); try { html.append("<TABLE border='0' cellspacing='1' cellpadding='2' width='100%'>"); html.append("<TR>"); html.append("<TD align='center'>User</TD>"); html.append("<TD align='center'>Created</TD>"); html.append("<TD align='center'>Last Access</TD>"); html.append("</TR>"); HashMap s = SessionListener.getSessions(); Set keys = s.keySet(); Iterator i = keys.iterator(); while (i.hasNext()) { String sessionId = i.next().toString(); HttpSession session = (HttpSession) s.get(sessionId); if (session!=null) { session.getAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY); UserContext u = getUser((SecurityContext)session.getAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY)); String userDetail = "Cannot be determined"; if (u != null && u.getUsername() != null) userDetail = u.getUsername() + (u.getCurrentAuthority() == null ? "" : " ("+ u.getCurrentAuthority() + ")"); html.append("<TR>"); html.append("<TD align='left'>" + userDetail + "</TD>"); html.append("<TD align='left'>" + sdf.format(new Date(session.getCreationTime())) + "</TD>"); html.append("<TD align='left'>" + sdf.format(new Date(session.getLastAccessedTime())) + "</TD>"); html.append("</TR>"); } } html.append("</TABLE>"); pageContext.getOut().print(html.toString()); } catch (Exception ex) { throw new JspTagException("SessionsTag: " + ex.getMessage()); } return SKIP_BODY; }
Example #24
Source File: ResourceServerConfig.java From spring-cloud-event-sourcing-example with GNU General Public License v3.0 | 4 votes |
@Bean HttpSessionSecurityContextRepository contextRepository() { return new HttpSessionSecurityContextRepository(); }
Example #25
Source File: LoginService.java From vics with MIT License | 4 votes |
private void persistUserSession(HttpSession session, Authentication authentication) { SecurityContextHolder.getContext().setAuthentication(authentication); session.setAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY, SecurityContextHolder.getContext()); }
Example #26
Source File: ResourceServerConfig.java From cloud-native-microservice-strangler-example with GNU General Public License v3.0 | 4 votes |
@Bean HttpSessionSecurityContextRepository contextRepository() { return new HttpSessionSecurityContextRepository(); }
Example #27
Source File: MolgenisWebAppSecurityConfig.java From molgenis with GNU Lesser General Public License v3.0 | 4 votes |
@Bean public SecurityContextRepository securityContextRepository() { return new TokenAwareSecurityContextRepository( new NullSecurityContextRepository(), new HttpSessionSecurityContextRepository()); }
Example #28
Source File: SessionConfig.java From Spring-Security-Third-Edition with MIT License | 4 votes |
@Bean public SecurityContextRepository securityContextRepository(){ return new HttpSessionSecurityContextRepository(); }
Example #29
Source File: ResourceServerConfig.java From microservices-event-sourcing with Apache License 2.0 | 4 votes |
@Bean public HttpSessionSecurityContextRepository contextRepository() { return new HttpSessionSecurityContextRepository(); }