List of usage examples for org.springframework.security.core.context SecurityContextHolder createEmptyContext
public static SecurityContext createEmptyContext()
From source file:net.cristcost.study.services.ServiceTestUtil.java
private static SecurityContext authenticate(PrintWriter writer, HttpServletRequest request, AuthenticationManager authenticationManager) { SecurityContext initialContext = SecurityContextHolder.getContext(); if (request.getParameter("user") != null) { UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken( request.getParameter("user"), request.getParameter("pass")); try {/*from w w w. ja v a 2 s.co m*/ Authentication authentication = authenticationManager.authenticate(authRequest); SecurityContextHolder.setContext(SecurityContextHolder.createEmptyContext()); SecurityContextHolder.getContext().setAuthentication(authentication); writer.println("Authenticating user: " + request.getParameter("user")); } catch (AuthenticationException e) { writer.println("! Error while Authenticating: " + e.getMessage()); } writer.println(); } return initialContext; }
From source file:com.mastercard.test.spring.security.LogPrincipalRuleTests.java
@Test public void ruleDoesNotBreakWhenAuthenticationIsNotProvided() throws Throwable { DefaultStatement statement = new DefaultStatement(); Description description = Description.createTestDescription(MockWithMockUserTest.class.getName(), "test"); LogPrincipalRule rule = new LogPrincipalRule(); Statement actual = rule.apply(statement, description); SecurityContextHolder.setContext(SecurityContextHolder.createEmptyContext()); actual.evaluate();/*from ww w. j a va 2s.c om*/ assertNotSame(statement, actual); assertTrue(statement.isEvaluated()); }
From source file:com.mastercard.test.spring.security.WithUserDetailsSecurityContextFactory.java
public SecurityContext createSecurityContext(WithUserDetails withUser) { String beanName = withUser.userDetailsServiceBeanName(); UserDetailsService userDetailsService = StringUtils.hasLength(beanName) ? this.beans.getBean(beanName, UserDetailsService.class) : this.beans.getBean(UserDetailsService.class); String username = withUser.value(); Assert.hasLength(username, "value() must be non empty String"); UserDetails principal = userDetailsService.loadUserByUsername(username); Authentication authentication = new UsernamePasswordAuthenticationToken(principal, principal.getPassword(), principal.getAuthorities()); SecurityContext context = SecurityContextHolder.createEmptyContext(); context.setAuthentication(authentication); return context; }
From source file:org.ng200.openolympus.TestUtilities.java
public void logInAsAdmin() { final SecurityContext context = SecurityContextHolder.createEmptyContext(); final User principal = this.userService.getUserByUsername("admin"); final Authentication auth = new UsernamePasswordAuthenticationToken(principal, "admin", principal.getAuthorities()); context.setAuthentication(auth);/*from w w w. j a v a 2s .c o m*/ SecurityContextHolder.setContext(context); }
From source file:com.ixortalk.aws.cognito.boot.mock.WithMockJwtUserSecurityContextFactory.java
@Override public SecurityContext createSecurityContext(WithMockJwtUser mockJwtUser) { String username = mockJwtUser.username(); if (username == null) { throw new IllegalArgumentException( mockJwtUser + " cannot have null username on both username and value properites"); }/* www .j a va 2 s . c o m*/ List<GrantedAuthority> grantedAuthorities = new ArrayList<GrantedAuthority>(); for (String role : mockJwtUser.roles()) { if (role.startsWith("ROLE_")) { throw new IllegalArgumentException("roles cannot start with ROLE_ Got " + role); } grantedAuthorities.add(new SimpleGrantedAuthority("ROLE_" + role)); } JWTClaimsSet.Builder builder = new JWTClaimsSet.Builder(); for (MockJwtClaim mockJwtClaim : mockJwtUser.mockJwtClaims()) { builder.claim(mockJwtClaim.key(), mockJwtClaim.value()); } JWTClaimsSet jwtClaimsSet = builder.build(); User principal = new User(username, "", true, true, true, true, grantedAuthorities); JwtAuthentication jwtAuthentication = new JwtAuthentication(principal, jwtClaimsSet, grantedAuthorities); SecurityContext context = SecurityContextHolder.createEmptyContext(); context.setAuthentication(jwtAuthentication); return context; }
From source file:au.gov.dto.springframework.security.web.context.CookieSecurityContextRepository.java
/** * Obtains the security context for the supplied request. For an unauthenticated user, an empty context * implementation should be returned. This method should not return null. * <p>//from w ww. j a va2 s. c om * The use of the <tt>HttpRequestResponseHolder</tt> parameter allows implementations to return wrapped versions of * the request or response (or both), allowing them to access implementation-specific state for the request. * The values obtained from the holder will be passed on to the filter chain and also to the <tt>saveContext</tt> * method when it is finally called. Implementations may wish to return a subclass of * {@link SaveContextOnUpdateOrErrorResponseWrapper} as the response object, which guarantees that the context is * persisted when an error or redirect occurs. * * @param requestResponseHolder holder for the current request and response for which the context should be loaded. * * @return The security context which should be used for the current request, never null. */ @Override public SecurityContext loadContext(HttpRequestResponseHolder requestResponseHolder) { HttpServletRequest request = requestResponseHolder.getRequest(); HttpServletResponse response = requestResponseHolder.getResponse(); requestResponseHolder.setResponse(new SaveToCookieResponseWrapper(request, response)); Cookie authenticationCookie = getAuthenticationCookie(request); if (authenticationCookie == null) { return SecurityContextHolder.createEmptyContext(); } String serialisedAuthentication = tokenEncryption.decryptAndVerify(authenticationCookie.getValue()); if (serialisedAuthentication == null) { response.addCookie(createExpireAuthenticationCookie(request)); return SecurityContextHolder.createEmptyContext(); } Authentication authentication = authenticationSerializer.deserialize(serialisedAuthentication); SecurityContext securityContext = SecurityContextHolder.createEmptyContext(); securityContext.setAuthentication(authentication); return securityContext; }
From source file:fr.mycellar.interfaces.web.security.SecurityContextTokenRepository.java
@Override public SecurityContext loadContext(HttpRequestResponseHolder requestResponseHolder) { try {// ww w .j a va 2s .c om Object key = requestResponseHolder.getRequest() .getHeader(SpringSecurityConfiguration.TOKEN_HEADER_NAME); if ((key != null) && (key instanceof String)) { Token token = keyBasedPersistenceTokenService.verifyToken((String) key); if (token != null) { TimedSecurityContext context = securityContexts.get(token); if (context != null) { context.localDateTime = new LocalDateTime(); return context.securityContext; } } } } catch (Exception e) { // return SecurityContextHolder.createEmptyContext(); } return SecurityContextHolder.createEmptyContext(); }
From source file:com.mastercard.test.spring.security.WithMockUserSecurityContextFactory.java
public SecurityContext createSecurityContext(WithMockUser withUser) { String username = StringUtils.hasLength(withUser.username()) ? withUser.username() : withUser.value(); if (username == null) { throw new IllegalArgumentException( withUser + " cannot have null username on both username and value properites"); }/*from w ww . j a va 2s . c o m*/ List<GrantedAuthority> grantedAuthorities = new ArrayList<GrantedAuthority>(); for (String authority : withUser.authorities()) { grantedAuthorities.add(new SimpleGrantedAuthority(authority)); } if (grantedAuthorities.isEmpty()) { for (String role : withUser.roles()) { if (role.startsWith("ROLE_")) { throw new IllegalArgumentException("roles cannot start with ROLE_ Got " + role); } grantedAuthorities.add(new SimpleGrantedAuthority("ROLE_" + role)); } } else if (!(withUser.roles().length == 1 && "USER".equals(withUser.roles()[0]))) { throw new IllegalStateException("You cannot define roles attribute " + Arrays.asList(withUser.roles()) + " with authorities attribute " + Arrays.asList(withUser.authorities())); } User principal = new User(username, withUser.password(), true, true, true, true, grantedAuthorities); Authentication authentication = new UsernamePasswordAuthenticationToken(principal, principal.getPassword(), principal.getAuthorities()); SecurityContext context = SecurityContextHolder.createEmptyContext(); context.setAuthentication(authentication); return context; }
From source file:org.openinfinity.sso.security.spring.InjectableSecurityContextFilterBean.java
private void injectIdentityBasedSecurityContext(String sessionId) { SecurityContext securityContext = SecurityContextHolder.createEmptyContext(); SecurityContextHolder.setContext(securityContext); Authentication authentication = IdentityContext.loadIdentity(sessionId); SecurityContextHolder.getContext().setAuthentication(authentication); LOGGER.info("SecurityContext created for active session based on IdentityContext for user: " + authentication.getName()); }
From source file:org.vaadin.spring.security.internal.VaadinSharedSecurity.java
@Override public Authentication login(Authentication authentication, boolean rememberMe) throws Exception { SecurityContext context = SecurityContextHolder.getContext(); final HttpServletRequest request = httpRequestResponseHolder.getCurrentRequest(); if (request == null) { throw new IllegalStateException("No HttpServletRequest bound to current thread"); }/*from w w w . ja v a 2 s .c o m*/ final HttpServletResponse response = httpRequestResponseHolder.getCurrentResponse(); if (response == null) { throw new IllegalStateException("No HttpServletResponse bound to current thread"); } try { logger.debug("Attempting authentication of {}, rememberMe = {}", authentication, rememberMe); final Authentication fullyAuthenticated = getAuthenticationManager().authenticate(authentication); context.setAuthentication(fullyAuthenticated); if (rememberMe) { if (hasRememberMeServices()) { logger.debug("Invoking RememberMeServices"); getRememberMeServices().loginSuccess(request, response, authentication); } else { throw new IllegalStateException( "Requested RememberMe authentication but no RememberBeServices are available"); } } logger.debug("Invoking session authentication strategy"); sessionAuthenticationStrategy.onAuthentication(fullyAuthenticated, request, response); logger.debug("Invoking authentication success handler"); vaadinAuthenticationSuccessHandler.onAuthenticationSuccess(fullyAuthenticated); return authentication; } catch (AuthenticationException e) { logger.debug("Authentication failed"); context = SecurityContextHolder.createEmptyContext(); if (hasRememberMeServices()) { logger.debug("Invoking RememberMeServices"); getRememberMeServices().loginFail(request, response); } throw e; } finally { if (saveContextInSessionAfterLogin) { logger.debug("Saving security context in the session"); WrappedSession session = getSession(); if (session != null) { session.setAttribute(springSecurityContextKey, context); } else { logger.warn( "Tried to save security context in the session, but no session was bound to the current thread"); } } } }