@Test public void testSuccessfulAuthentication() { RemoteAuthenticationManagerImpl manager = new RemoteAuthenticationManagerImpl(); AuthenticationManager am = mock(AuthenticationManager.class); when(am.authenticate(any(Authentication.class))).thenReturn( new TestingAuthenticationToken("u", "p", "A")); manager.setAuthenticationManager(am); manager.attemptAuthentication("rod", "password"); } }
@Test public void runAsReplacementIsCorrectlySet() throws Exception { SecurityContext ctx = SecurityContextHolder.getContext(); ctx.setAuthentication(token); token.setAuthenticated(true); final RunAsManager runAs = mock(RunAsManager.class); final RunAsUserToken runAsToken = new RunAsUserToken("key", "someone", "creds", token.getAuthorities(), TestingAuthenticationToken.class); interceptor.setRunAsManager(runAs); mdsReturnsUserRole(); when(runAs.buildRunAs(eq(token), any(MethodInvocation.class), any(List.class))) .thenReturn(runAsToken); String result = advisedTarget.makeUpperCase("hello"); assertThat(result).isEqualTo("HELLO org.springframework.security.access.intercept.RunAsUserToken true"); // Check we've changed back assertThat(SecurityContextHolder.getContext()).isSameAs(ctx); assertThat(SecurityContextHolder.getContext().getAuthentication()).isSameAs(token); }
public Authentication authenticate(Authentication authentication) throws AuthenticationException { ((TestingAuthenticationToken) authentication).setDetails(resultDetails); return authentication; }
private Authentication createAuthenticatedPrincipal() { TestingAuthenticationToken authentication = new TestingAuthenticationToken(this.principalName, "password"); authentication.setAuthenticated(true); return authentication; }
@Before public void setup() { authority = new SimpleGrantedAuthority("ROLE_AUTH"); TestingAuthenticationToken authentication = new TestingAuthenticationToken("foo", "bar", Arrays.asList(authority)); authentication.setAuthenticated(true); SecurityContextHolder.getContext().setAuthentication(authentication); }
@Test public void testAuthenticates() { TestingAuthenticationProvider provider = new TestingAuthenticationProvider(); TestingAuthenticationToken token = new TestingAuthenticationToken("Test", "Password", "ROLE_ONE", "ROLE_TWO"); Authentication result = provider.authenticate(token); assertThat(result instanceof TestingAuthenticationToken).isTrue(); TestingAuthenticationToken castResult = (TestingAuthenticationToken) result; assertThat(castResult.getPrincipal()).isEqualTo("Test"); assertThat(castResult.getCredentials()).isEqualTo("Password"); assertThat( AuthorityUtils.authorityListToSet(castResult.getAuthorities())).contains( "ROLE_ONE", "ROLE_TWO"); }
@Test public void checkPermissionAssertAccessDeniedWhenPrincipalIsNull() throws Exception { // Mock a join point of the method call // mockMethod("foo"); JoinPoint joinPoint = mock(JoinPoint.class); MethodSignature methodSignature = mock(MethodSignature.class); Method method = NamespaceSecurityAdviceTest.class.getDeclaredMethod("mockMethod", String.class); when(methodSignature.getParameterNames()).thenReturn(new String[] {"namespace"}); when(methodSignature.getMethod()).thenReturn(method); when(joinPoint.getSignature()).thenReturn(methodSignature); when(joinPoint.getArgs()).thenReturn(new Object[] {"foo"}); SecurityContextHolder.getContext().setAuthentication(new TestingAuthenticationToken(null, null)); try { namespaceSecurityAdvice.checkPermission(joinPoint); fail(); } catch (Exception e) { assertEquals(AccessDeniedException.class, e.getClass()); assertEquals("Current user does not have \"[READ]\" permission(s) to the namespace \"foo\"", e.getMessage()); } }
@Test(expected = UsernameNotFoundException.class) public void authenticate_userNotFound_2() throws Exception { when(this.userManager.getUser(Mockito.anyString(), Mockito.anyString())).thenReturn(null); TestingAuthenticationToken authTest = new TestingAuthenticationToken("username", "password"); try { Authentication auth = this.authenticationProviderManager.authenticate(authTest); Assert.fail(); } catch (UsernameNotFoundException e) { Mockito.verify(userManager, Mockito.times(1)).getUser(Mockito.anyString(), Mockito.anyString()); Mockito.verify(userManager, Mockito.times(0)).updateLastAccess(Mockito.any(UserDetails.class)); Mockito.verify(authorizationManager, Mockito.times(0)).getUserAuthorizations(Mockito.anyString()); Mockito.verify(tokenManager, Mockito.times(0)).createAccessTokenForLocalUser(Mockito.anyString()); throw e; } }
@Test public void oauth2ClientWhenCustomObjectsThenUsed() { this.spring.register(ClientRegistrationConfig.class, OAuth2ClientCustomConfig.class, AuthorizedClientController.class).autowire(); OAuth2ClientCustomConfig config = this.spring.getContext().getBean(OAuth2ClientCustomConfig.class); ServerAuthenticationConverter converter = config.authenticationConverter; ReactiveAuthenticationManager manager = config.manager; OAuth2AuthorizationExchange exchange = TestOAuth2AuthorizationExchanges.success(); OAuth2AccessToken accessToken = TestOAuth2AccessTokens.noScopes(); OAuth2AuthorizationCodeAuthenticationToken result = new OAuth2AuthorizationCodeAuthenticationToken(this.registration, exchange, accessToken); when(converter.convert(any())).thenReturn(Mono.just(new TestingAuthenticationToken("a", "b", "c"))); when(manager.authenticate(any())).thenReturn(Mono.just(result)); this.client.get() .uri("/authorize/oauth2/code/registration-id") .exchange() .expectStatus().is3xxRedirection(); verify(converter).convert(any()); verify(manager).authenticate(any()); }
@Test public void testDoFilterAuthenticateAll() throws Exception { AuthenticationSuccessHandler successHandler = mock(AuthenticationSuccessHandler.class); AuthenticationManager manager = mock(AuthenticationManager.class); Authentication authentication = new TestingAuthenticationToken("un", "pwd", "ROLE_USER"); when(manager.authenticate(any(Authentication.class))).thenReturn(authentication); ServiceProperties serviceProperties = new ServiceProperties(); serviceProperties.setAuthenticateAllArtifacts(true); .getContext().getAuthentication()).isNotNull().withFailMessage("Authentication should not be null"); verify(chain).doFilter(request, response); verifyZeroInteractions(successHandler); SecurityContextHolder.clearContext(); filter.doFilter(request, response, chain); verifyNoMoreInteractions(chain);
@Test public void afterInvocationManagerIsNotInvokedIfExceptionIsRaised() throws Throwable { MethodInvocation mi = mock(MethodInvocation.class); token.setAuthenticated(true); SecurityContextHolder.getContext().setAuthentication(token); mdsReturnsUserRole(); AfterInvocationManager aim = mock(AfterInvocationManager.class); interceptor.setAfterInvocationManager(aim); when(mi.proceed()).thenThrow(new Throwable()); try { interceptor.invoke(mi); fail("Expected exception"); } catch (Throwable expected) { } verifyZeroInteractions(aim); }
@Before public void setup() { this.authentication = new TestingAuthenticationToken(this.principalName, "password"); SecurityContext securityContext = SecurityContextHolder.createEmptyContext(); securityContext.setAuthentication(this.authentication); SecurityContextHolder.setContext(securityContext); .build(); this.clientRegistrationRepository = new InMemoryClientRegistrationRepository(this.registration1, this.registration2); this.authorizedClientRepository = mock(OAuth2AuthorizedClientRepository.class); this.argumentResolver = new OAuth2AuthorizedClientArgumentResolver( this.clientRegistrationRepository, this.authorizedClientRepository); this.authorizedClient1 = new OAuth2AuthorizedClient(this.registration1, this.principalName, mock(OAuth2AccessToken.class)); when(this.authorizedClientRepository.loadAuthorizedClient( eq(this.registration1.getRegistrationId()), any(Authentication.class), any(HttpServletRequest.class))) .thenReturn(this.authorizedClient1); this.authorizedClient2 = new OAuth2AuthorizedClient(this.registration2, this.principalName, mock(OAuth2AccessToken.class)); when(this.authorizedClientRepository.loadAuthorizedClient( eq(this.registration2.getRegistrationId()), any(Authentication.class), any(HttpServletRequest.class))) .thenReturn(this.authorizedClient2); this.request = new MockHttpServletRequest();
@Test(expected = AuthenticationServiceException.class) public void failAuthenticate_serviceError() throws Exception { when(this.userManager.getUser(Mockito.anyString(), Mockito.anyString())).thenThrow(new ApsSystemException("System error")); TestingAuthenticationToken authTest = new TestingAuthenticationToken("username", "password"); try { Authentication auth = this.authenticationProviderManager.authenticate(authTest); Assert.fail(); } catch (AuthenticationServiceException e) { Mockito.verify(userManager, Mockito.times(1)).getUser(Mockito.anyString(), Mockito.anyString()); Mockito.verify(userManager, Mockito.times(0)).updateLastAccess(Mockito.any(UserDetails.class)); Mockito.verify(authorizationManager, Mockito.times(0)).getUserAuthorizations(Mockito.anyString()); Mockito.verify(tokenManager, Mockito.times(0)).createAccessTokenForLocalUser(Mockito.anyString()); throw e; } }
@Test public void testAuthenticate() { Authentication expected = new TestingAuthenticationToken("bar", "foo", AuthorityUtils.commaSeparatedStringToAuthorityList("USER")); Mockito.when(delegate.authenticate(ArgumentMatchers.any(UsernamePasswordAuthenticationToken.class))) .thenReturn(expected); Authentication output = manager.authenticate(new TestingAuthenticationToken("foo", "bar")); assertSame(expected, output); }
@Test(expected = AuthenticationException.class) public void callIsntMadeWhenAuthenticationManagerRejectsAuthentication() throws Exception { final TestingAuthenticationToken token = new TestingAuthenticationToken("Test", "Password"); SecurityContextHolder.getContext().setAuthentication(token); mdsReturnsUserRole(); when(authman.authenticate(token)).thenThrow( new BadCredentialsException("rejected")); advisedTarget.makeLowerCase("HELLO"); }
@Test public void putInCacheAclWithParent() throws Exception { Authentication auth = new TestingAuthenticationToken("user", "password", "ROLE_GENERAL"); auth.setAuthenticated(true); SecurityContextHolder.getContext().setAuthentication(auth); ObjectIdentity identityParent = new ObjectIdentityImpl(TARGET_CLASS, Long.valueOf(2)); AclAuthorizationStrategy aclAuthorizationStrategy = new AclAuthorizationStrategyImpl( new SimpleGrantedAuthority("ROLE_OWNERSHIP"), new SimpleGrantedAuthority( "ROLE_AUDITING"), new SimpleGrantedAuthority("ROLE_GENERAL")); MutableAcl parentAcl = new AclImpl(identityParent, Long.valueOf(2), aclAuthorizationStrategy, new ConsoleAuditLogger()); acl.setParent(parentAcl); myCache.putInCache(acl); verify(cache, times(4)).put(element.capture()); List<Element> allValues = element.getAllValues(); assertThat(allValues.get(0).getKey()).isEqualTo(parentAcl.getObjectIdentity()); assertThat(allValues.get(0).getObjectValue()).isEqualTo(parentAcl); assertThat(allValues.get(1).getKey()).isEqualTo(parentAcl.getId()); assertThat(allValues.get(1).getObjectValue()).isEqualTo(parentAcl); assertThat(allValues.get(2).getKey()).isEqualTo(acl.getObjectIdentity()); assertThat(allValues.get(2).getObjectValue()).isEqualTo(acl); assertThat(allValues.get(3).getKey()).isEqualTo(acl.getId()); assertThat(allValues.get(3).getObjectValue()).isEqualTo(acl); }
@Test public void callSucceedsIfAccessDecisionManagerGrantsAccess() throws Exception { token.setAuthenticated(true); interceptor.setPublishAuthorizationSuccess(true); SecurityContextHolder.getContext().setAuthentication(token); mdsReturnsUserRole(); String result = advisedTarget.makeLowerCase("HELLO"); // Note we check the isAuthenticated remained true in following line assertThat(result).isEqualTo("hello org.springframework.security.authentication.TestingAuthenticationToken true"); verify(eventPublisher).publishEvent(any(AuthorizedEvent.class)); }
private void setAuthenticationPrincipal(Object principal) { this.expectedPrincipal = principal; SecurityContextHolder.getContext() .setAuthentication( new TestingAuthenticationToken(expectedPrincipal, "password", "ROLE_USER")); } }
@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); }
@Before public final void setUp() throws Exception { SecurityContextHolder.clearContext(); interceptor = new MethodSecurityInterceptor(); token = new TestingAuthenticationToken("Test", "Password", "ROLE_SOMETHING"); adm = mock(AccessDecisionManager.class); AuthenticationManager authman = mock(AuthenticationManager.class); mds = mock(MethodSecurityMetadataSource.class); interceptor.setAccessDecisionManager(adm); interceptor.setAuthenticationManager(authman); interceptor.setSecurityMetadataSource(mds); }