org.springframework.security.core.context.SecurityContextImpl Java Examples
The following examples show how to use
org.springframework.security.core.context.SecurityContextImpl.
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: AuthenticationWebFilter.java From spring-security-reactive with Apache License 2.0 | 6 votes |
@Override public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) { return authenticationConverter.convert(exchange) .flatMap( token -> { return authenticationManager.authenticate(token) .flatMap(authentication -> { SecurityContext context = new SecurityContextImpl(); context.setAuthentication(authentication); return securityContextRepository .save(exchange, context) .flatMap( value ->{ return chain.filter(exchange); }); }) .onErrorResume( AuthenticationException.class, t -> { return entryPoint.commence(exchange, t); }); }) .switchIfEmpty(Mono.defer(() -> { return chain.filter(exchange); })); }
Example #2
Source File: PageListControllerTest.java From Asqatasun with GNU Affero General Public License v3.0 | 6 votes |
/** * */ private void setUpMockAuthenticationContext(){ // initialise the context with the user identified by the email // "[email protected]" seen as authenticated Collection<GrantedAuthority> gac = new ArrayList(); TgolUserDetails tud = new TgolUserDetails("[email protected]", "", true, false, true, true, gac, mockUser); mockAuthentication = createMock(Authentication.class); SecurityContextImpl securityContextImpl = new SecurityContextImpl(); securityContextImpl.setAuthentication(mockAuthentication); SecurityContextHolder.setContext(securityContextImpl); expect(mockAuthentication.getName()).andReturn("[email protected]").anyTimes(); expect(mockAuthentication.getPrincipal()).andReturn(tud).anyTimes(); expect(mockAuthentication.getAuthorities()).andReturn(null).anyTimes(); replay(mockAuthentication); mockAuthenticationDetails = createMock(AuthenticationDetails.class); expect(mockAuthenticationDetails.getContext()).andReturn("[email protected]").anyTimes(); replay(mockAuthenticationDetails); }
Example #3
Source File: UserManagementControllerTest.java From Asqatasun with GNU Affero General Public License v3.0 | 6 votes |
private void setUpMockAuthenticationContext(){ // initialise the context with the user identified by the email // "[email protected]" seen as authenticated Collection<GrantedAuthority> gac = new ArrayList<GrantedAuthority>(); TgolUserDetails tud = new TgolUserDetails("[email protected]", "", true, false, true, true, gac, mockAdminUser); mockAuthentication = createMock(Authentication.class); SecurityContextImpl securityContextImpl = new SecurityContextImpl(); securityContextImpl.setAuthentication(mockAuthentication); SecurityContextHolder.setContext(securityContextImpl); expect(mockAuthentication.getName()).andReturn("[email protected]").anyTimes(); expect(mockAuthentication.getPrincipal()).andReturn(tud).anyTimes(); expect(mockAuthentication.getAuthorities()).andReturn(null).anyTimes(); replay(mockAuthentication); }
Example #4
Source File: ContractControllerTest.java From Asqatasun with GNU Affero General Public License v3.0 | 6 votes |
private void setUpMockAuthenticationContext(){ // initialise the context with the user identified by the email // "[email protected]" seen as authenticated Collection<GrantedAuthority> gac = new ArrayList(); TgolUserDetails tud = new TgolUserDetails("[email protected]", "", true, false, true, true, gac, mockUser); mockAuthentication = createMock(Authentication.class); SecurityContextImpl securityContextImpl = new SecurityContextImpl(); securityContextImpl.setAuthentication(mockAuthentication); SecurityContextHolder.setContext(securityContextImpl); expect(mockAuthentication.getName()).andReturn("[email protected]").anyTimes(); expect(mockAuthentication.getPrincipal()).andReturn(tud).anyTimes(); expect(mockAuthentication.getAuthorities()).andReturn(null).anyTimes(); replay(mockAuthentication); mockAuthenticationDetails = createMock(AuthenticationDetails.class); expect(mockAuthenticationDetails.getContext()).andReturn("[email protected]").anyTimes(); replay(mockAuthenticationDetails); }
Example #5
Source File: HomeControllerTest.java From Asqatasun with GNU Affero General Public License v3.0 | 6 votes |
private void setUpMockAuthenticationContext(){ // initialise the context with the user identified by the email // "[email protected]" seen as authenticated Collection<GrantedAuthority> gac = new ArrayList<GrantedAuthority>(); TgolUserDetails tud = new TgolUserDetails("[email protected]", "", true, false, true, true, gac, mockUser); mockAuthentication = createMock(Authentication.class); SecurityContextImpl securityContextImpl = new SecurityContextImpl(); securityContextImpl.setAuthentication(mockAuthentication); SecurityContextHolder.setContext(securityContextImpl); expect(mockAuthentication.getName()).andReturn("[email protected]").anyTimes(); expect(mockAuthentication.getPrincipal()).andReturn(tud).anyTimes(); expect(mockAuthentication.getAuthorities()).andReturn(null).anyTimes(); replay(mockAuthentication); mockAuthenticationDetails = createMock(AuthenticationDetails.class); expect(mockAuthenticationDetails.getContext()).andReturn("[email protected]").anyTimes(); replay(mockAuthenticationDetails); }
Example #6
Source File: AuditSetUpControllerTest.java From Asqatasun with GNU Affero General Public License v3.0 | 6 votes |
private void setUpMockAuthenticationContext(){ // initialise the context with the user identified by the email // "[email protected]" seen as authenticated Collection<GrantedAuthority> gac = new ArrayList<GrantedAuthority>(); TgolUserDetails tud = new TgolUserDetails("[email protected]", "", true, false, true, true, gac, mockUser); mockAuthentication = createMock(Authentication.class); SecurityContextImpl securityContextImpl = new SecurityContextImpl(); securityContextImpl.setAuthentication(mockAuthentication); SecurityContextHolder.setContext(securityContextImpl); expect(mockAuthentication.getName()).andReturn("[email protected]").anyTimes(); expect(mockAuthentication.getPrincipal()).andReturn(tud).anyTimes(); expect(mockAuthentication.getAuthorities()).andReturn(null).anyTimes(); replay(mockAuthentication); mockAuthenticationDetails = createMock(AuthenticationDetails.class); expect(mockAuthenticationDetails.getContext()).andReturn("[email protected]").anyTimes(); replay(mockAuthenticationDetails); }
Example #7
Source File: PinpointWebSocketTimerTaskDecoratorTest.java From pinpoint with Apache License 2.0 | 6 votes |
@Test public void testAuthenticationPropagation() throws InterruptedException { final int numThreads = 3; final Authentication[] authentications = new Authentication[numThreads]; for (int i = 0; i < authentications.length; i++) { final String principal = "principal" + i; final String credential = "credential" + i; authentications[i] = new TestingAuthenticationToken(principal, credential); } final CountDownLatch schedulerLatch = new CountDownLatch(numThreads); final Timer timer = new Timer(); for (Authentication authentication : authentications) { new Thread(new Runnable() { @Override public void run() { SecurityContext securityContext = new SecurityContextImpl(); securityContext.setAuthentication(authentication); SecurityContextHolder.setContext(securityContext); TimerTask timerTask = timerTaskDecoratorFactory.createTimerTaskDecorator().decorate(new TestTimerTask(schedulerLatch, authentication)); timer.schedule(timerTask, DELAY_MS); } }).start(); } Assert.assertTrue("Timed out waiting for timer task completion", schedulerLatch.await(2 * DELAY_MS, TimeUnit.MILLISECONDS)); }
Example #8
Source File: DefaultUserService.java From attic-rave with Apache License 2.0 | 6 votes |
private SecurityContext createContext(final User user) { SecurityContext securityContext = new SecurityContextImpl(); securityContext.setAuthentication(new AbstractAuthenticationToken(user.getAuthorities()) { private static final long serialVersionUID = 1L; @Override public Object getCredentials() { return "N/A"; } @Override public Object getPrincipal() { return user; } @Override public boolean isAuthenticated() { return true; } }); return securityContext; }
Example #9
Source File: QueryFilterTest.java From api-layer with Eclipse Public License 2.0 | 6 votes |
@Test public void shouldRejectIfNotAuthenticatedByCertficate() { httpServletRequest = new MockHttpServletRequest(); httpServletRequest.setMethod(HttpMethod.GET.name()); httpServletResponse = new MockHttpServletResponse(); TokenAuthentication authentication = new TokenAuthentication("token"); authentication.setAuthenticated(true); SecurityContextHolder.setContext(new SecurityContextImpl(authentication)); QueryFilter protectedQueryFilter = new QueryFilter("TEST_ENDPOINT", authenticationSuccessHandler, authenticationFailureHandler, authenticationService, HttpMethod.GET, true, authenticationManager); assertThrows(InvalidCertificateException.class, () -> protectedQueryFilter.attemptAuthentication(httpServletRequest, httpServletResponse), "Expected exception is not InvalidCertificateException"); }
Example #10
Source File: LDSecurityContextRepository.java From document-management-software with GNU Lesser General Public License v3.0 | 6 votes |
@Override public SecurityContext loadContext(HttpRequestResponseHolder request) { String sid = SessionManager.get().getSessionId(request.getRequest()); if (sid == null || !SessionManager.get().isOpen(sid)) sid = null; if (sid == null) return SecurityContextHolder.createEmptyContext(); Session session = SessionManager.get().get(sid); LDAuthenticationToken token = new LDAuthenticationToken(session.getUsername(), "", null); token.setSid(sid); SecurityContextImpl context = new SecurityContextImpl(); context.setAuthentication(token); HttpSession servletSession = request.getRequest().getSession(false); if (servletSession != null) servletSessionMapping.put(sid, servletSession); return context; }
Example #11
Source File: DefaultUserServiceTest.java From attic-rave with Apache License 2.0 | 6 votes |
@Test public void getAuthenticatedUser_validUser() { final User authUser = new UserImpl(USER_ID); AbstractAuthenticationToken auth = createNiceMock(AbstractAuthenticationToken.class); expect(auth.getPrincipal()).andReturn(authUser).anyTimes(); replay(auth); SecurityContext context = new SecurityContextImpl(); context.setAuthentication(auth); SecurityContextHolder.setContext(context); User result = service.getAuthenticatedUser(); assertThat(result, is(sameInstance(authUser))); verify(auth); }
Example #12
Source File: RenderServiceIntegrationTest.java From attic-rave with Apache License 2.0 | 6 votes |
@SuppressWarnings("unchecked") @Before public void setup() throws SQLException { restOperations = EasyMock.createNiceMock(RestOperations.class); EasyMock.expect(restOperations.postForObject(EasyMock.anyObject(String.class), EasyMock.anyObject(String.class), EasyMock.anyObject(Class.class))) .andReturn(VALID_METADATA); EasyMock.replay(restOperations); //Replace the real restOperations instance with a mock -- otherwise the call for gadget metadata would fail since //we don't have a shindig server available to hit. ReflectionTestUtils.setField(metadataRepository, "restOperations", restOperations); //Setup a mock authenticated user final User authUser = new UserImpl(VALID_USER_ID, VALID_USER_NAME); AbstractAuthenticationToken auth = EasyMock.createNiceMock(AbstractAuthenticationToken.class); EasyMock.expect(auth.getPrincipal()).andReturn(authUser).anyTimes(); EasyMock.replay(auth); SecurityContext context = new SecurityContextImpl(); context.setAuthentication(auth); SecurityContextHolder.setContext(context); }
Example #13
Source File: SimpleUserDetailsServiceImpl.java From nimrod with MIT License | 6 votes |
public static SimpleUser getCurrentSimpleUser(HttpServletRequest request) { SecurityContextImpl securityContextImpl = (SecurityContextImpl) request.getSession().getAttribute("SPRING_SECURITY_CONTEXT"); Authentication authentication; if (securityContextImpl != null) { authentication = securityContextImpl.getAuthentication(); } else { authentication = SecurityContextHolder.getContext().getAuthentication(); } if (authentication != null) { Object principal = authentication.getPrincipal(); if (principal instanceof UserDetails) { return (SimpleUser) principal; } } return null; }
Example #14
Source File: LoginTicketInterceptor.java From MyCommunity with Apache License 2.0 | 6 votes |
@Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { // loginTicket.getTicket() String ticket = CookieUtil.getValue(request, Const.ticket.TICKET); if (ticket != null) { // ticket:UUID LoginTicket loginTicket = userService.findLoginTicket(ticket); if (loginTicket != null && loginTicket.getStatus() == Const.loginStatus.VALID && loginTicket.getExpired().after(new Date())) { // 对 userId 加密,只分装必要的信息,密码不泄漏 UserVo userVo = userService.findUserById(XORUtil.encryptId(loginTicket.getUserId(), Const.getIdEncodeKeys.userIdKeys)); // 在本次请求中持有的用户 hostHolder.setUser(userVo); // 构建用户认证的结果,并存入SecurityContext,以便于Security进行授权. // authentication 认证结果 User user = userMapper.selectByPrimaryKey(XORUtil.encryptId(userVo.getId(), Const.getIdEncodeKeys.userIdKeys)); Authentication authentication = new UsernamePasswordAuthenticationToken( userVo.getId(), user.getPassword(), userService.getAuthorities(user.getId()) ); SecurityContextHolder.setContext(new SecurityContextImpl(authentication)); } } return true; }
Example #15
Source File: HeaderAuthenticationFilter.java From spring-rest-server with GNU Lesser General Public License v3.0 | 5 votes |
private SecurityContext createSecurityContext(UserDetails userDetails) { if (userDetails != null) { SecurityContextImpl securityContext = new SecurityContextImpl(); Authentication authentication = new UsernamePasswordAuthenticationToken(userDetails.getUsername(), userDetails.getPassword(), userDetails.getAuthorities()); securityContext.setAuthentication(authentication); return securityContext; } return SecurityContextHolder.createEmptyContext(); }
Example #16
Source File: DefaultUserServiceTest.java From attic-rave with Apache License 2.0 | 5 votes |
@Test(expected = SecurityException.class) public void getAuthenticatedUser_nullAuth() { SecurityContext context = new SecurityContextImpl(); SecurityContextHolder.setContext(context); service.getAuthenticatedUser(); }
Example #17
Source File: PrincipalNameIndexResolverTests.java From spring-session with Apache License 2.0 | 5 votes |
@Test void resolveFromSpringSecurityContext() { Authentication authentication = new UsernamePasswordAuthenticationToken(PRINCIPAL_NAME, "notused", AuthorityUtils.createAuthorityList("ROLE_USER")); SecurityContext context = new SecurityContextImpl(); context.setAuthentication(authentication); MapSession session = new MapSession(); session.setAttribute(SPRING_SECURITY_CONTEXT, context); assertThat(this.indexResolver.resolveIndexValueFor(session)).isEqualTo(PRINCIPAL_NAME); }
Example #18
Source File: SpringSessionBackedSessionRegistryTest.java From spring-session with Apache License 2.0 | 5 votes |
private Session createSession(String sessionId, String userName, Instant lastAccessed) { MapSession session = new MapSession(sessionId); session.setLastAccessedTime(lastAccessed); Authentication authentication = mock(Authentication.class); when(authentication.getName()).thenReturn(userName); SecurityContextImpl securityContext = new SecurityContextImpl(); securityContext.setAuthentication(authentication); session.setAttribute("SPRING_SECURITY_CONTEXT", securityContext); return session; }
Example #19
Source File: TokenRelayGatewayFilterFactoryTests.java From spring-cloud-security with Apache License 2.0 | 5 votes |
@Test public void principalIsNotOAuth2AuthenticationToken() { SecurityContextImpl securityContext = new SecurityContextImpl( new TestingAuthenticationToken("my", null)); SecurityContextServerWebExchange exchange = new SecurityContextServerWebExchange( mockExchange, Mono.just(securityContext)); filter.filter(exchange, filterChain).block(TIMEOUT); assertThat(request.getHeaders()).doesNotContainKeys(HttpHeaders.AUTHORIZATION); }
Example #20
Source File: TokenRelayGatewayFilterFactoryTests.java From spring-cloud-security with Apache License 2.0 | 5 votes |
@Test public void whenPrincipalExistsAuthorizationHeaderAdded() { OAuth2AccessToken accessToken = mock(OAuth2AccessToken.class); when(accessToken.getTokenValue()).thenReturn("mytoken"); ClientRegistration clientRegistration = ClientRegistration .withRegistrationId("myregistrationid") .authorizationGrantType(AuthorizationGrantType.CLIENT_CREDENTIALS) .clientId("myclientid").tokenUri("mytokenuri").build(); OAuth2AuthorizedClient authorizedClient = new OAuth2AuthorizedClient( clientRegistration, "joe", accessToken); when(repository.loadAuthorizedClient(anyString(), any(OAuth2AuthenticationToken.class), any(ServerWebExchange.class))) .thenReturn(Mono.just(authorizedClient)); OAuth2AuthenticationToken authenticationToken = new OAuth2AuthenticationToken( mock(OAuth2User.class), Collections.emptyList(), "myId"); SecurityContextImpl securityContext = new SecurityContextImpl( authenticationToken); SecurityContextServerWebExchange exchange = new SecurityContextServerWebExchange( mockExchange, Mono.just(securityContext)); filter.filter(exchange, filterChain).block(TIMEOUT); assertThat(request.getHeaders()).containsEntry(HttpHeaders.AUTHORIZATION, Collections.singletonList("Bearer mytoken")); }
Example #21
Source File: DefaultUserServiceTest.java From attic-rave with Apache License 2.0 | 5 votes |
@Test(expected = SecurityException.class) public void getAuthenticatedUser_wrongPrincipalType() { AbstractAuthenticationToken auth = createNiceMock(AbstractAuthenticationToken.class); expect(auth.getPrincipal()).andReturn(USER_ID).anyTimes(); replay(auth); SecurityContext context = new SecurityContextImpl(); SecurityContextHolder.setContext(context); service.getAuthenticatedUser(); verify(auth); }
Example #22
Source File: DefaultUserServiceTest.java From attic-rave with Apache License 2.0 | 5 votes |
@Test public void clearAuthentication() { SecurityContext context = new SecurityContextImpl(); SecurityContextHolder.setContext(context); service.clearAuthenticatedUser(); assertThat(SecurityContextHolder.getContext(), not(sameInstance(context))); }
Example #23
Source File: TicketAuthenticationClearingFilter.java From cosmo with Apache License 2.0 | 5 votes |
/** * Detects if a ticket is associated with * the current context and clears the context. * @param request The servlet request. * @param response The servlet response. * @param chain The filter chain. * @throws IOException - if something is wrong this exception is thrown. * @throws ServletException - if something is wrong this exception is thrown. */ public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { SecurityContext sc = SecurityContextHolder.getContext(); if (sc.getAuthentication()!=null && sc.getAuthentication() instanceof TicketAuthenticationToken) { if (LOG.isDebugEnabled()) { LOG.debug("found ticket authentication clearing..."); } SecurityContextHolder.setContext(new SecurityContextImpl()); } chain.doFilter(request, response); }
Example #24
Source File: LoginControllerTest.java From Asqatasun with GNU Affero General Public License v3.0 | 5 votes |
private void setUpMockAuthenticationContext(){ // initialise the context with the user identified by the email // "[email protected]" seen as authenticated mockAuthentication = createMock(Authentication.class); SecurityContextImpl securityContextImpl = new SecurityContextImpl(); securityContextImpl.setAuthentication(mockAuthentication); SecurityContextHolder.setContext(securityContextImpl); expect(mockAuthentication.isAuthenticated()).andReturn(Boolean.FALSE); replay(mockAuthentication); }
Example #25
Source File: SystemSecurityContext.java From hawkbit with Eclipse Public License 1.0 | 5 votes |
private void setCustomSecurityContext(final String tenantId, final Object principal, final Collection<? extends GrantedAuthority> authorities) { final AnonymousAuthenticationToken authenticationToken = new AnonymousAuthenticationToken( UUID.randomUUID().toString(), principal, authorities); authenticationToken.setDetails(new TenantAwareAuthenticationDetails(tenantId, true)); final SecurityContextImpl securityContextImpl = new SecurityContextImpl(); securityContextImpl.setAuthentication(authenticationToken); SecurityContextHolder.setContext(securityContextImpl); }
Example #26
Source File: CurrentUserResourceTest.java From gravitee-management-rest-api with Apache License 2.0 | 5 votes |
private void setCurrentUserDetails(final UserDetails userDetails) { final Authentication authentication = mock(Authentication.class); final UserEntity userEntity = new UserEntity(); userEntity.setId(ID); userEntity.setRoles(Collections.emptySet()); when(authentication.getPrincipal()).thenReturn(userDetails); when(userService.findByIdWithRoles(USER_NAME)).thenReturn(userEntity); SecurityContextHolder.setStrategyName(SecurityContextHolder.MODE_GLOBAL); SecurityContextHolder.setContext(new SecurityContextImpl(authentication)); }
Example #27
Source File: SecurityContextRepository.java From spring-boot-webflux-jjwt with Apache License 2.0 | 5 votes |
@Override public Mono<SecurityContext> load(ServerWebExchange swe) { ServerHttpRequest request = swe.getRequest(); String authHeader = request.getHeaders().getFirst(HttpHeaders.AUTHORIZATION); if (authHeader != null && authHeader.startsWith("Bearer ")) { String authToken = authHeader.substring(7); Authentication auth = new UsernamePasswordAuthenticationToken(authToken, authToken); return this.authenticationManager.authenticate(auth).map((authentication) -> { return new SecurityContextImpl(authentication); }); } else { return Mono.empty(); } }
Example #28
Source File: ReactiveSecurityContextTest.java From cloud-security-xsuaa-integration with Apache License 2.0 | 5 votes |
@Test @Ignore public void authenticated() { XsuaaToken jwt = new XsuaaToken(new JwtGenerator().setUserName("user").getToken()); SecurityContext expectedContext = new SecurityContextImpl( new TestingAuthenticationToken("user", jwt, "ROLE_USER")); ReactiveSecurityContextHolder.withSecurityContext(Mono.just(expectedContext)); Mono<XsuaaToken> tokenMono = ReactiveSecurityContext.getToken(); StepVerifier.create(tokenMono) .expectNext(jwt) .verifyComplete(); }
Example #29
Source File: ReactiveSecurityContextTest.java From cloud-security-xsuaa-integration with Apache License 2.0 | 5 votes |
@Test public void unauthenticated() { SecurityContext expectedContext = new SecurityContextImpl(); ReactiveSecurityContextHolder.withSecurityContext(Mono.just(expectedContext)); Mono<XsuaaToken> tokenMono = ReactiveSecurityContext.getToken(); StepVerifier.create(tokenMono) .expectError(AccessDeniedException.class) .verify(); }
Example #30
Source File: SpringSecurityContextTest.java From cloud-security-xsuaa-integration with Apache License 2.0 | 5 votes |
private static void setToken(Token token, Set<String> scopes) { SecurityContext context = new SecurityContextImpl(); OAuth2Authentication authentication = SAPOfflineTokenServicesCloud.getOAuth2Authentication( "clientId", scopes); HttpServletRequest request = mock(HttpServletRequest.class); when(request.getAttribute(OAuth2AuthenticationDetails.ACCESS_TOKEN_VALUE)).thenReturn(token.getTokenValue()); authentication.setDetails(new OAuth2AuthenticationDetails(request)); context.setAuthentication(authentication); SecurityContextHolder.clearContext(); SecurityContextHolder.setContext(context); assertThat(SecurityContextHolder.getContext()).isEqualTo(context); }