@Override public V call() throws Exception { this.originalSecurityContext = SecurityContextHolder.getContext(); try { SecurityContextHolder.setContext(delegateSecurityContext); return delegate.call(); } finally { SecurityContext emptyContext = SecurityContextHolder.createEmptyContext(); if (emptyContext.equals(originalSecurityContext)) { SecurityContextHolder.clearContext(); } else { SecurityContextHolder.setContext(originalSecurityContext); } this.originalSecurityContext = null; } }
@Override public void run() { this.originalSecurityContext = SecurityContextHolder.getContext(); try { SecurityContextHolder.setContext(delegateSecurityContext); delegate.run(); } finally { SecurityContext emptyContext = SecurityContextHolder.createEmptyContext(); if (emptyContext.equals(originalSecurityContext)) { SecurityContextHolder.clearContext(); } else { SecurityContextHolder.setContext(originalSecurityContext); } this.originalSecurityContext = null; } }
private void setup(Message<?> message) { SecurityContext currentContext = SecurityContextHolder.getContext(); Stack<SecurityContext> contextStack = ORIGINAL_CONTEXT.get(); if (contextStack == null) { contextStack = new Stack<>(); ORIGINAL_CONTEXT.set(contextStack); } contextStack.push(currentContext); Object user = message.getHeaders().get(authenticationHeaderName); Authentication authentication; if ((user instanceof Authentication)) { authentication = (Authentication) user; } else { authentication = this.anonymous; } SecurityContext context = SecurityContextHolder.createEmptyContext(); context.setAuthentication(authentication); SecurityContextHolder.setContext(context); }
private void cleanup() { Stack<SecurityContext> contextStack = ORIGINAL_CONTEXT.get(); if (contextStack == null || contextStack.isEmpty()) { SecurityContextHolder.clearContext(); ORIGINAL_CONTEXT.remove(); return; } SecurityContext originalContext = contextStack.pop(); try { if (EMPTY_CONTEXT.equals(originalContext)) { SecurityContextHolder.clearContext(); ORIGINAL_CONTEXT.remove(); } else { SecurityContextHolder.setContext(originalContext); } } catch (Throwable t) { SecurityContextHolder.clearContext(); } } }
/** * Cleans up the work of the <tt>AbstractSecurityInterceptor</tt> after the secure * object invocation has been completed. This method should be invoked after the * secure object invocation and before afterInvocation regardless of the secure object * invocation returning successfully (i.e. it should be done in a finally block). * * @param token as returned by the {@link #beforeInvocation(Object)} method */ protected void finallyInvocation(InterceptorStatusToken token) { if (token != null && token.isContextHolderRefreshRequired()) { if (logger.isDebugEnabled()) { logger.debug("Reverting to original Authentication: " + token.getSecurityContext().getAuthentication()); } SecurityContextHolder.setContext(token.getSecurityContext()); } }
@Before public final void setContext() { SecurityContextHolder.setContext(currentSecurityContext); }
@Test public void testContextHolderGetterSetterClearer() { SecurityContext sc = new SecurityContextImpl(); sc.setAuthentication(new UsernamePasswordAuthenticationToken("Foobar", "pass")); SecurityContextHolder.setContext(sc); assertThat(SecurityContextHolder.getContext()).isEqualTo(sc); SecurityContextHolder.clearContext(); assertThat(SecurityContextHolder.getContext()).isNotSameAs(sc); SecurityContextHolder.clearContext(); }
@Test public void testRejectsNulls() { try { SecurityContextHolder.setContext(null); fail("Should have rejected null"); } catch (IllegalArgumentException expected) { } } }
@Test public void callOnSameThread() throws Exception { originalSecurityContext = securityContext; SecurityContextHolder.setContext(originalSecurityContext); callable = new DelegatingSecurityContextCallable<>(delegate, securityContext); assertWrapped(callable.call()); }
private ExpiringCode setupResetPassword(String clientId, String redirectUri) { ScimUser user = new ScimUser("usermans-id","userman","firstName","lastName"); user.setMeta(new ScimMeta(new Date(System.currentTimeMillis()-(1000*60*60*24)), new Date(System.currentTimeMillis()-(1000*60*60*24)), 0)); user.setPrimaryEmail("user@example.com"); String zoneId = IdentityZoneHolder.get().getId(); when(scimUserProvisioning.retrieve(eq("usermans-id"), eq(zoneId))).thenReturn(user); ExpiringCode code = new ExpiringCode("code", new Timestamp(System.currentTimeMillis()), "{\"user_id\":\"usermans-id\",\"username\":\"userman\",\"passwordModifiedTime\":null,\"client_id\":\"" + clientId + "\",\"redirect_uri\":\"" + redirectUri + "\"}", null); when(codeStore.retrieveCode(eq("secret_code"), anyString())).thenReturn(code); SecurityContext securityContext = mock(SecurityContext.class); when(securityContext.getAuthentication()).thenReturn(new MockAuthentication()); SecurityContextHolder.setContext(securityContext); return code; } }
@Test public void resolveArgumentWhenRegistrationIdEmptyAndOAuth2AuthenticationThenResolves() throws Exception { OAuth2AuthenticationToken authentication = mock(OAuth2AuthenticationToken.class); when(authentication.getAuthorizedClientRegistrationId()).thenReturn("client1"); SecurityContext securityContext = SecurityContextHolder.createEmptyContext(); securityContext.setAuthentication(authentication); SecurityContextHolder.setContext(securityContext); MethodParameter methodParameter = this.getMethodParameter("registrationIdEmpty", OAuth2AuthorizedClient.class); assertThat(this.argumentResolver.resolveArgument( methodParameter, null, new ServletWebRequest(this.request), null)).isSameAs(this.authorizedClient1); }
@Test public void resetPassword_InvalidCodeData() { ExpiringCode expiringCode = new ExpiringCode("good_code", new Timestamp(System.currentTimeMillis() + UaaResetPasswordService.PASSWORD_RESET_LIFETIME), "user-id", null); when(codeStore.retrieveCode("good_code", IdentityZoneHolder.get().getId())).thenReturn(expiringCode); SecurityContext securityContext = mock(SecurityContext.class); when(securityContext.getAuthentication()).thenReturn(new MockAuthentication()); SecurityContextHolder.setContext(securityContext); try { uaaResetPasswordService.resetPassword(expiringCode, "password"); fail(); } catch (InvalidCodeException e) { assertEquals("Sorry, your reset password link is no longer valid. Please request a new one", e.getMessage()); } }
@Test public void callOnSameThread() throws Exception { originalSecurityContext = securityContext; SecurityContextHolder.setContext(originalSecurityContext); executor = synchronousExecutor(); runnable = new DelegatingSecurityContextRunnable(delegate, securityContext); assertWrapped(runnable); }
@Test public void createNullSecurityContext() throws Exception { SecurityContextHolder.setContext(securityContext); runnable = DelegatingSecurityContextRunnable.create(delegate, null); SecurityContextHolder.clearContext(); // ensure runnable is what sets up the // SecurityContextHolder assertWrapped(runnable); }
@Test public void callDefaultSecurityContext() throws Exception { SecurityContextHolder.setContext(securityContext); callable = new DelegatingSecurityContextCallable<>(delegate); SecurityContextHolder.clearContext(); // ensure callable is what sets up the // SecurityContextHolder assertWrapped(callable); }
@Test public void createNullSecurityContext() throws Exception { SecurityContextHolder.setContext(securityContext); callable = DelegatingSecurityContextCallable.create(delegate, null); SecurityContextHolder.clearContext(); // ensure callable is what sets up the // SecurityContextHolder assertWrapped(callable); }
@Test public void callDefaultSecurityContext() throws Exception { SecurityContextHolder.setContext(securityContext); runnable = new DelegatingSecurityContextRunnable(delegate); SecurityContextHolder.clearContext(); // ensure runnable is what sets up the // SecurityContextHolder assertWrapped(runnable); }
@Before public void setup() { this.registration1 = TestClientRegistrations.clientRegistration().build(); this.clientRegistrationRepository = new InMemoryClientRegistrationRepository(this.registration1); this.authorizedClientService = new InMemoryOAuth2AuthorizedClientService(this.clientRegistrationRepository); this.authorizedClientRepository = new AuthenticatedPrincipalOAuth2AuthorizedClientRepository(this.authorizedClientService); this.authorizationRequestRepository = new HttpSessionOAuth2AuthorizationRequestRepository(); this.authenticationManager = mock(AuthenticationManager.class); this.filter = spy(new OAuth2AuthorizationCodeGrantFilter( this.clientRegistrationRepository, this.authorizedClientRepository, this.authenticationManager)); this.filter.setAuthorizationRequestRepository(this.authorizationRequestRepository); TestingAuthenticationToken authentication = new TestingAuthenticationToken(this.principalName1, "password"); authentication.setAuthenticated(true); SecurityContext securityContext = SecurityContextHolder.createEmptyContext(); securityContext.setAuthentication(authentication); SecurityContextHolder.setContext(securityContext); }
@Test public void authenticationPrincipalExpressionWhenBeanExpressionSuppliedThenBeanUsed() throws Exception { User user = new User("user", "password", AuthorityUtils.createAuthorityList("ROLE_USER")); SecurityContext context = SecurityContextHolder.createEmptyContext(); context.setAuthentication(new UsernamePasswordAuthenticationToken(user, user.getPassword(), user.getAuthorities())); SecurityContextHolder.setContext(context); MockMvc mockMvc = MockMvcBuilders .webAppContextSetup(wac) .build(); mockMvc.perform(get("/users/self")) .andExpect(status().isOk()) .andExpect(content().string("extracted-user")); }
@Before public void init() { publisher = TestApplicationEventPublisher.forEventClass(IdentityProviderAuthenticationSuccessEvent.class); manager.setApplicationEventPublisher(publisher); manager.setUserDatabase(userDatabase); oauth2Authentication = new OAuth2Authentication(new AuthorizationRequest("client", Arrays.asList("read", "write")).createOAuth2Request(), null); SecurityContextImpl context = new SecurityContextImpl(); context.setAuthentication(oauth2Authentication); SecurityContextHolder.setContext(context); }