Add UsernamePasswordAuthenticationToken factory methods

- unauthenticated factory method
 - authenticated factory method
 - test for unauthenticated factory method
 - test for authenticated factory method
 - make existing constructor protected
 - use newly factory methods in rest of the project
 - update copyright dates

Closes gh-10790
This commit is contained in:
Norbert Nowak 2022-03-08 11:33:13 +01:00 committed by Josh Cummings
parent 28c7a4be11
commit abd33389be
88 changed files with 439 additions and 346 deletions

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2020 the original author or authors. * Copyright 2002-2022 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -56,7 +56,7 @@ public class LdapProviderBeanDefinitionParserTests {
AuthenticationManager authenticationManager = this.appCtx.getBean(BeanIds.AUTHENTICATION_MANAGER, AuthenticationManager authenticationManager = this.appCtx.getBean(BeanIds.AUTHENTICATION_MANAGER,
AuthenticationManager.class); AuthenticationManager.class);
Authentication auth = authenticationManager Authentication auth = authenticationManager
.authenticate(new UsernamePasswordAuthenticationToken("ben", "benspassword")); .authenticate(UsernamePasswordAuthenticationToken.unauthenticated("ben", "benspassword"));
UserDetails ben = (UserDetails) auth.getPrincipal(); UserDetails ben = (UserDetails) auth.getPrincipal();
assertThat(ben.getAuthorities()).hasSize(3); assertThat(ben.getAuthorities()).hasSize(3);
} }
@ -89,7 +89,7 @@ public class LdapProviderBeanDefinitionParserTests {
AuthenticationManager authenticationManager = this.appCtx.getBean(BeanIds.AUTHENTICATION_MANAGER, AuthenticationManager authenticationManager = this.appCtx.getBean(BeanIds.AUTHENTICATION_MANAGER,
AuthenticationManager.class); AuthenticationManager.class);
Authentication auth = authenticationManager Authentication auth = authenticationManager
.authenticate(new UsernamePasswordAuthenticationToken("ben", "benspassword")); .authenticate(UsernamePasswordAuthenticationToken.unauthenticated("ben", "benspassword"));
assertThat(auth).isNotNull(); assertThat(auth).isNotNull();
} }
@ -104,7 +104,8 @@ public class LdapProviderBeanDefinitionParserTests {
AuthenticationManager authenticationManager = this.appCtx.getBean(BeanIds.AUTHENTICATION_MANAGER, AuthenticationManager authenticationManager = this.appCtx.getBean(BeanIds.AUTHENTICATION_MANAGER,
AuthenticationManager.class); AuthenticationManager.class);
Authentication auth = authenticationManager.authenticate(new UsernamePasswordAuthenticationToken("ben", "ben")); Authentication auth = authenticationManager
.authenticate(UsernamePasswordAuthenticationToken.unauthenticated("ben", "ben"));
assertThat(auth).isNotNull(); assertThat(auth).isNotNull();
} }
@ -121,7 +122,7 @@ public class LdapProviderBeanDefinitionParserTests {
AuthenticationManager authenticationManager = this.appCtx.getBean(BeanIds.AUTHENTICATION_MANAGER, AuthenticationManager authenticationManager = this.appCtx.getBean(BeanIds.AUTHENTICATION_MANAGER,
AuthenticationManager.class); AuthenticationManager.class);
Authentication auth = authenticationManager Authentication auth = authenticationManager
.authenticate(new UsernamePasswordAuthenticationToken("bcrypt", "password")); .authenticate(UsernamePasswordAuthenticationToken.unauthenticated("bcrypt", "password"));
assertThat(auth).isNotNull(); assertThat(auth).isNotNull();
} }

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2018 the original author or authors. * Copyright 2002-2022 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -93,8 +93,8 @@ public class AuthenticationManagerBuilderTests {
given(opp.postProcess(any())).willAnswer((a) -> a.getArgument(0)); given(opp.postProcess(any())).willAnswer((a) -> a.getArgument(0));
AuthenticationManager am = new AuthenticationManagerBuilder(opp).authenticationEventPublisher(aep) AuthenticationManager am = new AuthenticationManagerBuilder(opp).authenticationEventPublisher(aep)
.inMemoryAuthentication().and().build(); .inMemoryAuthentication().and().build();
assertThatExceptionOfType(AuthenticationException.class) assertThatExceptionOfType(AuthenticationException.class).isThrownBy(
.isThrownBy(() -> am.authenticate(new UsernamePasswordAuthenticationToken("user", "password"))); () -> am.authenticate(UsernamePasswordAuthenticationToken.unauthenticated("user", "password")));
verify(aep).publishAuthenticationFailure(any(), any()); verify(aep).publishAuthenticationFailure(any(), any());
} }
@ -103,7 +103,8 @@ public class AuthenticationManagerBuilderTests {
this.spring.register(PasswordEncoderGlobalConfig.class).autowire(); this.spring.register(PasswordEncoderGlobalConfig.class).autowire();
AuthenticationManager manager = this.spring.getContext().getBean(AuthenticationConfiguration.class) AuthenticationManager manager = this.spring.getContext().getBean(AuthenticationConfiguration.class)
.getAuthenticationManager(); .getAuthenticationManager();
Authentication auth = manager.authenticate(new UsernamePasswordAuthenticationToken("user", "password")); Authentication auth = manager
.authenticate(UsernamePasswordAuthenticationToken.unauthenticated("user", "password"));
assertThat(auth.getName()).isEqualTo("user"); assertThat(auth.getName()).isEqualTo("user");
assertThat(auth.getAuthorities()).extracting(GrantedAuthority::getAuthority).containsOnly("ROLE_USER"); assertThat(auth.getAuthorities()).extracting(GrantedAuthority::getAuthority).containsOnly("ROLE_USER");
} }
@ -113,7 +114,8 @@ public class AuthenticationManagerBuilderTests {
this.spring.register(PasswordEncoderGlobalConfig.class).autowire(); this.spring.register(PasswordEncoderGlobalConfig.class).autowire();
AuthenticationManager manager = this.spring.getContext().getBean(AuthenticationConfiguration.class) AuthenticationManager manager = this.spring.getContext().getBean(AuthenticationConfiguration.class)
.getAuthenticationManager(); .getAuthenticationManager();
Authentication auth = manager.authenticate(new UsernamePasswordAuthenticationToken("user", "password")); Authentication auth = manager
.authenticate(UsernamePasswordAuthenticationToken.unauthenticated("user", "password"));
assertThat(auth.getName()).isEqualTo("user"); assertThat(auth.getName()).isEqualTo("user");
assertThat(auth.getAuthorities()).extracting(GrantedAuthority::getAuthority).containsOnly("ROLE_USER"); assertThat(auth.getAuthorities()).extracting(GrantedAuthority::getAuthority).containsOnly("ROLE_USER");
} }

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2018 the original author or authors. * Copyright 2002-2022 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -47,7 +47,8 @@ public class AuthenticationConfigurationPublishTests {
// gh-4940 // gh-4940
@Test @Test
public void authenticationEventPublisherBeanUsedByDefault() { public void authenticationEventPublisherBeanUsedByDefault() {
this.authenticationManager.authenticate(new UsernamePasswordAuthenticationToken("user", "password")); this.authenticationManager
.authenticate(UsernamePasswordAuthenticationToken.unauthenticated("user", "password"));
assertThat(this.listener.getEvents()).hasSize(1); assertThat(this.listener.getEvents()).hasSize(1);
} }

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2019 the original author or authors. * Copyright 2002-2022 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -129,7 +129,8 @@ public class AuthenticationConfigurationTests {
@Test @Test
public void getAuthenticationWhenGlobalAuthenticationConfigurerAdapterThenAuthenticates() throws Exception { public void getAuthenticationWhenGlobalAuthenticationConfigurerAdapterThenAuthenticates() throws Exception {
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("user", "password"); UsernamePasswordAuthenticationToken token = UsernamePasswordAuthenticationToken.unauthenticated("user",
"password");
this.spring.register(AuthenticationConfiguration.class, ObjectPostProcessorConfiguration.class, this.spring.register(AuthenticationConfiguration.class, ObjectPostProcessorConfiguration.class,
UserGlobalAuthenticationConfigurerAdapter.class).autowire(); UserGlobalAuthenticationConfigurerAdapter.class).autowire();
AuthenticationManager authentication = this.spring.getContext().getBean(AuthenticationConfiguration.class) AuthenticationManager authentication = this.spring.getContext().getBean(AuthenticationConfiguration.class)
@ -139,7 +140,8 @@ public class AuthenticationConfigurationTests {
@Test @Test
public void getAuthenticationWhenAuthenticationManagerBeanThenAuthenticates() throws Exception { public void getAuthenticationWhenAuthenticationManagerBeanThenAuthenticates() throws Exception {
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("user", "password"); UsernamePasswordAuthenticationToken token = UsernamePasswordAuthenticationToken.unauthenticated("user",
"password");
this.spring.register(AuthenticationConfiguration.class, ObjectPostProcessorConfiguration.class, this.spring.register(AuthenticationConfiguration.class, ObjectPostProcessorConfiguration.class,
AuthenticationManagerBeanConfig.class).autowire(); AuthenticationManagerBeanConfig.class).autowire();
AuthenticationManager authentication = this.spring.getContext().getBean(AuthenticationConfiguration.class) AuthenticationManager authentication = this.spring.getContext().getBean(AuthenticationConfiguration.class)
@ -165,9 +167,9 @@ public class AuthenticationConfigurationTests {
config.setGlobalAuthenticationConfigurers(Arrays.asList(new ConfiguresInMemoryConfigurerAdapter(), config.setGlobalAuthenticationConfigurers(Arrays.asList(new ConfiguresInMemoryConfigurerAdapter(),
new BootGlobalAuthenticationConfigurerAdapter())); new BootGlobalAuthenticationConfigurerAdapter()));
AuthenticationManager authenticationManager = config.getAuthenticationManager(); AuthenticationManager authenticationManager = config.getAuthenticationManager();
authenticationManager.authenticate(new UsernamePasswordAuthenticationToken("user", "password")); authenticationManager.authenticate(UsernamePasswordAuthenticationToken.unauthenticated("user", "password"));
assertThatExceptionOfType(AuthenticationException.class).isThrownBy( assertThatExceptionOfType(AuthenticationException.class).isThrownBy(() -> authenticationManager
() -> authenticationManager.authenticate(new UsernamePasswordAuthenticationToken("boot", "password"))); .authenticate(UsernamePasswordAuthenticationToken.unauthenticated("boot", "password")));
} }
@Test @Test
@ -176,7 +178,7 @@ public class AuthenticationConfigurationTests {
AuthenticationConfiguration config = this.spring.getContext().getBean(AuthenticationConfiguration.class); AuthenticationConfiguration config = this.spring.getContext().getBean(AuthenticationConfiguration.class);
config.setGlobalAuthenticationConfigurers(Arrays.asList(new BootGlobalAuthenticationConfigurerAdapter())); config.setGlobalAuthenticationConfigurers(Arrays.asList(new BootGlobalAuthenticationConfigurerAdapter()));
AuthenticationManager authenticationManager = config.getAuthenticationManager(); AuthenticationManager authenticationManager = config.getAuthenticationManager();
authenticationManager.authenticate(new UsernamePasswordAuthenticationToken("boot", "password")); authenticationManager.authenticate(UsernamePasswordAuthenticationToken.unauthenticated("boot", "password"));
} }
// gh-2531 // gh-2531
@ -206,9 +208,9 @@ public class AuthenticationConfigurationTests {
AuthenticationManager am = this.spring.getContext().getBean(AuthenticationConfiguration.class) AuthenticationManager am = this.spring.getContext().getBean(AuthenticationConfiguration.class)
.getAuthenticationManager(); .getAuthenticationManager();
given(uds.loadUserByUsername("user")).willReturn(PasswordEncodedUser.user(), PasswordEncodedUser.user()); given(uds.loadUserByUsername("user")).willReturn(PasswordEncodedUser.user(), PasswordEncodedUser.user());
am.authenticate(new UsernamePasswordAuthenticationToken("user", "password")); am.authenticate(UsernamePasswordAuthenticationToken.unauthenticated("user", "password"));
assertThatExceptionOfType(AuthenticationException.class) assertThatExceptionOfType(AuthenticationException.class).isThrownBy(
.isThrownBy(() -> am.authenticate(new UsernamePasswordAuthenticationToken("user", "invalid"))); () -> am.authenticate(UsernamePasswordAuthenticationToken.unauthenticated("user", "invalid")));
} }
@Test @Test
@ -221,9 +223,9 @@ public class AuthenticationConfigurationTests {
.getAuthenticationManager(); .getAuthenticationManager();
given(uds.loadUserByUsername("user")).willReturn(User.withUserDetails(user).build(), given(uds.loadUserByUsername("user")).willReturn(User.withUserDetails(user).build(),
User.withUserDetails(user).build()); User.withUserDetails(user).build());
am.authenticate(new UsernamePasswordAuthenticationToken("user", "password")); am.authenticate(UsernamePasswordAuthenticationToken.unauthenticated("user", "password"));
assertThatExceptionOfType(AuthenticationException.class) assertThatExceptionOfType(AuthenticationException.class).isThrownBy(
.isThrownBy(() -> am.authenticate(new UsernamePasswordAuthenticationToken("user", "invalid"))); () -> am.authenticate(UsernamePasswordAuthenticationToken.unauthenticated("user", "invalid")));
} }
@Test @Test
@ -237,7 +239,7 @@ public class AuthenticationConfigurationTests {
given(manager.loadUserByUsername("user")).willReturn(User.withUserDetails(user).build(), given(manager.loadUserByUsername("user")).willReturn(User.withUserDetails(user).build(),
User.withUserDetails(user).build()); User.withUserDetails(user).build());
given(manager.updatePassword(any(), any())).willReturn(user); given(manager.updatePassword(any(), any())).willReturn(user);
am.authenticate(new UsernamePasswordAuthenticationToken("user", "password")); am.authenticate(UsernamePasswordAuthenticationToken.unauthenticated("user", "password"));
verify(manager).updatePassword(eq(user), startsWith("{bcrypt}")); verify(manager).updatePassword(eq(user), startsWith("{bcrypt}"));
} }
@ -250,7 +252,7 @@ public class AuthenticationConfigurationTests {
.getAuthenticationManager(); .getAuthenticationManager();
given(ap.supports(any())).willReturn(true); given(ap.supports(any())).willReturn(true);
given(ap.authenticate(any())).willReturn(TestAuthentication.authenticatedUser()); given(ap.authenticate(any())).willReturn(TestAuthentication.authenticatedUser());
am.authenticate(new UsernamePasswordAuthenticationToken("user", "password")); am.authenticate(UsernamePasswordAuthenticationToken.unauthenticated("user", "password"));
} }
// gh-3091 // gh-3091
@ -262,7 +264,7 @@ public class AuthenticationConfigurationTests {
.getAuthenticationManager(); .getAuthenticationManager();
given(ap.supports(any())).willReturn(true); given(ap.supports(any())).willReturn(true);
given(ap.authenticate(any())).willReturn(TestAuthentication.authenticatedUser()); given(ap.authenticate(any())).willReturn(TestAuthentication.authenticatedUser());
am.authenticate(new UsernamePasswordAuthenticationToken("user", "password")); am.authenticate(UsernamePasswordAuthenticationToken.unauthenticated("user", "password"));
} }
@Test @Test

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2018 the original author or authors. * Copyright 2002-2022 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -75,21 +75,21 @@ public class Issue50Tests {
@Test @Test
public void authenticateWhenMissingUserThenUsernameNotFoundException() { public void authenticateWhenMissingUserThenUsernameNotFoundException() {
assertThatExceptionOfType(UsernameNotFoundException.class).isThrownBy(() -> this.authenticationManager assertThatExceptionOfType(UsernameNotFoundException.class).isThrownBy(() -> this.authenticationManager
.authenticate(new UsernamePasswordAuthenticationToken("test", "password"))); .authenticate(UsernamePasswordAuthenticationToken.unauthenticated("test", "password")));
} }
@Test @Test
public void authenticateWhenInvalidPasswordThenBadCredentialsException() { public void authenticateWhenInvalidPasswordThenBadCredentialsException() {
this.userRepo.save(User.withUsernameAndPassword("test", "password")); this.userRepo.save(User.withUsernameAndPassword("test", "password"));
assertThatExceptionOfType(BadCredentialsException.class).isThrownBy(() -> this.authenticationManager assertThatExceptionOfType(BadCredentialsException.class).isThrownBy(() -> this.authenticationManager
.authenticate(new UsernamePasswordAuthenticationToken("test", "invalid"))); .authenticate(UsernamePasswordAuthenticationToken.unauthenticated("test", "invalid")));
} }
@Test @Test
public void authenticateWhenValidUserThenAuthenticates() { public void authenticateWhenValidUserThenAuthenticates() {
this.userRepo.save(User.withUsernameAndPassword("test", "password")); this.userRepo.save(User.withUsernameAndPassword("test", "password"));
Authentication result = this.authenticationManager Authentication result = this.authenticationManager
.authenticate(new UsernamePasswordAuthenticationToken("test", "password")); .authenticate(UsernamePasswordAuthenticationToken.unauthenticated("test", "password"));
assertThat(result.getName()).isEqualTo("test"); assertThat(result.getName()).isEqualTo("test");
} }
@ -98,7 +98,7 @@ public class Issue50Tests {
SecurityContextHolder.getContext().setAuthentication(new TestingAuthenticationToken("test", null, "ROLE_USER")); SecurityContextHolder.getContext().setAuthentication(new TestingAuthenticationToken("test", null, "ROLE_USER"));
this.userRepo.save(User.withUsernameAndPassword("denied", "password")); this.userRepo.save(User.withUsernameAndPassword("denied", "password"));
assertThatExceptionOfType(AccessDeniedException.class).isThrownBy(() -> this.authenticationManager assertThatExceptionOfType(AccessDeniedException.class).isThrownBy(() -> this.authenticationManager
.authenticate(new UsernamePasswordAuthenticationToken("test", "password"))); .authenticate(UsernamePasswordAuthenticationToken.unauthenticated("test", "password")));
} }
} }

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2021 the original author or authors. * Copyright 2002-2022 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -106,8 +106,8 @@ public class GlobalMethodSecurityConfigurationTests {
@Test @Test
public void methodSecurityAuthenticationManagerPublishesEvent() { public void methodSecurityAuthenticationManagerPublishesEvent() {
this.spring.register(InMemoryAuthWithGlobalMethodSecurityConfig.class).autowire(); this.spring.register(InMemoryAuthWithGlobalMethodSecurityConfig.class).autowire();
assertThatExceptionOfType(AuthenticationException.class).isThrownBy( assertThatExceptionOfType(AuthenticationException.class).isThrownBy(() -> this.authenticationManager
() -> this.authenticationManager.authenticate(new UsernamePasswordAuthenticationToken("foo", "bar"))); .authenticate(UsernamePasswordAuthenticationToken.unauthenticated("foo", "bar")));
assertThat(this.events.getEvents()).extracting(Object::getClass) assertThat(this.events.getEvents()).extracting(Object::getClass)
.containsOnly((Class) AuthenticationFailureBadCredentialsEvent.class); .containsOnly((Class) AuthenticationFailureBadCredentialsEvent.class);
} }

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2016 the original author or authors. * Copyright 2002-2022 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -65,7 +65,7 @@ public class AuthenticationPrincipalArgumentResolverTests {
User user = new User("user", "password", AuthorityUtils.createAuthorityList("ROLE_USER")); User user = new User("user", "password", AuthorityUtils.createAuthorityList("ROLE_USER"));
SecurityContext context = SecurityContextHolder.createEmptyContext(); SecurityContext context = SecurityContextHolder.createEmptyContext();
context.setAuthentication( context.setAuthentication(
new UsernamePasswordAuthenticationToken(user, user.getPassword(), user.getAuthorities())); UsernamePasswordAuthenticationToken.authenticated(user, user.getPassword(), user.getAuthorities()));
SecurityContextHolder.setContext(context); SecurityContextHolder.setContext(context);
MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build(); MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build();
// @formatter:off // @formatter:off

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2020 the original author or authors. * Copyright 2002-2022 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -60,7 +60,7 @@ public class EnableWebSecurityTests {
this.spring.register(SecurityConfig.class).autowire(); this.spring.register(SecurityConfig.class).autowire();
AuthenticationManager authenticationManager = this.spring.getContext().getBean(AuthenticationManager.class); AuthenticationManager authenticationManager = this.spring.getContext().getBean(AuthenticationManager.class);
Authentication authentication = authenticationManager Authentication authentication = authenticationManager
.authenticate(new UsernamePasswordAuthenticationToken("user", "password")); .authenticate(UsernamePasswordAuthenticationToken.unauthenticated("user", "password"));
assertThat(authentication.isAuthenticated()).isTrue(); assertThat(authentication.isAuthenticated()).isTrue();
} }

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2021 the original author or authors. * Copyright 2002-2022 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -1013,7 +1013,7 @@ public class WebSecurityConfigurationTests {
return new ProviderManager(new AuthenticationProvider() { return new ProviderManager(new AuthenticationProvider() {
@Override @Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException { public Authentication authenticate(Authentication authentication) throws AuthenticationException {
return new UsernamePasswordAuthenticationToken("user", "credentials"); return UsernamePasswordAuthenticationToken.unauthenticated("user", "credentials");
} }
@Override @Override
@ -1028,7 +1028,7 @@ public class WebSecurityConfigurationTests {
return new ProviderManager(new AuthenticationProvider() { return new ProviderManager(new AuthenticationProvider() {
@Override @Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException { public Authentication authenticate(Authentication authentication) throws AuthenticationException {
return new UsernamePasswordAuthenticationToken("subuser", "credentials"); return UsernamePasswordAuthenticationToken.unauthenticated("subuser", "credentials");
} }
@Override @Override

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2019 the original author or authors. * Copyright 2002-2022 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -150,7 +150,7 @@ public class AuthorizeRequestsTests {
public void roleHiearchy() throws Exception { public void roleHiearchy() throws Exception {
loadConfig(RoleHiearchyConfig.class); loadConfig(RoleHiearchyConfig.class);
SecurityContext securityContext = new SecurityContextImpl(); SecurityContext securityContext = new SecurityContextImpl();
securityContext.setAuthentication(new UsernamePasswordAuthenticationToken("test", "notused", securityContext.setAuthentication(UsernamePasswordAuthenticationToken.authenticated("test", "notused",
AuthorityUtils.createAuthorityList("ROLE_USER"))); AuthorityUtils.createAuthorityList("ROLE_USER")));
this.request.getSession().setAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY, this.request.getSession().setAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY,
securityContext); securityContext);

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2019 the original author or authors. * Copyright 2002-2022 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -100,7 +100,8 @@ public class NamespaceHttpInterceptUrlTests {
} }
private static Authentication user(String role) { private static Authentication user(String role) {
return new UsernamePasswordAuthenticationToken("user", null, AuthorityUtils.createAuthorityList(role)); return UsernamePasswordAuthenticationToken.authenticated("user", null,
AuthorityUtils.createAuthorityList(role));
} }
@EnableWebSecurity @EnableWebSecurity

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2019 the original author or authors. * Copyright 2002-2022 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -97,7 +97,7 @@ public class NamespaceHttpServerAccessDeniedHandlerTests {
} }
private static Authentication user() { private static Authentication user() {
return new UsernamePasswordAuthenticationToken("user", null, AuthorityUtils.NO_AUTHORITIES); return UsernamePasswordAuthenticationToken.authenticated("user", null, AuthorityUtils.NO_AUTHORITIES);
} }
private <T> T verifyBean(Class<T> beanClass) { private <T> T verifyBean(Class<T> beanClass) {

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2012-2016 the original author or authors. * Copyright 2012-2022 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -72,7 +72,7 @@ public class AuthenticationConfigurationGh3935Tests {
AuthenticationManager authenticationManager = this.adapter.authenticationManager; AuthenticationManager authenticationManager = this.adapter.authenticationManager;
assertThat(authenticationManager).isNotNull(); assertThat(authenticationManager).isNotNull();
Authentication auth = authenticationManager Authentication auth = authenticationManager
.authenticate(new UsernamePasswordAuthenticationToken(username, password)); .authenticate(UsernamePasswordAuthenticationToken.unauthenticated(username, password));
verify(this.uds).loadUserByUsername(username); verify(this.uds).loadUserByUsername(username);
assertThat(auth.getPrincipal()).isEqualTo(PasswordEncodedUser.user()); assertThat(auth.getPrincipal()).isEqualTo(PasswordEncodedUser.user());
} }

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2021 the original author or authors. * Copyright 2002-2022 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -98,7 +98,7 @@ public class AuthenticationManagerBeanDefinitionParserTests {
Object eventPublisher = FieldUtils.getFieldValue(pm, "eventPublisher"); Object eventPublisher = FieldUtils.getFieldValue(pm, "eventPublisher");
assertThat(eventPublisher).isNotNull(); assertThat(eventPublisher).isNotNull();
assertThat(eventPublisher instanceof DefaultAuthenticationEventPublisher).isTrue(); assertThat(eventPublisher instanceof DefaultAuthenticationEventPublisher).isTrue();
pm.authenticate(new UsernamePasswordAuthenticationToken("bob", "bobspassword")); pm.authenticate(UsernamePasswordAuthenticationToken.unauthenticated("bob", "bobspassword"));
assertThat(listener.events).hasSize(1); assertThat(listener.events).hasSize(1);
} }

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2016 the original author or authors. * Copyright 2002-2022 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -42,7 +42,8 @@ public class AuthenticationProviderBeanDefinitionParserTests {
private AbstractXmlApplicationContext appContext; private AbstractXmlApplicationContext appContext;
private UsernamePasswordAuthenticationToken bob = new UsernamePasswordAuthenticationToken("bob", "bobspassword"); private UsernamePasswordAuthenticationToken bob = UsernamePasswordAuthenticationToken.unauthenticated("bob",
"bobspassword");
@AfterEach @AfterEach
public void closeAppContext() { public void closeAppContext() {

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2016 the original author or authors. * Copyright 2002-2022 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -129,7 +129,7 @@ public class JdbcUserServiceBeanDefinitionParserTests {
+ DATA_SOURCE); + DATA_SOURCE);
// @formatter:on // @formatter:on
AuthenticationManager mgr = (AuthenticationManager) this.appContext.getBean(BeanIds.AUTHENTICATION_MANAGER); AuthenticationManager mgr = (AuthenticationManager) this.appContext.getBean(BeanIds.AUTHENTICATION_MANAGER);
mgr.authenticate(new UsernamePasswordAuthenticationToken("rod", "koala")); mgr.authenticate(UsernamePasswordAuthenticationToken.unauthenticated("rod", "koala"));
} }
@Test @Test
@ -146,7 +146,7 @@ public class JdbcUserServiceBeanDefinitionParserTests {
ProviderManager mgr = (ProviderManager) this.appContext.getBean(BeanIds.AUTHENTICATION_MANAGER); ProviderManager mgr = (ProviderManager) this.appContext.getBean(BeanIds.AUTHENTICATION_MANAGER);
DaoAuthenticationProvider provider = (DaoAuthenticationProvider) mgr.getProviders().get(0); DaoAuthenticationProvider provider = (DaoAuthenticationProvider) mgr.getProviders().get(0);
assertThat(this.appContext.getBean("userCache")).isSameAs(provider.getUserCache()); assertThat(this.appContext.getBean("userCache")).isSameAs(provider.getUserCache());
provider.authenticate(new UsernamePasswordAuthenticationToken("rod", "koala")); provider.authenticate(UsernamePasswordAuthenticationToken.unauthenticated("rod", "koala"));
assertThat(provider.getUserCache().getUserFromCache("rod")).isNotNull() assertThat(provider.getUserCache().getUserFromCache("rod")).isNotNull()
.withFailMessage("Cache should contain user after authentication"); .withFailMessage("Cache should contain user after authentication");
} }

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2017 the original author or authors. * Copyright 2002-2022 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -67,7 +67,7 @@ import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
*/ */
public class GlobalMethodSecurityBeanDefinitionParserTests { public class GlobalMethodSecurityBeanDefinitionParserTests {
private final UsernamePasswordAuthenticationToken bob = new UsernamePasswordAuthenticationToken("bob", private final UsernamePasswordAuthenticationToken bob = UsernamePasswordAuthenticationToken.unauthenticated("bob",
"bobspassword"); "bobspassword");
private AbstractXmlApplicationContext appContext; private AbstractXmlApplicationContext appContext;
@ -106,7 +106,8 @@ public class GlobalMethodSecurityBeanDefinitionParserTests {
@Test @Test
public void targetShouldAllowProtectedMethodInvocationWithCorrectRole() { public void targetShouldAllowProtectedMethodInvocationWithCorrectRole() {
loadContext(); loadContext();
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("user", "password"); UsernamePasswordAuthenticationToken token = UsernamePasswordAuthenticationToken.unauthenticated("user",
"password");
SecurityContextHolder.getContext().setAuthentication(token); SecurityContextHolder.getContext().setAuthentication(token);
this.target.someUserMethod1(); this.target.someUserMethod1();
// SEC-1213. Check the order // SEC-1213. Check the order
@ -153,8 +154,8 @@ public class GlobalMethodSecurityBeanDefinitionParserTests {
+ "</authentication-manager>"); + "</authentication-manager>");
// @formatter:on // @formatter:on
UserDetailsService service = (UserDetailsService) this.appContext.getBean("myUserService"); UserDetailsService service = (UserDetailsService) this.appContext.getBean("myUserService");
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("Test", "Password", UsernamePasswordAuthenticationToken token = UsernamePasswordAuthenticationToken.authenticated("Test",
AuthorityUtils.createAuthorityList("ROLE_SOMEOTHERROLE")); "Password", AuthorityUtils.createAuthorityList("ROLE_SOMEOTHERROLE"));
SecurityContextHolder.getContext().setAuthentication(token); SecurityContextHolder.getContext().setAuthentication(token);
assertThatExceptionOfType(AccessDeniedException.class).isThrownBy(() -> service.loadUserByUsername("notused")); assertThatExceptionOfType(AccessDeniedException.class).isThrownBy(() -> service.loadUserByUsername("notused"));
} }
@ -170,7 +171,7 @@ public class GlobalMethodSecurityBeanDefinitionParserTests {
+ ConfigTestUtils.AUTH_PROVIDER_XML); + ConfigTestUtils.AUTH_PROVIDER_XML);
// @formatter:on // @formatter:on
SecurityContextHolder.getContext() SecurityContextHolder.getContext()
.setAuthentication(new UsernamePasswordAuthenticationToken("user", "password")); .setAuthentication(UsernamePasswordAuthenticationToken.unauthenticated("user", "password"));
this.target = (BusinessService) this.appContext.getBean("target"); this.target = (BusinessService) this.appContext.getBean("target");
// someOther(int) should not be matched by someOther(String), but should require // someOther(int) should not be matched by someOther(String), but should require
// ROLE_USER // ROLE_USER
@ -198,7 +199,7 @@ public class GlobalMethodSecurityBeanDefinitionParserTests {
assertThatExceptionOfType(AuthenticationCredentialsNotFoundException.class) assertThatExceptionOfType(AuthenticationCredentialsNotFoundException.class)
.isThrownBy(() -> this.target.someOther(0)); .isThrownBy(() -> this.target.someOther(0));
SecurityContextHolder.getContext() SecurityContextHolder.getContext()
.setAuthentication(new UsernamePasswordAuthenticationToken("user", "password")); .setAuthentication(UsernamePasswordAuthenticationToken.unauthenticated("user", "password"));
this.target.someOther(0); this.target.someOther(0);
} }
@ -366,7 +367,7 @@ public class GlobalMethodSecurityBeanDefinitionParserTests {
Foo foo = (Foo) this.appContext.getBean("target"); Foo foo = (Foo) this.appContext.getBean("target");
assertThatExceptionOfType(AccessDeniedException.class).isThrownBy(() -> foo.foo(new SecurityConfig("A"))); assertThatExceptionOfType(AccessDeniedException.class).isThrownBy(() -> foo.foo(new SecurityConfig("A")));
SecurityContextHolder.getContext() SecurityContextHolder.getContext()
.setAuthentication(new UsernamePasswordAuthenticationToken("admin", "password")); .setAuthentication(UsernamePasswordAuthenticationToken.unauthenticated("admin", "password"));
foo.foo(new SecurityConfig("A")); foo.foo(new SecurityConfig("A"));
} }
@ -387,7 +388,7 @@ public class GlobalMethodSecurityBeanDefinitionParserTests {
Foo foo = (Foo) this.appContext.getBean("target"); Foo foo = (Foo) this.appContext.getBean("target");
assertThatExceptionOfType(AccessDeniedException.class).isThrownBy(() -> foo.foo(new SecurityConfig("A"))); assertThatExceptionOfType(AccessDeniedException.class).isThrownBy(() -> foo.foo(new SecurityConfig("A")));
SecurityContextHolder.getContext() SecurityContextHolder.getContext()
.setAuthentication(new UsernamePasswordAuthenticationToken("admin", "password")); .setAuthentication(UsernamePasswordAuthenticationToken.unauthenticated("admin", "password"));
foo.foo(new SecurityConfig("A")); foo.foo(new SecurityConfig("A"));
} }

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2017 the original author or authors. * Copyright 2002-2022 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -91,16 +91,16 @@ public class InterceptMethodsBeanDefinitionDecoratorTests implements Application
@Test @Test
public void targetShouldAllowProtectedMethodInvocationWithCorrectRole() { public void targetShouldAllowProtectedMethodInvocationWithCorrectRole() {
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("Test", "Password", UsernamePasswordAuthenticationToken token = UsernamePasswordAuthenticationToken.authenticated("Test",
AuthorityUtils.createAuthorityList("ROLE_USER")); "Password", AuthorityUtils.createAuthorityList("ROLE_USER"));
SecurityContextHolder.getContext().setAuthentication(token); SecurityContextHolder.getContext().setAuthentication(token);
this.target.doSomething(); this.target.doSomething();
} }
@Test @Test
public void targetShouldPreventProtectedMethodInvocationWithIncorrectRole() { public void targetShouldPreventProtectedMethodInvocationWithIncorrectRole() {
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("Test", "Password", UsernamePasswordAuthenticationToken token = UsernamePasswordAuthenticationToken.authenticated("Test",
AuthorityUtils.createAuthorityList("ROLE_SOMEOTHERROLE")); "Password", AuthorityUtils.createAuthorityList("ROLE_SOMEOTHERROLE"));
SecurityContextHolder.getContext().setAuthentication(token); SecurityContextHolder.getContext().setAuthentication(token);
assertThatExceptionOfType(AccessDeniedException.class).isThrownBy(this.target::doSomething); assertThatExceptionOfType(AccessDeniedException.class).isThrownBy(this.target::doSomething);
} }

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2016 the original author or authors. * Copyright 2002-2022 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -67,32 +67,32 @@ public class Jsr250AnnotationDrivenBeanDefinitionParserTests {
@Test @Test
public void permitAllShouldBeDefaultAttribute() { public void permitAllShouldBeDefaultAttribute() {
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("Test", "Password", UsernamePasswordAuthenticationToken token = UsernamePasswordAuthenticationToken.authenticated("Test",
AuthorityUtils.createAuthorityList("ROLE_USER")); "Password", AuthorityUtils.createAuthorityList("ROLE_USER"));
SecurityContextHolder.getContext().setAuthentication(token); SecurityContextHolder.getContext().setAuthentication(token);
this.target.someOther(0); this.target.someOther(0);
} }
@Test @Test
public void targetShouldAllowProtectedMethodInvocationWithCorrectRole() { public void targetShouldAllowProtectedMethodInvocationWithCorrectRole() {
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("Test", "Password", UsernamePasswordAuthenticationToken token = UsernamePasswordAuthenticationToken.authenticated("Test",
AuthorityUtils.createAuthorityList("ROLE_USER")); "Password", AuthorityUtils.createAuthorityList("ROLE_USER"));
SecurityContextHolder.getContext().setAuthentication(token); SecurityContextHolder.getContext().setAuthentication(token);
this.target.someUserMethod1(); this.target.someUserMethod1();
} }
@Test @Test
public void targetShouldPreventProtectedMethodInvocationWithIncorrectRole() { public void targetShouldPreventProtectedMethodInvocationWithIncorrectRole() {
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("Test", "Password", UsernamePasswordAuthenticationToken token = UsernamePasswordAuthenticationToken.authenticated("Test",
AuthorityUtils.createAuthorityList("ROLE_SOMEOTHERROLE")); "Password", AuthorityUtils.createAuthorityList("ROLE_SOMEOTHERROLE"));
SecurityContextHolder.getContext().setAuthentication(token); SecurityContextHolder.getContext().setAuthentication(token);
assertThatExceptionOfType(AccessDeniedException.class).isThrownBy(this.target::someAdminMethod); assertThatExceptionOfType(AccessDeniedException.class).isThrownBy(this.target::someAdminMethod);
} }
@Test @Test
public void hasAnyRoleAddsDefaultPrefix() { public void hasAnyRoleAddsDefaultPrefix() {
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("Test", "Password", UsernamePasswordAuthenticationToken token = UsernamePasswordAuthenticationToken.authenticated("Test",
AuthorityUtils.createAuthorityList("ROLE_USER")); "Password", AuthorityUtils.createAuthorityList("ROLE_USER"));
SecurityContextHolder.getContext().setAuthentication(token); SecurityContextHolder.getContext().setAuthentication(token);
this.target.rolesAllowedUser(); this.target.rolesAllowedUser();
} }

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2017 the original author or authors. * Copyright 2002-2022 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -59,7 +59,7 @@ public class MethodSecurityBeanDefinitionParserTests {
private static final String CONFIG_LOCATION_PREFIX = "classpath:org/springframework/security/config/method/MethodSecurityBeanDefinitionParserTests"; private static final String CONFIG_LOCATION_PREFIX = "classpath:org/springframework/security/config/method/MethodSecurityBeanDefinitionParserTests";
private final UsernamePasswordAuthenticationToken bob = new UsernamePasswordAuthenticationToken("bob", private final UsernamePasswordAuthenticationToken bob = UsernamePasswordAuthenticationToken.unauthenticated("bob",
"bobspassword"); "bobspassword");
@Autowired(required = false) @Autowired(required = false)

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2016 the original author or authors. * Copyright 2002-2022 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -73,16 +73,16 @@ public class SecuredAnnotationDrivenBeanDefinitionParserTests {
@Test @Test
public void targetShouldAllowProtectedMethodInvocationWithCorrectRole() { public void targetShouldAllowProtectedMethodInvocationWithCorrectRole() {
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("Test", "Password", UsernamePasswordAuthenticationToken token = UsernamePasswordAuthenticationToken.authenticated("Test",
AuthorityUtils.createAuthorityList("ROLE_USER")); "Password", AuthorityUtils.createAuthorityList("ROLE_USER"));
SecurityContextHolder.getContext().setAuthentication(token); SecurityContextHolder.getContext().setAuthentication(token);
this.target.someUserMethod1(); this.target.someUserMethod1();
} }
@Test @Test
public void targetShouldPreventProtectedMethodInvocationWithIncorrectRole() { public void targetShouldPreventProtectedMethodInvocationWithIncorrectRole() {
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("Test", "Password", UsernamePasswordAuthenticationToken token = UsernamePasswordAuthenticationToken.authenticated("Test",
AuthorityUtils.createAuthorityList("ROLE_SOMEOTHER")); "Password", AuthorityUtils.createAuthorityList("ROLE_SOMEOTHER"));
SecurityContextHolder.getContext().setAuthentication(token); SecurityContextHolder.getContext().setAuthentication(token);
assertThatExceptionOfType(AccessDeniedException.class).isThrownBy(this.target::someAdminMethod); assertThatExceptionOfType(AccessDeniedException.class).isThrownBy(this.target::someAdminMethod);
} }

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2020 the original author or authors. * Copyright 2002-2022 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -117,7 +117,7 @@ public abstract class AbstractUserDetailsReactiveAuthenticationManager
} }
private UsernamePasswordAuthenticationToken createUsernamePasswordAuthenticationToken(UserDetails userDetails) { private UsernamePasswordAuthenticationToken createUsernamePasswordAuthenticationToken(UserDetails userDetails) {
return new UsernamePasswordAuthenticationToken(userDetails, userDetails.getPassword(), return UsernamePasswordAuthenticationToken.authenticated(userDetails, userDetails.getPassword(),
userDetails.getAuthorities()); userDetails.getAuthorities());
} }

View File

@ -32,6 +32,7 @@ import org.springframework.util.Assert;
* <code>String</code>. * <code>String</code>.
* *
* @author Ben Alex * @author Ben Alex
* @author Norbert Nowak
*/ */
public class UsernamePasswordAuthenticationToken extends AbstractAuthenticationToken { public class UsernamePasswordAuthenticationToken extends AbstractAuthenticationToken {
@ -71,6 +72,33 @@ public class UsernamePasswordAuthenticationToken extends AbstractAuthenticationT
super.setAuthenticated(true); // must use super, as we override super.setAuthenticated(true); // must use super, as we override
} }
/**
* This factory method can be safely used by any code that wishes to create a
* unauthenticated <code>UsernamePasswordAuthenticationToken</code>.
* @param principal
* @param credentials
* @return UsernamePasswordAuthenticationToken with false isAuthenticated() result
*
* @since 5.7
*/
public static UsernamePasswordAuthenticationToken unauthenticated(Object principal, Object credentials) {
return new UsernamePasswordAuthenticationToken(principal, credentials);
}
/**
* This factory method can be safely used by any code that wishes to create a
* authenticated <code>UsernamePasswordAuthenticationToken</code>.
* @param principal
* @param credentials
* @return UsernamePasswordAuthenticationToken with true isAuthenticated() result
*
* @since 5.7
*/
public static UsernamePasswordAuthenticationToken authenticated(Object principal, Object credentials,
Collection<? extends GrantedAuthority> authorities) {
return new UsernamePasswordAuthenticationToken(principal, credentials, authorities);
}
@Override @Override
public Object getCredentials() { public Object getCredentials() {
return this.credentials; return this.credentials;

View File

@ -193,7 +193,7 @@ public abstract class AbstractUserDetailsAuthenticationProvider
// so subsequent attempts are successful even with encoded passwords. // so subsequent attempts are successful even with encoded passwords.
// Also ensure we return the original getDetails(), so that future // Also ensure we return the original getDetails(), so that future
// authentication events after cache expiry contain the details // authentication events after cache expiry contain the details
UsernamePasswordAuthenticationToken result = new UsernamePasswordAuthenticationToken(principal, UsernamePasswordAuthenticationToken result = UsernamePasswordAuthenticationToken.authenticated(principal,
authentication.getCredentials(), this.authoritiesMapper.mapAuthorities(user.getAuthorities())); authentication.getCredentials(), this.authoritiesMapper.mapAuthorities(user.getAuthorities()));
result.setDetails(authentication.getDetails()); result.setDetails(authentication.getDetails());
this.logger.debug("Authenticated user"); this.logger.debug("Authenticated user");

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2015-2018 the original author or authors. * Copyright 2015-2022 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -78,8 +78,8 @@ class UsernamePasswordAuthenticationTokenDeserializer extends JsonDeserializer<U
List<GrantedAuthority> authorities = mapper.readValue(readJsonNode(jsonNode, "authorities").traverse(mapper), List<GrantedAuthority> authorities = mapper.readValue(readJsonNode(jsonNode, "authorities").traverse(mapper),
GRANTED_AUTHORITY_LIST); GRANTED_AUTHORITY_LIST);
UsernamePasswordAuthenticationToken token = (!authenticated) UsernamePasswordAuthenticationToken token = (!authenticated)
? new UsernamePasswordAuthenticationToken(principal, credentials) ? UsernamePasswordAuthenticationToken.unauthenticated(principal, credentials)
: new UsernamePasswordAuthenticationToken(principal, credentials, authorities); : UsernamePasswordAuthenticationToken.authenticated(principal, credentials, authorities);
JsonNode detailsNode = readJsonNode(jsonNode, "details"); JsonNode detailsNode = readJsonNode(jsonNode, "details");
if (detailsNode.isNull() || detailsNode.isMissingNode()) { if (detailsNode.isNull() || detailsNode.isMissingNode()) {
token.setDetails(null); token.setDetails(null);

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2021 the original author or authors. * Copyright 2002-2022 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -125,7 +125,8 @@ public class InMemoryUserDetailsManager implements UserDetailsManager, UserDetai
// supplied password. // supplied password.
if (this.authenticationManager != null) { if (this.authenticationManager != null) {
this.logger.debug(LogMessage.format("Reauthenticating user '%s' for password change request.", username)); this.logger.debug(LogMessage.format("Reauthenticating user '%s' for password change request.", username));
this.authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(username, oldPassword)); this.authenticationManager
.authenticate(UsernamePasswordAuthenticationToken.unauthenticated(username, oldPassword));
} }
else { else {
this.logger.debug("No authentication manager set. Password won't be re-checked."); this.logger.debug("No authentication manager set. Password won't be re-checked.");

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2021 the original author or authors. * Copyright 2002-2022 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -271,7 +271,8 @@ public class JdbcUserDetailsManager extends JdbcDaoImpl implements UserDetailsMa
// supplied password. // supplied password.
if (this.authenticationManager != null) { if (this.authenticationManager != null) {
this.logger.debug(LogMessage.format("Reauthenticating user '%s' for password change request.", username)); this.logger.debug(LogMessage.format("Reauthenticating user '%s' for password change request.", username));
this.authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(username, oldPassword)); this.authenticationManager
.authenticate(UsernamePasswordAuthenticationToken.unauthenticated(username, oldPassword));
} }
else { else {
this.logger.debug("No authentication manager set. Password won't be re-checked."); this.logger.debug("No authentication manager set. Password won't be re-checked.");
@ -287,8 +288,8 @@ public class JdbcUserDetailsManager extends JdbcDaoImpl implements UserDetailsMa
protected Authentication createNewAuthentication(Authentication currentAuth, String newPassword) { protected Authentication createNewAuthentication(Authentication currentAuth, String newPassword) {
UserDetails user = loadUserByUsername(currentAuth.getName()); UserDetails user = loadUserByUsername(currentAuth.getName());
UsernamePasswordAuthenticationToken newAuthentication = new UsernamePasswordAuthenticationToken(user, null, UsernamePasswordAuthenticationToken newAuthentication = UsernamePasswordAuthenticationToken.authenticated(user,
user.getAuthorities()); null, user.getAuthorities());
newAuthentication.setDetails(currentAuth.getDetails()); newAuthentication.setDetails(currentAuth.getDetails());
return newAuthentication; return newAuthentication;
} }

View File

@ -34,7 +34,8 @@ import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException
*/ */
public class AuthorizationFailureEventTests { public class AuthorizationFailureEventTests {
private final UsernamePasswordAuthenticationToken foo = new UsernamePasswordAuthenticationToken("foo", "bar"); private final UsernamePasswordAuthenticationToken foo = UsernamePasswordAuthenticationToken.unauthenticated("foo",
"bar");
private List<ConfigAttribute> attributes = SecurityConfig.createList("TEST"); private List<ConfigAttribute> attributes = SecurityConfig.createList("TEST");

View File

@ -34,13 +34,13 @@ public class AuthorizedEventTests {
@Test @Test
public void testRejectsNulls() { public void testRejectsNulls() {
assertThatIllegalArgumentException().isThrownBy(() -> new AuthorizedEvent(null, assertThatIllegalArgumentException().isThrownBy(() -> new AuthorizedEvent(null,
SecurityConfig.createList("TEST"), new UsernamePasswordAuthenticationToken("foo", "bar"))); SecurityConfig.createList("TEST"), UsernamePasswordAuthenticationToken.unauthenticated("foo", "bar")));
} }
@Test @Test
public void testRejectsNulls2() { public void testRejectsNulls2() {
assertThatIllegalArgumentException().isThrownBy(() -> new AuthorizedEvent(new SimpleMethodInvocation(), null, assertThatIllegalArgumentException().isThrownBy(() -> new AuthorizedEvent(new SimpleMethodInvocation(), null,
new UsernamePasswordAuthenticationToken("foo", "bar"))); UsernamePasswordAuthenticationToken.unauthenticated("foo", "bar")));
} }
@Test @Test

View File

@ -44,8 +44,8 @@ public class RunAsManagerImplTests {
@Test @Test
public void testDoesNotReturnAdditionalAuthoritiesIfCalledWithoutARunAsSetting() { public void testDoesNotReturnAdditionalAuthoritiesIfCalledWithoutARunAsSetting() {
UsernamePasswordAuthenticationToken inputToken = new UsernamePasswordAuthenticationToken("Test", "Password", UsernamePasswordAuthenticationToken inputToken = UsernamePasswordAuthenticationToken.authenticated("Test",
AuthorityUtils.createAuthorityList("ROLE_ONE", "ROLE_TWO")); "Password", AuthorityUtils.createAuthorityList("ROLE_ONE", "ROLE_TWO"));
RunAsManagerImpl runAs = new RunAsManagerImpl(); RunAsManagerImpl runAs = new RunAsManagerImpl();
runAs.setKey("my_password"); runAs.setKey("my_password");
Authentication resultingToken = runAs.buildRunAs(inputToken, new Object(), Authentication resultingToken = runAs.buildRunAs(inputToken, new Object(),
@ -55,8 +55,8 @@ public class RunAsManagerImplTests {
@Test @Test
public void testRespectsRolePrefix() { public void testRespectsRolePrefix() {
UsernamePasswordAuthenticationToken inputToken = new UsernamePasswordAuthenticationToken("Test", "Password", UsernamePasswordAuthenticationToken inputToken = UsernamePasswordAuthenticationToken.authenticated("Test",
AuthorityUtils.createAuthorityList("ONE", "TWO")); "Password", AuthorityUtils.createAuthorityList("ONE", "TWO"));
RunAsManagerImpl runAs = new RunAsManagerImpl(); RunAsManagerImpl runAs = new RunAsManagerImpl();
runAs.setKey("my_password"); runAs.setKey("my_password");
runAs.setRolePrefix("FOOBAR_"); runAs.setRolePrefix("FOOBAR_");
@ -75,8 +75,8 @@ public class RunAsManagerImplTests {
@Test @Test
public void testReturnsAdditionalGrantedAuthorities() { public void testReturnsAdditionalGrantedAuthorities() {
UsernamePasswordAuthenticationToken inputToken = new UsernamePasswordAuthenticationToken("Test", "Password", UsernamePasswordAuthenticationToken inputToken = UsernamePasswordAuthenticationToken.authenticated("Test",
AuthorityUtils.createAuthorityList("ROLE_ONE", "ROLE_TWO")); "Password", AuthorityUtils.createAuthorityList("ROLE_ONE", "ROLE_TWO"));
RunAsManagerImpl runAs = new RunAsManagerImpl(); RunAsManagerImpl runAs = new RunAsManagerImpl();
runAs.setKey("my_password"); runAs.setKey("my_password");
Authentication result = runAs.buildRunAs(inputToken, new Object(), Authentication result = runAs.buildRunAs(inputToken, new Object(),

View File

@ -44,7 +44,7 @@ public class AuthenticatedVoterTests {
} }
private Authentication createFullyAuthenticated() { private Authentication createFullyAuthenticated() {
return new UsernamePasswordAuthenticationToken("ignored", "ignored", return UsernamePasswordAuthenticationToken.authenticated("ignored", "ignored",
AuthorityUtils.createAuthorityList("ignored")); AuthorityUtils.createAuthorityList("ignored"));
} }

View File

@ -66,12 +66,13 @@ public class ProviderManagerTests {
@Test @Test
public void credentialsAreClearedByDefault() { public void credentialsAreClearedByDefault() {
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("Test", "Password"); UsernamePasswordAuthenticationToken token = UsernamePasswordAuthenticationToken.unauthenticated("Test",
"Password");
ProviderManager mgr = makeProviderManager(); ProviderManager mgr = makeProviderManager();
Authentication result = mgr.authenticate(token); Authentication result = mgr.authenticate(token);
assertThat(result.getCredentials()).isNull(); assertThat(result.getCredentials()).isNull();
mgr.setEraseCredentialsAfterAuthentication(false); mgr.setEraseCredentialsAfterAuthentication(false);
token = new UsernamePasswordAuthenticationToken("Test", "Password"); token = UsernamePasswordAuthenticationToken.unauthenticated("Test", "Password");
result = mgr.authenticate(token); result = mgr.authenticate(token);
assertThat(result.getCredentials()).isNotNull(); assertThat(result.getCredentials()).isNotNull();
} }

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2017 the original author or authors. * Copyright 2002-2022 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -72,7 +72,7 @@ public class ReactiveUserDetailsServiceAuthenticationManagerTests {
@Test @Test
public void authenticateWhenUserNotFoundThenBadCredentials() { public void authenticateWhenUserNotFoundThenBadCredentials() {
given(this.repository.findByUsername(this.username)).willReturn(Mono.empty()); given(this.repository.findByUsername(this.username)).willReturn(Mono.empty());
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(this.username, UsernamePasswordAuthenticationToken token = UsernamePasswordAuthenticationToken.unauthenticated(this.username,
this.password); this.password);
Mono<Authentication> authentication = this.manager.authenticate(token); Mono<Authentication> authentication = this.manager.authenticate(token);
// @formatter:off // @formatter:off
@ -91,7 +91,7 @@ public class ReactiveUserDetailsServiceAuthenticationManagerTests {
.build(); .build();
// @formatter:on // @formatter:on
given(this.repository.findByUsername(user.getUsername())).willReturn(Mono.just(user)); given(this.repository.findByUsername(user.getUsername())).willReturn(Mono.just(user));
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(this.username, UsernamePasswordAuthenticationToken token = UsernamePasswordAuthenticationToken.unauthenticated(this.username,
this.password + "INVALID"); this.password + "INVALID");
Mono<Authentication> authentication = this.manager.authenticate(token); Mono<Authentication> authentication = this.manager.authenticate(token);
// @formatter:off // @formatter:off
@ -110,7 +110,7 @@ public class ReactiveUserDetailsServiceAuthenticationManagerTests {
.build(); .build();
// @formatter:on // @formatter:on
given(this.repository.findByUsername(user.getUsername())).willReturn(Mono.just(user)); given(this.repository.findByUsername(user.getUsername())).willReturn(Mono.just(user));
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(this.username, UsernamePasswordAuthenticationToken token = UsernamePasswordAuthenticationToken.unauthenticated(this.username,
this.password); this.password);
Authentication authentication = this.manager.authenticate(token).block(); Authentication authentication = this.manager.authenticate(token).block();
assertThat(authentication).isEqualTo(authentication); assertThat(authentication).isEqualTo(authentication);
@ -122,7 +122,7 @@ public class ReactiveUserDetailsServiceAuthenticationManagerTests {
given(this.passwordEncoder.matches(any(), any())).willReturn(true); given(this.passwordEncoder.matches(any(), any())).willReturn(true);
User user = new User(this.username, this.password, AuthorityUtils.createAuthorityList("ROLE_USER")); User user = new User(this.username, this.password, AuthorityUtils.createAuthorityList("ROLE_USER"));
given(this.repository.findByUsername(user.getUsername())).willReturn(Mono.just(user)); given(this.repository.findByUsername(user.getUsername())).willReturn(Mono.just(user));
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(this.username, UsernamePasswordAuthenticationToken token = UsernamePasswordAuthenticationToken.unauthenticated(this.username,
this.password); this.password);
Authentication authentication = this.manager.authenticate(token).block(); Authentication authentication = this.manager.authenticate(token).block();
assertThat(authentication).isEqualTo(authentication); assertThat(authentication).isEqualTo(authentication);
@ -134,7 +134,7 @@ public class ReactiveUserDetailsServiceAuthenticationManagerTests {
given(this.passwordEncoder.matches(any(), any())).willReturn(false); given(this.passwordEncoder.matches(any(), any())).willReturn(false);
User user = new User(this.username, this.password, AuthorityUtils.createAuthorityList("ROLE_USER")); User user = new User(this.username, this.password, AuthorityUtils.createAuthorityList("ROLE_USER"));
given(this.repository.findByUsername(user.getUsername())).willReturn(Mono.just(user)); given(this.repository.findByUsername(user.getUsername())).willReturn(Mono.just(user));
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(this.username, UsernamePasswordAuthenticationToken token = UsernamePasswordAuthenticationToken.unauthenticated(this.username,
this.password); this.password);
Mono<Authentication> authentication = this.manager.authenticate(token); Mono<Authentication> authentication = this.manager.authenticate(token);
// @formatter:off // @formatter:off

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2018 the original author or authors. * Copyright 2002-2022 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -35,7 +35,7 @@ public class TestAuthentication extends PasswordEncodedUser {
} }
public static Authentication autheticated(UserDetails user) { public static Authentication autheticated(UserDetails user) {
return new UsernamePasswordAuthenticationToken(user, null, user.getAuthorities()); return UsernamePasswordAuthenticationToken.authenticated(user, null, user.getAuthorities());
} }
} }

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2021 the original author or authors. * Copyright 2002-2022 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -95,7 +95,7 @@ public class UserDetailsRepositoryReactiveAuthenticationManagerTests {
given(this.encoder.matches(any(), any())).willReturn(true); given(this.encoder.matches(any(), any())).willReturn(true);
this.manager.setScheduler(this.scheduler); this.manager.setScheduler(this.scheduler);
this.manager.setPasswordEncoder(this.encoder); this.manager.setPasswordEncoder(this.encoder);
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(this.user, UsernamePasswordAuthenticationToken token = UsernamePasswordAuthenticationToken.unauthenticated(this.user,
this.user.getPassword()); this.user.getPassword());
Authentication result = this.manager.authenticate(token).block(); Authentication result = this.manager.authenticate(token).block();
verify(this.scheduler).schedule(any()); verify(this.scheduler).schedule(any());
@ -111,7 +111,7 @@ public class UserDetailsRepositoryReactiveAuthenticationManagerTests {
given(this.userDetailsPasswordService.updatePassword(any(), any())).willReturn(Mono.just(this.user)); given(this.userDetailsPasswordService.updatePassword(any(), any())).willReturn(Mono.just(this.user));
this.manager.setPasswordEncoder(this.encoder); this.manager.setPasswordEncoder(this.encoder);
this.manager.setUserDetailsPasswordService(this.userDetailsPasswordService); this.manager.setUserDetailsPasswordService(this.userDetailsPasswordService);
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(this.user, UsernamePasswordAuthenticationToken token = UsernamePasswordAuthenticationToken.unauthenticated(this.user,
this.user.getPassword()); this.user.getPassword());
Authentication result = this.manager.authenticate(token).block(); Authentication result = this.manager.authenticate(token).block();
verify(this.encoder).encode(this.user.getPassword()); verify(this.encoder).encode(this.user.getPassword());
@ -124,7 +124,7 @@ public class UserDetailsRepositoryReactiveAuthenticationManagerTests {
given(this.encoder.matches(any(), any())).willReturn(false); given(this.encoder.matches(any(), any())).willReturn(false);
this.manager.setPasswordEncoder(this.encoder); this.manager.setPasswordEncoder(this.encoder);
this.manager.setUserDetailsPasswordService(this.userDetailsPasswordService); this.manager.setUserDetailsPasswordService(this.userDetailsPasswordService);
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(this.user, UsernamePasswordAuthenticationToken token = UsernamePasswordAuthenticationToken.unauthenticated(this.user,
this.user.getPassword()); this.user.getPassword());
assertThatExceptionOfType(BadCredentialsException.class) assertThatExceptionOfType(BadCredentialsException.class)
.isThrownBy(() -> this.manager.authenticate(token).block()); .isThrownBy(() -> this.manager.authenticate(token).block());
@ -138,7 +138,7 @@ public class UserDetailsRepositoryReactiveAuthenticationManagerTests {
given(this.encoder.upgradeEncoding(any())).willReturn(false); given(this.encoder.upgradeEncoding(any())).willReturn(false);
this.manager.setPasswordEncoder(this.encoder); this.manager.setPasswordEncoder(this.encoder);
this.manager.setUserDetailsPasswordService(this.userDetailsPasswordService); this.manager.setUserDetailsPasswordService(this.userDetailsPasswordService);
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(this.user, UsernamePasswordAuthenticationToken token = UsernamePasswordAuthenticationToken.unauthenticated(this.user,
this.user.getPassword()); this.user.getPassword());
Authentication result = this.manager.authenticate(token).block(); Authentication result = this.manager.authenticate(token).block();
verifyZeroInteractions(this.userDetailsPasswordService); verifyZeroInteractions(this.userDetailsPasswordService);
@ -152,8 +152,8 @@ public class UserDetailsRepositoryReactiveAuthenticationManagerTests {
this.manager.setPasswordEncoder(this.encoder); this.manager.setPasswordEncoder(this.encoder);
this.manager.setPostAuthenticationChecks(this.postAuthenticationChecks); this.manager.setPostAuthenticationChecks(this.postAuthenticationChecks);
assertThatExceptionOfType(LockedException.class).isThrownBy(() -> this.manager assertThatExceptionOfType(LockedException.class).isThrownBy(() -> this.manager
.authenticate(new UsernamePasswordAuthenticationToken(this.user, this.user.getPassword())).block()) .authenticate(UsernamePasswordAuthenticationToken.unauthenticated(this.user, this.user.getPassword()))
.withMessage("account is locked"); .block()).withMessage("account is locked");
verify(this.postAuthenticationChecks).check(eq(this.user)); verify(this.postAuthenticationChecks).check(eq(this.user));
} }
@ -162,7 +162,7 @@ public class UserDetailsRepositoryReactiveAuthenticationManagerTests {
given(this.userDetailsService.findByUsername(any())).willReturn(Mono.just(this.user)); given(this.userDetailsService.findByUsername(any())).willReturn(Mono.just(this.user));
given(this.encoder.matches(any(), any())).willReturn(true); given(this.encoder.matches(any(), any())).willReturn(true);
this.manager.setPasswordEncoder(this.encoder); this.manager.setPasswordEncoder(this.encoder);
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(this.user, UsernamePasswordAuthenticationToken token = UsernamePasswordAuthenticationToken.unauthenticated(this.user,
this.user.getPassword()); this.user.getPassword());
this.manager.authenticate(token).block(); this.manager.authenticate(token).block();
verifyZeroInteractions(this.postAuthenticationChecks); verifyZeroInteractions(this.postAuthenticationChecks);
@ -179,7 +179,7 @@ public class UserDetailsRepositoryReactiveAuthenticationManagerTests {
.build(); .build();
// @formatter:on // @formatter:on
given(this.userDetailsService.findByUsername(any())).willReturn(Mono.just(expiredUser)); given(this.userDetailsService.findByUsername(any())).willReturn(Mono.just(expiredUser));
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(expiredUser, UsernamePasswordAuthenticationToken token = UsernamePasswordAuthenticationToken.unauthenticated(expiredUser,
expiredUser.getPassword()); expiredUser.getPassword());
assertThatExceptionOfType(AccountExpiredException.class) assertThatExceptionOfType(AccountExpiredException.class)
.isThrownBy(() -> this.manager.authenticate(token).block()); .isThrownBy(() -> this.manager.authenticate(token).block());
@ -196,7 +196,7 @@ public class UserDetailsRepositoryReactiveAuthenticationManagerTests {
.build(); .build();
// @formatter:on // @formatter:on
given(this.userDetailsService.findByUsername(any())).willReturn(Mono.just(lockedUser)); given(this.userDetailsService.findByUsername(any())).willReturn(Mono.just(lockedUser));
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(lockedUser, UsernamePasswordAuthenticationToken token = UsernamePasswordAuthenticationToken.unauthenticated(lockedUser,
lockedUser.getPassword()); lockedUser.getPassword());
assertThatExceptionOfType(LockedException.class).isThrownBy(() -> this.manager.authenticate(token).block()); assertThatExceptionOfType(LockedException.class).isThrownBy(() -> this.manager.authenticate(token).block());
} }
@ -212,7 +212,7 @@ public class UserDetailsRepositoryReactiveAuthenticationManagerTests {
.build(); .build();
// @formatter:on // @formatter:on
given(this.userDetailsService.findByUsername(any())).willReturn(Mono.just(disabledUser)); given(this.userDetailsService.findByUsername(any())).willReturn(Mono.just(disabledUser));
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(disabledUser, UsernamePasswordAuthenticationToken token = UsernamePasswordAuthenticationToken.unauthenticated(disabledUser,
disabledUser.getPassword()); disabledUser.getPassword());
assertThatExceptionOfType(DisabledException.class).isThrownBy(() -> this.manager.authenticate(token).block()); assertThatExceptionOfType(DisabledException.class).isThrownBy(() -> this.manager.authenticate(token).block());
} }

View File

@ -33,8 +33,8 @@ public class UsernamePasswordAuthenticationTokenTests {
@Test @Test
public void authenticatedPropertyContractIsSatisfied() { public void authenticatedPropertyContractIsSatisfied() {
UsernamePasswordAuthenticationToken grantedToken = new UsernamePasswordAuthenticationToken("Test", "Password", UsernamePasswordAuthenticationToken grantedToken = UsernamePasswordAuthenticationToken.authenticated("Test",
AuthorityUtils.NO_AUTHORITIES); "Password", AuthorityUtils.NO_AUTHORITIES);
// check default given we passed some GrantedAuthorty[]s (well, we passed empty // check default given we passed some GrantedAuthorty[]s (well, we passed empty
// list) // list)
assertThat(grantedToken.isAuthenticated()).isTrue(); assertThat(grantedToken.isAuthenticated()).isTrue();
@ -44,8 +44,8 @@ public class UsernamePasswordAuthenticationTokenTests {
assertThat(!grantedToken.isAuthenticated()).isTrue(); assertThat(!grantedToken.isAuthenticated()).isTrue();
// Now let's create a UsernamePasswordAuthenticationToken without any // Now let's create a UsernamePasswordAuthenticationToken without any
// GrantedAuthorty[]s (different constructor) // GrantedAuthorty[]s (different constructor)
UsernamePasswordAuthenticationToken noneGrantedToken = new UsernamePasswordAuthenticationToken("Test", UsernamePasswordAuthenticationToken noneGrantedToken = UsernamePasswordAuthenticationToken
"Password"); .unauthenticated("Test", "Password");
assertThat(!noneGrantedToken.isAuthenticated()).isTrue(); assertThat(!noneGrantedToken.isAuthenticated()).isTrue();
// check we're allowed to still set it to untrusted // check we're allowed to still set it to untrusted
noneGrantedToken.setAuthenticated(false); noneGrantedToken.setAuthenticated(false);
@ -56,8 +56,8 @@ public class UsernamePasswordAuthenticationTokenTests {
@Test @Test
public void gettersReturnCorrectData() { public void gettersReturnCorrectData() {
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("Test", "Password", UsernamePasswordAuthenticationToken token = UsernamePasswordAuthenticationToken.authenticated("Test",
AuthorityUtils.createAuthorityList("ROLE_ONE", "ROLE_TWO")); "Password", AuthorityUtils.createAuthorityList("ROLE_ONE", "ROLE_TWO"));
assertThat(token.getPrincipal()).isEqualTo("Test"); assertThat(token.getPrincipal()).isEqualTo("Test");
assertThat(token.getCredentials()).isEqualTo("Password"); assertThat(token.getCredentials()).isEqualTo("Password");
assertThat(AuthorityUtils.authorityListToSet(token.getAuthorities())).contains("ROLE_ONE"); assertThat(AuthorityUtils.authorityListToSet(token.getAuthorities())).contains("ROLE_ONE");
@ -71,4 +71,18 @@ public class UsernamePasswordAuthenticationTokenTests {
.isThrownBy(() -> clazz.getDeclaredConstructor((Class[]) null)); .isThrownBy(() -> clazz.getDeclaredConstructor((Class[]) null));
} }
@Test
public void unauthenticatedFactoryMethodResultsUnauthenticatedToken() {
UsernamePasswordAuthenticationToken grantedToken = UsernamePasswordAuthenticationToken.unauthenticated("Test",
"Password");
assertThat(grantedToken.isAuthenticated()).isFalse();
}
@Test
public void authenticatedFactoryMethodResultsAuthenticatedToken() {
UsernamePasswordAuthenticationToken grantedToken = UsernamePasswordAuthenticationToken.authenticated("Test",
"Password", AuthorityUtils.NO_AUTHORITIES);
assertThat(grantedToken.isAuthenticated()).isTrue();
}
} }

View File

@ -81,8 +81,8 @@ public class AnonymousAuthenticationTokenTests {
@Test @Test
public void testNotEqualsDueToDifferentAuthenticationClass() { public void testNotEqualsDueToDifferentAuthenticationClass() {
AnonymousAuthenticationToken token1 = new AnonymousAuthenticationToken("key", "Test", ROLES_12); AnonymousAuthenticationToken token1 = new AnonymousAuthenticationToken("key", "Test", ROLES_12);
UsernamePasswordAuthenticationToken token2 = new UsernamePasswordAuthenticationToken("Test", "Password", UsernamePasswordAuthenticationToken token2 = UsernamePasswordAuthenticationToken.authenticated("Test",
ROLES_12); "Password", ROLES_12);
assertThat(token1.equals(token2)).isFalse(); assertThat(token1.equals(token2)).isFalse();
} }

View File

@ -75,7 +75,7 @@ public class DaoAuthenticationProviderTests {
@Test @Test
public void testAuthenticateFailsForIncorrectPasswordCase() { public void testAuthenticateFailsForIncorrectPasswordCase() {
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("rod", "KOala"); UsernamePasswordAuthenticationToken token = UsernamePasswordAuthenticationToken.unauthenticated("rod", "KOala");
DaoAuthenticationProvider provider = createProvider(); DaoAuthenticationProvider provider = createProvider();
provider.setUserDetailsService(new MockUserDetailsServiceUserRod()); provider.setUserDetailsService(new MockUserDetailsServiceUserRod());
provider.setUserCache(new MockUserCache()); provider.setUserCache(new MockUserCache());
@ -88,14 +88,16 @@ public class DaoAuthenticationProviderTests {
DaoAuthenticationProvider provider = createProvider(); DaoAuthenticationProvider provider = createProvider();
provider.setUserDetailsService(new MockUserDetailsServiceUserRod()); provider.setUserDetailsService(new MockUserDetailsServiceUserRod());
provider.setUserCache(new MockUserCache()); provider.setUserCache(new MockUserCache());
UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken("rod", null); UsernamePasswordAuthenticationToken authenticationToken = UsernamePasswordAuthenticationToken
.unauthenticated("rod", null);
assertThatExceptionOfType(BadCredentialsException.class) assertThatExceptionOfType(BadCredentialsException.class)
.isThrownBy(() -> provider.authenticate(authenticationToken)); .isThrownBy(() -> provider.authenticate(authenticationToken));
} }
@Test @Test
public void testAuthenticateFailsIfAccountExpired() { public void testAuthenticateFailsIfAccountExpired() {
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("peter", "opal"); UsernamePasswordAuthenticationToken token = UsernamePasswordAuthenticationToken.unauthenticated("peter",
"opal");
DaoAuthenticationProvider provider = createProvider(); DaoAuthenticationProvider provider = createProvider();
provider.setUserDetailsService(new MockUserDetailsServiceUserPeterAccountExpired()); provider.setUserDetailsService(new MockUserDetailsServiceUserPeterAccountExpired());
provider.setUserCache(new MockUserCache()); provider.setUserCache(new MockUserCache());
@ -104,7 +106,8 @@ public class DaoAuthenticationProviderTests {
@Test @Test
public void testAuthenticateFailsIfAccountLocked() { public void testAuthenticateFailsIfAccountLocked() {
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("peter", "opal"); UsernamePasswordAuthenticationToken token = UsernamePasswordAuthenticationToken.unauthenticated("peter",
"opal");
DaoAuthenticationProvider provider = createProvider(); DaoAuthenticationProvider provider = createProvider();
provider.setUserDetailsService(new MockUserDetailsServiceUserPeterAccountLocked()); provider.setUserDetailsService(new MockUserDetailsServiceUserPeterAccountLocked());
provider.setUserCache(new MockUserCache()); provider.setUserCache(new MockUserCache());
@ -116,17 +119,18 @@ public class DaoAuthenticationProviderTests {
DaoAuthenticationProvider provider = createProvider(); DaoAuthenticationProvider provider = createProvider();
provider.setUserDetailsService(new MockUserDetailsServiceUserPeterCredentialsExpired()); provider.setUserDetailsService(new MockUserDetailsServiceUserPeterCredentialsExpired());
provider.setUserCache(new MockUserCache()); provider.setUserCache(new MockUserCache());
assertThatExceptionOfType(CredentialsExpiredException.class) assertThatExceptionOfType(CredentialsExpiredException.class).isThrownBy(
.isThrownBy(() -> provider.authenticate(new UsernamePasswordAuthenticationToken("peter", "opal"))); () -> provider.authenticate(UsernamePasswordAuthenticationToken.unauthenticated("peter", "opal")));
// Check that wrong password causes BadCredentialsException, rather than // Check that wrong password causes BadCredentialsException, rather than
// CredentialsExpiredException // CredentialsExpiredException
assertThatExceptionOfType(BadCredentialsException.class).isThrownBy( assertThatExceptionOfType(BadCredentialsException.class).isThrownBy(() -> provider
() -> provider.authenticate(new UsernamePasswordAuthenticationToken("peter", "wrong_password"))); .authenticate(UsernamePasswordAuthenticationToken.unauthenticated("peter", "wrong_password")));
} }
@Test @Test
public void testAuthenticateFailsIfUserDisabled() { public void testAuthenticateFailsIfUserDisabled() {
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("peter", "opal"); UsernamePasswordAuthenticationToken token = UsernamePasswordAuthenticationToken.unauthenticated("peter",
"opal");
DaoAuthenticationProvider provider = createProvider(); DaoAuthenticationProvider provider = createProvider();
provider.setUserDetailsService(new MockUserDetailsServiceUserPeter()); provider.setUserDetailsService(new MockUserDetailsServiceUserPeter());
provider.setUserCache(new MockUserCache()); provider.setUserCache(new MockUserCache());
@ -135,7 +139,7 @@ public class DaoAuthenticationProviderTests {
@Test @Test
public void testAuthenticateFailsWhenAuthenticationDaoHasBackendFailure() { public void testAuthenticateFailsWhenAuthenticationDaoHasBackendFailure() {
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("rod", "koala"); UsernamePasswordAuthenticationToken token = UsernamePasswordAuthenticationToken.unauthenticated("rod", "koala");
DaoAuthenticationProvider provider = createProvider(); DaoAuthenticationProvider provider = createProvider();
provider.setUserDetailsService(new MockUserDetailsServiceSimulateBackendError()); provider.setUserDetailsService(new MockUserDetailsServiceSimulateBackendError());
provider.setUserCache(new MockUserCache()); provider.setUserCache(new MockUserCache());
@ -145,7 +149,7 @@ public class DaoAuthenticationProviderTests {
@Test @Test
public void testAuthenticateFailsWithEmptyUsername() { public void testAuthenticateFailsWithEmptyUsername() {
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(null, "koala"); UsernamePasswordAuthenticationToken token = UsernamePasswordAuthenticationToken.unauthenticated(null, "koala");
DaoAuthenticationProvider provider = createProvider(); DaoAuthenticationProvider provider = createProvider();
provider.setUserDetailsService(new MockUserDetailsServiceUserRod()); provider.setUserDetailsService(new MockUserDetailsServiceUserRod());
provider.setUserCache(new MockUserCache()); provider.setUserCache(new MockUserCache());
@ -154,7 +158,8 @@ public class DaoAuthenticationProviderTests {
@Test @Test
public void testAuthenticateFailsWithInvalidPassword() { public void testAuthenticateFailsWithInvalidPassword() {
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("rod", "INVALID_PASSWORD"); UsernamePasswordAuthenticationToken token = UsernamePasswordAuthenticationToken.unauthenticated("rod",
"INVALID_PASSWORD");
DaoAuthenticationProvider provider = createProvider(); DaoAuthenticationProvider provider = createProvider();
provider.setUserDetailsService(new MockUserDetailsServiceUserRod()); provider.setUserDetailsService(new MockUserDetailsServiceUserRod());
provider.setUserCache(new MockUserCache()); provider.setUserCache(new MockUserCache());
@ -163,7 +168,8 @@ public class DaoAuthenticationProviderTests {
@Test @Test
public void testAuthenticateFailsWithInvalidUsernameAndHideUserNotFoundExceptionFalse() { public void testAuthenticateFailsWithInvalidUsernameAndHideUserNotFoundExceptionFalse() {
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("INVALID_USER", "koala"); UsernamePasswordAuthenticationToken token = UsernamePasswordAuthenticationToken.unauthenticated("INVALID_USER",
"koala");
DaoAuthenticationProvider provider = createProvider(); DaoAuthenticationProvider provider = createProvider();
provider.setHideUserNotFoundExceptions(false); // we want provider.setHideUserNotFoundExceptions(false); // we want
// UsernameNotFoundExceptions // UsernameNotFoundExceptions
@ -174,7 +180,8 @@ public class DaoAuthenticationProviderTests {
@Test @Test
public void testAuthenticateFailsWithInvalidUsernameAndHideUserNotFoundExceptionsWithDefaultOfTrue() { public void testAuthenticateFailsWithInvalidUsernameAndHideUserNotFoundExceptionsWithDefaultOfTrue() {
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("INVALID_USER", "koala"); UsernamePasswordAuthenticationToken token = UsernamePasswordAuthenticationToken.unauthenticated("INVALID_USER",
"koala");
DaoAuthenticationProvider provider = createProvider(); DaoAuthenticationProvider provider = createProvider();
assertThat(provider.isHideUserNotFoundExceptions()).isTrue(); assertThat(provider.isHideUserNotFoundExceptions()).isTrue();
provider.setUserDetailsService(new MockUserDetailsServiceUserRod()); provider.setUserDetailsService(new MockUserDetailsServiceUserRod());
@ -184,7 +191,8 @@ public class DaoAuthenticationProviderTests {
@Test @Test
public void testAuthenticateFailsWithInvalidUsernameAndChangePasswordEncoder() { public void testAuthenticateFailsWithInvalidUsernameAndChangePasswordEncoder() {
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("INVALID_USER", "koala"); UsernamePasswordAuthenticationToken token = UsernamePasswordAuthenticationToken.unauthenticated("INVALID_USER",
"koala");
DaoAuthenticationProvider provider = createProvider(); DaoAuthenticationProvider provider = createProvider();
assertThat(provider.isHideUserNotFoundExceptions()).isTrue(); assertThat(provider.isHideUserNotFoundExceptions()).isTrue();
provider.setUserDetailsService(new MockUserDetailsServiceUserRod()); provider.setUserDetailsService(new MockUserDetailsServiceUserRod());
@ -196,7 +204,7 @@ public class DaoAuthenticationProviderTests {
@Test @Test
public void testAuthenticateFailsWithMixedCaseUsernameIfDefaultChanged() { public void testAuthenticateFailsWithMixedCaseUsernameIfDefaultChanged() {
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("RoD", "koala"); UsernamePasswordAuthenticationToken token = UsernamePasswordAuthenticationToken.unauthenticated("RoD", "koala");
DaoAuthenticationProvider provider = createProvider(); DaoAuthenticationProvider provider = createProvider();
provider.setUserDetailsService(new MockUserDetailsServiceUserRod()); provider.setUserDetailsService(new MockUserDetailsServiceUserRod());
provider.setUserCache(new MockUserCache()); provider.setUserCache(new MockUserCache());
@ -205,7 +213,7 @@ public class DaoAuthenticationProviderTests {
@Test @Test
public void testAuthenticates() { public void testAuthenticates() {
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("rod", "koala"); UsernamePasswordAuthenticationToken token = UsernamePasswordAuthenticationToken.unauthenticated("rod", "koala");
token.setDetails("192.168.0.1"); token.setDetails("192.168.0.1");
DaoAuthenticationProvider provider = createProvider(); DaoAuthenticationProvider provider = createProvider();
provider.setUserDetailsService(new MockUserDetailsServiceUserRod()); provider.setUserDetailsService(new MockUserDetailsServiceUserRod());
@ -223,7 +231,7 @@ public class DaoAuthenticationProviderTests {
@Test @Test
public void testAuthenticatesASecondTime() { public void testAuthenticatesASecondTime() {
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("rod", "koala"); UsernamePasswordAuthenticationToken token = UsernamePasswordAuthenticationToken.unauthenticated("rod", "koala");
DaoAuthenticationProvider provider = createProvider(); DaoAuthenticationProvider provider = createProvider();
provider.setUserDetailsService(new MockUserDetailsServiceUserRod()); provider.setUserDetailsService(new MockUserDetailsServiceUserRod());
provider.setUserCache(new MockUserCache()); provider.setUserCache(new MockUserCache());
@ -241,7 +249,7 @@ public class DaoAuthenticationProviderTests {
@Test @Test
public void testAuthenticatesWithForcePrincipalAsString() { public void testAuthenticatesWithForcePrincipalAsString() {
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("rod", "koala"); UsernamePasswordAuthenticationToken token = UsernamePasswordAuthenticationToken.unauthenticated("rod", "koala");
DaoAuthenticationProvider provider = createProvider(); DaoAuthenticationProvider provider = createProvider();
provider.setUserDetailsService(new MockUserDetailsServiceUserRod()); provider.setUserDetailsService(new MockUserDetailsServiceUserRod());
provider.setUserCache(new MockUserCache()); provider.setUserCache(new MockUserCache());
@ -259,7 +267,8 @@ public class DaoAuthenticationProviderTests {
public void authenticateWhenSuccessAndPasswordManagerThenUpdates() { public void authenticateWhenSuccessAndPasswordManagerThenUpdates() {
String password = "password"; String password = "password";
String encodedPassword = "encoded"; String encodedPassword = "encoded";
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("user", password); UsernamePasswordAuthenticationToken token = UsernamePasswordAuthenticationToken.unauthenticated("user",
password);
PasswordEncoder encoder = mock(PasswordEncoder.class); PasswordEncoder encoder = mock(PasswordEncoder.class);
UserDetailsService userDetailsService = mock(UserDetailsService.class); UserDetailsService userDetailsService = mock(UserDetailsService.class);
UserDetailsPasswordService passwordManager = mock(UserDetailsPasswordService.class); UserDetailsPasswordService passwordManager = mock(UserDetailsPasswordService.class);
@ -280,7 +289,8 @@ public class DaoAuthenticationProviderTests {
@Test @Test
public void authenticateWhenBadCredentialsAndPasswordManagerThenNoUpdate() { public void authenticateWhenBadCredentialsAndPasswordManagerThenNoUpdate() {
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("user", "password"); UsernamePasswordAuthenticationToken token = UsernamePasswordAuthenticationToken.unauthenticated("user",
"password");
PasswordEncoder encoder = mock(PasswordEncoder.class); PasswordEncoder encoder = mock(PasswordEncoder.class);
UserDetailsService userDetailsService = mock(UserDetailsService.class); UserDetailsService userDetailsService = mock(UserDetailsService.class);
UserDetailsPasswordService passwordManager = mock(UserDetailsPasswordService.class); UserDetailsPasswordService passwordManager = mock(UserDetailsPasswordService.class);
@ -297,7 +307,8 @@ public class DaoAuthenticationProviderTests {
@Test @Test
public void authenticateWhenNotUpgradeAndPasswordManagerThenNoUpdate() { public void authenticateWhenNotUpgradeAndPasswordManagerThenNoUpdate() {
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("user", "password"); UsernamePasswordAuthenticationToken token = UsernamePasswordAuthenticationToken.unauthenticated("user",
"password");
PasswordEncoder encoder = mock(PasswordEncoder.class); PasswordEncoder encoder = mock(PasswordEncoder.class);
UserDetailsService userDetailsService = mock(UserDetailsService.class); UserDetailsService userDetailsService = mock(UserDetailsService.class);
UserDetailsPasswordService passwordManager = mock(UserDetailsPasswordService.class); UserDetailsPasswordService passwordManager = mock(UserDetailsPasswordService.class);
@ -315,7 +326,7 @@ public class DaoAuthenticationProviderTests {
@Test @Test
public void testDetectsNullBeingReturnedFromAuthenticationDao() { public void testDetectsNullBeingReturnedFromAuthenticationDao() {
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("rod", "koala"); UsernamePasswordAuthenticationToken token = UsernamePasswordAuthenticationToken.unauthenticated("rod", "koala");
DaoAuthenticationProvider provider = createProvider(); DaoAuthenticationProvider provider = createProvider();
provider.setUserDetailsService(new MockUserDetailsServiceReturnsNull()); provider.setUserDetailsService(new MockUserDetailsServiceReturnsNull());
assertThatExceptionOfType(AuthenticationServiceException.class).isThrownBy(() -> provider.authenticate(token)) assertThatExceptionOfType(AuthenticationServiceException.class).isThrownBy(() -> provider.authenticate(token))
@ -336,7 +347,7 @@ public class DaoAuthenticationProviderTests {
@Test @Test
public void testGoesBackToAuthenticationDaoToObtainLatestPasswordIfCachedPasswordSeemsIncorrect() { public void testGoesBackToAuthenticationDaoToObtainLatestPasswordIfCachedPasswordSeemsIncorrect() {
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("rod", "koala"); UsernamePasswordAuthenticationToken token = UsernamePasswordAuthenticationToken.unauthenticated("rod", "koala");
MockUserDetailsServiceUserRod authenticationDao = new MockUserDetailsServiceUserRod(); MockUserDetailsServiceUserRod authenticationDao = new MockUserDetailsServiceUserRod();
MockUserCache cache = new MockUserCache(); MockUserCache cache = new MockUserCache();
DaoAuthenticationProvider provider = createProvider(); DaoAuthenticationProvider provider = createProvider();
@ -349,7 +360,7 @@ public class DaoAuthenticationProviderTests {
// Now change the password the AuthenticationDao will return // Now change the password the AuthenticationDao will return
authenticationDao.setPassword("easternLongNeckTurtle"); authenticationDao.setPassword("easternLongNeckTurtle");
// Now try authentication again, with the new password // Now try authentication again, with the new password
token = new UsernamePasswordAuthenticationToken("rod", "easternLongNeckTurtle"); token = UsernamePasswordAuthenticationToken.unauthenticated("rod", "easternLongNeckTurtle");
provider.authenticate(token); provider.authenticate(token);
// To get this far, the new password was accepted // To get this far, the new password was accepted
// Check the cache was updated // Check the cache was updated
@ -391,7 +402,8 @@ public class DaoAuthenticationProviderTests {
// SEC-2056 // SEC-2056
@Test @Test
public void testUserNotFoundEncodesPassword() throws Exception { public void testUserNotFoundEncodesPassword() throws Exception {
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("missing", "koala"); UsernamePasswordAuthenticationToken token = UsernamePasswordAuthenticationToken.unauthenticated("missing",
"koala");
PasswordEncoder encoder = mock(PasswordEncoder.class); PasswordEncoder encoder = mock(PasswordEncoder.class);
given(encoder.encode(anyString())).willReturn("koala"); given(encoder.encode(anyString())).willReturn("koala");
DaoAuthenticationProvider provider = new DaoAuthenticationProvider(); DaoAuthenticationProvider provider = new DaoAuthenticationProvider();
@ -407,7 +419,8 @@ public class DaoAuthenticationProviderTests {
@Test @Test
public void testUserNotFoundBCryptPasswordEncoder() { public void testUserNotFoundBCryptPasswordEncoder() {
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("missing", "koala"); UsernamePasswordAuthenticationToken token = UsernamePasswordAuthenticationToken.unauthenticated("missing",
"koala");
PasswordEncoder encoder = new BCryptPasswordEncoder(); PasswordEncoder encoder = new BCryptPasswordEncoder();
DaoAuthenticationProvider provider = new DaoAuthenticationProvider(); DaoAuthenticationProvider provider = new DaoAuthenticationProvider();
provider.setHideUserNotFoundExceptions(false); provider.setHideUserNotFoundExceptions(false);
@ -420,7 +433,8 @@ public class DaoAuthenticationProviderTests {
@Test @Test
public void testUserNotFoundDefaultEncoder() { public void testUserNotFoundDefaultEncoder() {
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("missing", null); UsernamePasswordAuthenticationToken token = UsernamePasswordAuthenticationToken.unauthenticated("missing",
null);
DaoAuthenticationProvider provider = createProvider(); DaoAuthenticationProvider provider = createProvider();
provider.setHideUserNotFoundExceptions(false); provider.setHideUserNotFoundExceptions(false);
provider.setUserDetailsService(new MockUserDetailsServiceUserRod()); provider.setUserDetailsService(new MockUserDetailsServiceUserRod());
@ -433,8 +447,10 @@ public class DaoAuthenticationProviderTests {
* SEC-2056 is fixed. * SEC-2056 is fixed.
*/ */
public void IGNOREtestSec2056() { public void IGNOREtestSec2056() {
UsernamePasswordAuthenticationToken foundUser = new UsernamePasswordAuthenticationToken("rod", "koala"); UsernamePasswordAuthenticationToken foundUser = UsernamePasswordAuthenticationToken.unauthenticated("rod",
UsernamePasswordAuthenticationToken notFoundUser = new UsernamePasswordAuthenticationToken("notFound", "koala"); "koala");
UsernamePasswordAuthenticationToken notFoundUser = UsernamePasswordAuthenticationToken
.unauthenticated("notFound", "koala");
PasswordEncoder encoder = new BCryptPasswordEncoder(10, new SecureRandom()); PasswordEncoder encoder = new BCryptPasswordEncoder(10, new SecureRandom());
DaoAuthenticationProvider provider = new DaoAuthenticationProvider(); DaoAuthenticationProvider provider = new DaoAuthenticationProvider();
provider.setHideUserNotFoundExceptions(false); provider.setHideUserNotFoundExceptions(false);
@ -468,7 +484,8 @@ public class DaoAuthenticationProviderTests {
@Test @Test
public void testUserNotFoundNullCredentials() { public void testUserNotFoundNullCredentials() {
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("missing", null); UsernamePasswordAuthenticationToken token = UsernamePasswordAuthenticationToken.unauthenticated("missing",
null);
PasswordEncoder encoder = mock(PasswordEncoder.class); PasswordEncoder encoder = mock(PasswordEncoder.class);
DaoAuthenticationProvider provider = new DaoAuthenticationProvider(); DaoAuthenticationProvider provider = new DaoAuthenticationProvider();
provider.setHideUserNotFoundExceptions(false); provider.setHideUserNotFoundExceptions(false);

View File

@ -34,8 +34,8 @@ import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException
public class AuthenticationEventTests { public class AuthenticationEventTests {
private Authentication getAuthentication() { private Authentication getAuthentication() {
UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken("Principal", UsernamePasswordAuthenticationToken authentication = UsernamePasswordAuthenticationToken
"Credentials"); .unauthenticated("Principal", "Credentials");
authentication.setDetails("127.0.0.1"); authentication.setDetails("127.0.0.1");
return authentication; return authentication;
} }

View File

@ -30,8 +30,8 @@ import org.springframework.security.core.Authentication;
public class LoggerListenerTests { public class LoggerListenerTests {
private Authentication getAuthentication() { private Authentication getAuthentication() {
UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken("Principal", UsernamePasswordAuthenticationToken authentication = UsernamePasswordAuthenticationToken
"Credentials"); .unauthenticated("Principal", "Credentials");
authentication.setDetails("127.0.0.1"); authentication.setDetails("127.0.0.1");
return authentication; return authentication;
} }

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2010-2016 the original author or authors. * Copyright 2010-2022 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -79,7 +79,7 @@ public class DefaultJaasAuthenticationProviderTests {
new AppConfigurationEntry(TestLoginModule.class.getName(), LoginModuleControlFlag.REQUIRED, new AppConfigurationEntry(TestLoginModule.class.getName(), LoginModuleControlFlag.REQUIRED,
Collections.<String, Object>emptyMap()) }; Collections.<String, Object>emptyMap()) };
given(configuration.getAppConfigurationEntry(this.provider.getLoginContextName())).willReturn(aces); given(configuration.getAppConfigurationEntry(this.provider.getLoginContextName())).willReturn(aces);
this.token = new UsernamePasswordAuthenticationToken("user", "password"); this.token = UsernamePasswordAuthenticationToken.unauthenticated("user", "password");
ReflectionTestUtils.setField(this.provider, "log", this.log); ReflectionTestUtils.setField(this.provider, "log", this.log);
} }
@ -113,15 +113,15 @@ public class DefaultJaasAuthenticationProviderTests {
@Test @Test
public void authenticateBadPassword() { public void authenticateBadPassword() {
assertThatExceptionOfType(AuthenticationException.class) assertThatExceptionOfType(AuthenticationException.class).isThrownBy(
.isThrownBy(() -> this.provider.authenticate(new UsernamePasswordAuthenticationToken("user", "asdf"))); () -> this.provider.authenticate(UsernamePasswordAuthenticationToken.unauthenticated("user", "asdf")));
verifyFailedLogin(); verifyFailedLogin();
} }
@Test @Test
public void authenticateBadUser() { public void authenticateBadUser() {
assertThatExceptionOfType(AuthenticationException.class).isThrownBy( assertThatExceptionOfType(AuthenticationException.class).isThrownBy(() -> this.provider
() -> this.provider.authenticate(new UsernamePasswordAuthenticationToken("asdf", "password"))); .authenticate(UsernamePasswordAuthenticationToken.unauthenticated("asdf", "password")));
verifyFailedLogin(); verifyFailedLogin();
} }

View File

@ -75,8 +75,8 @@ public class JaasAuthenticationProviderTests {
@Test @Test
public void testBadPassword() { public void testBadPassword() {
assertThatExceptionOfType(AuthenticationException.class).isThrownBy( assertThatExceptionOfType(AuthenticationException.class).isThrownBy(() -> this.jaasProvider
() -> this.jaasProvider.authenticate(new UsernamePasswordAuthenticationToken("user", "asdf"))); .authenticate(UsernamePasswordAuthenticationToken.unauthenticated("user", "asdf")));
assertThat(this.eventCheck.failedEvent).as("Failure event not fired").isNotNull(); assertThat(this.eventCheck.failedEvent).as("Failure event not fired").isNotNull();
assertThat(this.eventCheck.failedEvent.getException()).withFailMessage("Failure event exception was null") assertThat(this.eventCheck.failedEvent.getException()).withFailMessage("Failure event exception was null")
.isNotNull(); .isNotNull();
@ -85,8 +85,8 @@ public class JaasAuthenticationProviderTests {
@Test @Test
public void testBadUser() { public void testBadUser() {
assertThatExceptionOfType(AuthenticationException.class).isThrownBy( assertThatExceptionOfType(AuthenticationException.class).isThrownBy(() -> this.jaasProvider
() -> this.jaasProvider.authenticate(new UsernamePasswordAuthenticationToken("asdf", "password"))); .authenticate(UsernamePasswordAuthenticationToken.unauthenticated("asdf", "password")));
assertThat(this.eventCheck.failedEvent).as("Failure event not fired").isNotNull(); assertThat(this.eventCheck.failedEvent).as("Failure event not fired").isNotNull();
assertThat(this.eventCheck.failedEvent.getException()).withFailMessage("Failure event exception was null") assertThat(this.eventCheck.failedEvent.getException()).withFailMessage("Failure event exception was null")
.isNotNull(); .isNotNull();
@ -158,8 +158,8 @@ public class JaasAuthenticationProviderTests {
@Test @Test
public void testFull() { public void testFull() {
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("user", "password", UsernamePasswordAuthenticationToken token = UsernamePasswordAuthenticationToken.authenticated("user",
AuthorityUtils.createAuthorityList("ROLE_ONE")); "password", AuthorityUtils.createAuthorityList("ROLE_ONE"));
assertThat(this.jaasProvider.supports(UsernamePasswordAuthenticationToken.class)).isTrue(); assertThat(this.jaasProvider.supports(UsernamePasswordAuthenticationToken.class)).isTrue();
Authentication auth = this.jaasProvider.authenticate(token); Authentication auth = this.jaasProvider.authenticate(token);
assertThat(this.jaasProvider.getAuthorityGranters()).isNotNull(); assertThat(this.jaasProvider.getAuthorityGranters()).isNotNull();
@ -198,7 +198,7 @@ public class JaasAuthenticationProviderTests {
assertThat(this.jaasProvider.getLoginExceptionResolver()).isNotNull(); assertThat(this.jaasProvider.getLoginExceptionResolver()).isNotNull();
this.jaasProvider.setLoginExceptionResolver((e) -> new LockedException("This is just a test!")); this.jaasProvider.setLoginExceptionResolver((e) -> new LockedException("This is just a test!"));
try { try {
this.jaasProvider.authenticate(new UsernamePasswordAuthenticationToken("user", "password")); this.jaasProvider.authenticate(UsernamePasswordAuthenticationToken.unauthenticated("user", "password"));
} }
catch (LockedException ex) { catch (LockedException ex) {
} }
@ -221,7 +221,8 @@ public class JaasAuthenticationProviderTests {
@Test @Test
public void testNullDefaultAuthorities() { public void testNullDefaultAuthorities() {
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("user", "password"); UsernamePasswordAuthenticationToken token = UsernamePasswordAuthenticationToken.unauthenticated("user",
"password");
assertThat(this.jaasProvider.supports(UsernamePasswordAuthenticationToken.class)).isTrue(); assertThat(this.jaasProvider.supports(UsernamePasswordAuthenticationToken.class)).isTrue();
Authentication auth = this.jaasProvider.authenticate(token); Authentication auth = this.jaasProvider.authenticate(token);
assertThat(auth.getAuthorities()).withFailMessage("Only ROLE_TEST1 and ROLE_TEST2 should have been returned") assertThat(auth.getAuthorities()).withFailMessage("Only ROLE_TEST1 and ROLE_TEST2 should have been returned")

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2016 the original author or authors. * Copyright 2002-2022 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -56,8 +56,8 @@ public class Sec760Tests {
} }
private void testAuthenticate(JaasAuthenticationProvider p1) { private void testAuthenticate(JaasAuthenticationProvider p1) {
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("user", "password", UsernamePasswordAuthenticationToken token = UsernamePasswordAuthenticationToken.authenticated("user",
AuthorityUtils.createAuthorityList("ROLE_ONE", "ROLE_TWO")); "password", AuthorityUtils.createAuthorityList("ROLE_ONE", "ROLE_TWO"));
Authentication auth = p1.authenticate(token); Authentication auth = p1.authenticate(token);
assertThat(auth).isNotNull(); assertThat(auth).isNotNull();
} }

View File

@ -44,7 +44,7 @@ public class SecurityContextLoginModuleTests {
private Subject subject = new Subject(false, new HashSet<>(), new HashSet<>(), new HashSet<>()); private Subject subject = new Subject(false, new HashSet<>(), new HashSet<>(), new HashSet<>());
private UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken("principal", private UsernamePasswordAuthenticationToken auth = UsernamePasswordAuthenticationToken.unauthenticated("principal",
"credentials"); "credentials");
@BeforeEach @BeforeEach

View File

@ -76,8 +76,8 @@ public class RememberMeAuthenticationTokenTests {
@Test @Test
public void testNotEqualsDueToDifferentAuthenticationClass() { public void testNotEqualsDueToDifferentAuthenticationClass() {
RememberMeAuthenticationToken token1 = new RememberMeAuthenticationToken("key", "Test", ROLES_12); RememberMeAuthenticationToken token1 = new RememberMeAuthenticationToken("key", "Test", ROLES_12);
UsernamePasswordAuthenticationToken token2 = new UsernamePasswordAuthenticationToken("Test", "Password", UsernamePasswordAuthenticationToken token2 = UsernamePasswordAuthenticationToken.authenticated("Test",
ROLES_12); "Password", ROLES_12);
assertThat(token1.equals(token2)).isFalse(); assertThat(token1.equals(token2)).isFalse();
} }

View File

@ -41,7 +41,7 @@ public class SecurityContextHolderTests {
@Test @Test
public void testContextHolderGetterSetterClearer() { public void testContextHolderGetterSetterClearer() {
SecurityContext sc = new SecurityContextImpl(); SecurityContext sc = new SecurityContextImpl();
sc.setAuthentication(new UsernamePasswordAuthenticationToken("Foobar", "pass")); sc.setAuthentication(UsernamePasswordAuthenticationToken.unauthenticated("Foobar", "pass"));
SecurityContextHolder.setContext(sc); SecurityContextHolder.setContext(sc);
assertThat(SecurityContextHolder.getContext()).isEqualTo(sc); assertThat(SecurityContextHolder.getContext()).isEqualTo(sc);
SecurityContextHolder.clearContext(); SecurityContextHolder.clearContext();

View File

@ -40,7 +40,7 @@ public class SecurityContextImplTests {
@Test @Test
public void testSecurityContextCorrectOperation() { public void testSecurityContextCorrectOperation() {
SecurityContext context = new SecurityContextImpl(); SecurityContext context = new SecurityContextImpl();
Authentication auth = new UsernamePasswordAuthenticationToken("rod", "koala"); Authentication auth = UsernamePasswordAuthenticationToken.unauthenticated("rod", "koala");
context.setAuthentication(auth); context.setAuthentication(auth);
assertThat(context.getAuthentication()).isEqualTo(auth); assertThat(context.getAuthentication()).isEqualTo(auth);
assertThat(context.toString().lastIndexOf("rod") != -1).isTrue(); assertThat(context.toString().lastIndexOf("rod") != -1).isTrue();

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2015-2016 the original author or authors. * Copyright 2015-2022 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -47,7 +47,7 @@ public class SecurityContextMixinTests extends AbstractMixinTests {
@Test @Test
public void securityContextSerializeTest() throws JsonProcessingException, JSONException { public void securityContextSerializeTest() throws JsonProcessingException, JSONException {
SecurityContext context = new SecurityContextImpl(); SecurityContext context = new SecurityContextImpl();
context.setAuthentication(new UsernamePasswordAuthenticationToken("admin", "1234", context.setAuthentication(UsernamePasswordAuthenticationToken.authenticated("admin", "1234",
Collections.singleton(new SimpleGrantedAuthority("ROLE_USER")))); Collections.singleton(new SimpleGrantedAuthority("ROLE_USER"))));
String actualJson = this.mapper.writeValueAsString(context); String actualJson = this.mapper.writeValueAsString(context);
JSONAssert.assertEquals(SECURITY_CONTEXT_JSON, actualJson, true); JSONAssert.assertEquals(SECURITY_CONTEXT_JSON, actualJson, true);

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2015-2016 the original author or authors. * Copyright 2015-2022 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -71,7 +71,8 @@ public class UsernamePasswordAuthenticationTokenMixinTests extends AbstractMixin
@Test @Test
public void serializeUnauthenticatedUsernamePasswordAuthenticationTokenMixinTest() public void serializeUnauthenticatedUsernamePasswordAuthenticationTokenMixinTest()
throws JsonProcessingException, JSONException { throws JsonProcessingException, JSONException {
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("admin", "1234"); UsernamePasswordAuthenticationToken token = UsernamePasswordAuthenticationToken.unauthenticated("admin",
"1234");
String serializedJson = this.mapper.writeValueAsString(token); String serializedJson = this.mapper.writeValueAsString(token);
JSONAssert.assertEquals(UNAUTHENTICATED_STRINGPRINCIPAL_JSON, serializedJson, true); JSONAssert.assertEquals(UNAUTHENTICATED_STRINGPRINCIPAL_JSON, serializedJson, true);
} }
@ -80,8 +81,8 @@ public class UsernamePasswordAuthenticationTokenMixinTests extends AbstractMixin
public void serializeAuthenticatedUsernamePasswordAuthenticationTokenMixinTest() public void serializeAuthenticatedUsernamePasswordAuthenticationTokenMixinTest()
throws JsonProcessingException, JSONException { throws JsonProcessingException, JSONException {
User user = createDefaultUser(); User user = createDefaultUser();
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(user.getUsername(), UsernamePasswordAuthenticationToken token = UsernamePasswordAuthenticationToken
user.getPassword(), user.getAuthorities()); .authenticated(user.getUsername(), user.getPassword(), user.getAuthorities());
String serializedJson = this.mapper.writeValueAsString(token); String serializedJson = this.mapper.writeValueAsString(token);
JSONAssert.assertEquals(AUTHENTICATED_STRINGPRINCIPAL_JSON, serializedJson, true); JSONAssert.assertEquals(AUTHENTICATED_STRINGPRINCIPAL_JSON, serializedJson, true);
} }
@ -140,7 +141,7 @@ public class UsernamePasswordAuthenticationTokenMixinTests extends AbstractMixin
throws JsonProcessingException, JSONException { throws JsonProcessingException, JSONException {
NonUserPrincipal principal = new NonUserPrincipal(); NonUserPrincipal principal = new NonUserPrincipal();
principal.setUsername("admin"); principal.setUsername("admin");
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(principal, null, UsernamePasswordAuthenticationToken token = UsernamePasswordAuthenticationToken.authenticated(principal, null,
new ArrayList<>()); new ArrayList<>());
String actualJson = this.mapper.writeValueAsString(token); String actualJson = this.mapper.writeValueAsString(token);
JSONAssert.assertEquals(AUTHENTICATED_NON_USER_PRINCIPAL_JSON, actualJson, true); JSONAssert.assertEquals(AUTHENTICATED_NON_USER_PRINCIPAL_JSON, actualJson, true);
@ -170,7 +171,8 @@ public class UsernamePasswordAuthenticationTokenMixinTests extends AbstractMixin
@Test @Test
public void serializingThenDeserializingWithNoCredentialsOrDetailsShouldWork() throws IOException { public void serializingThenDeserializingWithNoCredentialsOrDetailsShouldWork() throws IOException {
UsernamePasswordAuthenticationToken original = new UsernamePasswordAuthenticationToken("Frodo", null); UsernamePasswordAuthenticationToken original = UsernamePasswordAuthenticationToken.unauthenticated("Frodo",
null);
String serialized = this.mapper.writeValueAsString(original); String serialized = this.mapper.writeValueAsString(original);
UsernamePasswordAuthenticationToken deserialized = this.mapper.readValue(serialized, UsernamePasswordAuthenticationToken deserialized = this.mapper.readValue(serialized,
UsernamePasswordAuthenticationToken.class); UsernamePasswordAuthenticationToken.class);
@ -181,7 +183,8 @@ public class UsernamePasswordAuthenticationTokenMixinTests extends AbstractMixin
public void serializingThenDeserializingWithConfiguredObjectMapperShouldWork() throws IOException { public void serializingThenDeserializingWithConfiguredObjectMapperShouldWork() throws IOException {
this.mapper.setDefaultPropertyInclusion(Value.construct(Include.ALWAYS, Include.NON_NULL)) this.mapper.setDefaultPropertyInclusion(Value.construct(Include.ALWAYS, Include.NON_NULL))
.setSerializationInclusion(Include.NON_ABSENT); .setSerializationInclusion(Include.NON_ABSENT);
UsernamePasswordAuthenticationToken original = new UsernamePasswordAuthenticationToken("Frodo", null); UsernamePasswordAuthenticationToken original = UsernamePasswordAuthenticationToken.unauthenticated("Frodo",
null);
String serialized = this.mapper.writeValueAsString(original); String serialized = this.mapper.writeValueAsString(original);
UsernamePasswordAuthenticationToken deserialized = this.mapper.readValue(serialized, UsernamePasswordAuthenticationToken deserialized = this.mapper.readValue(serialized,
UsernamePasswordAuthenticationToken.class); UsernamePasswordAuthenticationToken.class);
@ -190,8 +193,8 @@ public class UsernamePasswordAuthenticationTokenMixinTests extends AbstractMixin
private UsernamePasswordAuthenticationToken createToken() { private UsernamePasswordAuthenticationToken createToken() {
User user = createDefaultUser(); User user = createDefaultUser();
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(user, user.getPassword(), UsernamePasswordAuthenticationToken token = UsernamePasswordAuthenticationToken.authenticated(user,
user.getAuthorities()); user.getPassword(), user.getAuthorities());
return token; return token;
} }

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2018 the original author or authors. * Copyright 2002-2022 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -344,14 +344,14 @@ public class JdbcUserDetailsManagerTests {
@Test @Test
public void createNewAuthenticationUsesNullPasswordToKeepPassordsSave() { public void createNewAuthenticationUsesNullPasswordToKeepPassordsSave() {
insertJoe(); insertJoe();
UsernamePasswordAuthenticationToken currentAuth = new UsernamePasswordAuthenticationToken("joe", null, UsernamePasswordAuthenticationToken currentAuth = UsernamePasswordAuthenticationToken.authenticated("joe", null,
AuthorityUtils.createAuthorityList("ROLE_USER")); AuthorityUtils.createAuthorityList("ROLE_USER"));
Authentication updatedAuth = this.manager.createNewAuthentication(currentAuth, "new"); Authentication updatedAuth = this.manager.createNewAuthentication(currentAuth, "new");
assertThat(updatedAuth.getCredentials()).isNull(); assertThat(updatedAuth.getCredentials()).isNull();
} }
private Authentication authenticateJoe() { private Authentication authenticateJoe() {
UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken("joe", "password", UsernamePasswordAuthenticationToken auth = UsernamePasswordAuthenticationToken.authenticated("joe", "password",
joe.getAuthorities()); joe.getAuthorities());
SecurityContextHolder.getContext().setAuthentication(auth); SecurityContextHolder.getContext().setAuthentication(auth);
return auth; return auth;

View File

@ -137,7 +137,7 @@ You can see an example of how it might be used below:
---- ----
SecurityContext context = SecurityContextHolder.createEmptyContext(); SecurityContext context = SecurityContextHolder.createEmptyContext();
Authentication authentication = Authentication authentication =
new UsernamePasswordAuthenticationToken("user","doesnotmatter", AuthorityUtils.createAuthorityList("ROLE_USER")); UsernamePasswordAuthenticationToken.authenticated("user","doesnotmatter", AuthorityUtils.createAuthorityList("ROLE_USER"));
context.setAuthentication(authentication); context.setAuthentication(authentication);
SimpleAsyncTaskExecutor delegateExecutor = SimpleAsyncTaskExecutor delegateExecutor =

View File

@ -95,7 +95,7 @@ The following example shows how to use it:
---- ----
SecurityContext context = SecurityContextHolder.createEmptyContext(); SecurityContext context = SecurityContextHolder.createEmptyContext();
Authentication authentication = Authentication authentication =
new UsernamePasswordAuthenticationToken("user","doesnotmatter", AuthorityUtils.createAuthorityList("ROLE_USER")); UsernamePasswordAuthenticationToken.authenticated("user","doesnotmatter", AuthorityUtils.createAuthorityList("ROLE_USER"));
context.setAuthentication(authentication); context.setAuthentication(authentication);
SimpleAsyncTaskExecutor delegateExecutor = SimpleAsyncTaskExecutor delegateExecutor =

View File

@ -529,7 +529,7 @@ public class WithMockCustomUserSecurityContextFactory
CustomUserDetails principal = CustomUserDetails principal =
new CustomUserDetails(customUser.name(), customUser.username()); new CustomUserDetails(customUser.name(), customUser.username());
Authentication auth = Authentication auth =
new UsernamePasswordAuthenticationToken(principal, "password", principal.getAuthorities()); UsernamePasswordAuthenticationToken.authenticated(principal, "password", principal.getAuthorities());
context.setAuthentication(auth); context.setAuthentication(auth);
return context; return context;
} }
@ -575,7 +575,7 @@ final class WithUserDetailsSecurityContextFactory
String username = withUser.value(); String username = withUser.value();
Assert.hasLength(username, "value() must be non-empty String"); Assert.hasLength(username, "value() must be non-empty String");
UserDetails principal = userDetailsService.loadUserByUsername(username); UserDetails principal = userDetailsService.loadUserByUsername(username);
Authentication authentication = new UsernamePasswordAuthenticationToken(principal, principal.getPassword(), principal.getAuthorities()); Authentication authentication = UsernamePasswordAuthenticationToken.authenticated(principal, principal.getPassword(), principal.getAuthorities());
SecurityContext context = SecurityContextHolder.createEmptyContext(); SecurityContext context = SecurityContextHolder.createEmptyContext();
context.setAuthentication(authentication); context.setAuthentication(authentication);
return context; return context;

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2016 the original author or authors. * Copyright 2002-2022 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -35,7 +35,7 @@ public class PythonInterpreterBasedSecurityTests {
@Test @Test
public void serviceMethod() { public void serviceMethod() {
SecurityContextHolder.getContext() SecurityContextHolder.getContext()
.setAuthentication(new UsernamePasswordAuthenticationToken("bob", "bobspassword")); .setAuthentication(UsernamePasswordAuthenticationToken.unauthenticated("bob", "bobspassword"));
// for (int i=0; i < 1000; i++) { // for (int i=0; i < 1000; i++) {
this.service.someMethod(); this.service.someMethod();

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2016 the original author or authors. * Copyright 2002-2022 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -58,7 +58,7 @@ public class FilterChainPerformanceTests {
private static StopWatch sw = new StopWatch("Filter Chain Performance Tests"); private static StopWatch sw = new StopWatch("Filter Chain Performance Tests");
private final UsernamePasswordAuthenticationToken user = new UsernamePasswordAuthenticationToken("bob", private final UsernamePasswordAuthenticationToken user = UsernamePasswordAuthenticationToken.authenticated("bob",
"bobspassword", createRoles(N_AUTHORITIES)); "bobspassword", createRoles(N_AUTHORITIES));
private HttpSession session; private HttpSession session;
@ -129,8 +129,8 @@ public class FilterChainPerformanceTests {
StopWatch sw = new StopWatch("Scaling with nAuthorities"); StopWatch sw = new StopWatch("Scaling with nAuthorities");
for (int user = 0; user < N_AUTHORITIES / 10; user++) { for (int user = 0; user < N_AUTHORITIES / 10; user++) {
int nAuthorities = (user != 0) ? user * 10 : 1; int nAuthorities = (user != 0) ? user * 10 : 1;
SecurityContextHolder.getContext().setAuthentication( SecurityContextHolder.getContext().setAuthentication(UsernamePasswordAuthenticationToken
new UsernamePasswordAuthenticationToken("bob", "bobspassword", createRoles(nAuthorities))); .authenticated("bob", "bobspassword", createRoles(nAuthorities)));
this.session.setAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY, this.session.setAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY,
SecurityContextHolder.getContext()); SecurityContextHolder.getContext());
SecurityContextHolder.clearContext(); SecurityContextHolder.clearContext();

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2017 the original author or authors. * Copyright 2002-2022 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -117,7 +117,7 @@ public class SecurityContextHolderMTTests extends TestCase{
} else if (expectAllThreadsToUseIdenticalAuthentication) { } else if (expectAllThreadsToUseIdenticalAuthentication) {
// A global // A global
SecurityContextHolder.getContext() SecurityContextHolder.getContext()
.setAuthentication(new UsernamePasswordAuthenticationToken("GLOBAL_USERNAME", .setAuthentication(UsernamePasswordAuthenticationToken.unauthenticated("GLOBAL_USERNAME",
"pass")); "pass"));
for (int i = 0; i < threads.length; i++) { for (int i = 0; i < threads.length; i++) {
@ -182,7 +182,7 @@ public class SecurityContextHolderMTTests extends TestCase{
public void run() { public void run() {
if (injectAuthIntoCurrentThread) { if (injectAuthIntoCurrentThread) {
// Set authentication in this thread // Set authentication in this thread
SecurityContextHolder.getContext().setAuthentication(new UsernamePasswordAuthenticationToken( SecurityContextHolder.getContext().setAuthentication(UsernamePasswordAuthenticationToken.authenticated(
expectedUsername, "pass")); expectedUsername, "pass"));
//System.out.println(threadIdentifier + " - set to " + SecurityContextHolder.getContext().getAuthentication()); //System.out.println(threadIdentifier + " - set to " + SecurityContextHolder.getContext().getAuthentication());

View File

@ -56,14 +56,14 @@ public class BindAuthenticatorTests {
public void setUp() { public void setUp() {
this.authenticator = new BindAuthenticator(this.contextSource); this.authenticator = new BindAuthenticator(this.contextSource);
this.authenticator.setMessageSource(new SpringSecurityMessageSource()); this.authenticator.setMessageSource(new SpringSecurityMessageSource());
this.bob = new UsernamePasswordAuthenticationToken("bob", "bobspassword"); this.bob = UsernamePasswordAuthenticationToken.unauthenticated("bob", "bobspassword");
} }
@Test @Test
public void emptyPasswordIsRejected() { public void emptyPasswordIsRejected() {
assertThatExceptionOfType(BadCredentialsException.class) assertThatExceptionOfType(BadCredentialsException.class).isThrownBy(
.isThrownBy(() -> this.authenticator.authenticate(new UsernamePasswordAuthenticationToken("jen", ""))); () -> this.authenticator.authenticate(UsernamePasswordAuthenticationToken.unauthenticated("jen", "")));
} }
@Test @Test
@ -72,14 +72,15 @@ public class BindAuthenticatorTests {
DirContextOperations user = this.authenticator.authenticate(this.bob); DirContextOperations user = this.authenticator.authenticate(this.bob);
assertThat(user.getStringAttribute("uid")).isEqualTo("bob"); assertThat(user.getStringAttribute("uid")).isEqualTo("bob");
this.authenticator.authenticate(new UsernamePasswordAuthenticationToken("mouse, jerry", "jerryspassword")); this.authenticator
.authenticate(UsernamePasswordAuthenticationToken.unauthenticated("mouse, jerry", "jerryspassword"));
} }
@Test @Test
public void testAuthenticationWithInvalidUserNameFails() { public void testAuthenticationWithInvalidUserNameFails() {
this.authenticator.setUserDnPatterns(new String[] { "uid={0},ou=people" }); this.authenticator.setUserDnPatterns(new String[] { "uid={0},ou=people" });
assertThatExceptionOfType(BadCredentialsException.class).isThrownBy(() -> this.authenticator assertThatExceptionOfType(BadCredentialsException.class).isThrownBy(() -> this.authenticator
.authenticate(new UsernamePasswordAuthenticationToken("nonexistentsuser", "password"))); .authenticate(UsernamePasswordAuthenticationToken.unauthenticated("nonexistentsuser", "password")));
} }
@Test @Test
@ -93,14 +94,18 @@ public class BindAuthenticatorTests {
assertThat(result.getStringAttribute("cn")).isEqualTo("Bob Hamilton"); assertThat(result.getStringAttribute("cn")).isEqualTo("Bob Hamilton");
// SEC-1444 // SEC-1444
this.authenticator.setUserSearch(new FilterBasedLdapUserSearch("ou=people", "(cn={0})", this.contextSource)); this.authenticator.setUserSearch(new FilterBasedLdapUserSearch("ou=people", "(cn={0})", this.contextSource));
this.authenticator.authenticate(new UsernamePasswordAuthenticationToken("mouse, jerry", "jerryspassword")); this.authenticator
this.authenticator.authenticate(new UsernamePasswordAuthenticationToken("slash/guy", "slashguyspassword")); .authenticate(UsernamePasswordAuthenticationToken.unauthenticated("mouse, jerry", "jerryspassword"));
this.authenticator
.authenticate(UsernamePasswordAuthenticationToken.unauthenticated("slash/guy", "slashguyspassword"));
// SEC-1661 // SEC-1661
this.authenticator.setUserSearch( this.authenticator.setUserSearch(
new FilterBasedLdapUserSearch("ou=\\\"quoted people\\\"", "(cn={0})", this.contextSource)); new FilterBasedLdapUserSearch("ou=\\\"quoted people\\\"", "(cn={0})", this.contextSource));
this.authenticator.authenticate(new UsernamePasswordAuthenticationToken("quote\"guy", "quoteguyspassword")); this.authenticator
.authenticate(UsernamePasswordAuthenticationToken.unauthenticated("quote\"guy", "quoteguyspassword"));
this.authenticator.setUserSearch(new FilterBasedLdapUserSearch("", "(cn={0})", this.contextSource)); this.authenticator.setUserSearch(new FilterBasedLdapUserSearch("", "(cn={0})", this.contextSource));
this.authenticator.authenticate(new UsernamePasswordAuthenticationToken("quote\"guy", "quoteguyspassword")); this.authenticator
.authenticate(UsernamePasswordAuthenticationToken.unauthenticated("quote\"guy", "quoteguyspassword"));
} }
/* /*
@ -127,8 +132,8 @@ public class BindAuthenticatorTests {
@Test @Test
public void testAuthenticationWithWrongPasswordFails() { public void testAuthenticationWithWrongPasswordFails() {
this.authenticator.setUserDnPatterns(new String[] { "uid={0},ou=people" }); this.authenticator.setUserDnPatterns(new String[] { "uid={0},ou=people" });
assertThatExceptionOfType(BadCredentialsException.class).isThrownBy( assertThatExceptionOfType(BadCredentialsException.class).isThrownBy(() -> this.authenticator
() -> this.authenticator.authenticate(new UsernamePasswordAuthenticationToken("bob", "wrongpassword"))); .authenticate(UsernamePasswordAuthenticationToken.unauthenticated("bob", "wrongpassword")));
} }
@Test @Test

View File

@ -63,8 +63,8 @@ public class PasswordComparisonAuthenticatorTests {
this.authenticator = new PasswordComparisonAuthenticator(this.contextSource); this.authenticator = new PasswordComparisonAuthenticator(this.contextSource);
this.authenticator.setPasswordEncoder(NoOpPasswordEncoder.getInstance()); this.authenticator.setPasswordEncoder(NoOpPasswordEncoder.getInstance());
this.authenticator.setUserDnPatterns(new String[] { "uid={0},ou=people" }); this.authenticator.setUserDnPatterns(new String[] { "uid={0},ou=people" });
this.bob = new UsernamePasswordAuthenticationToken("bob", "bobspassword"); this.bob = UsernamePasswordAuthenticationToken.unauthenticated("bob", "bobspassword");
this.ben = new UsernamePasswordAuthenticationToken("ben", "benspassword"); this.ben = UsernamePasswordAuthenticationToken.unauthenticated("ben", "benspassword");
} }
@Test @Test
@ -81,16 +81,16 @@ public class PasswordComparisonAuthenticatorTests {
.isEmpty(); .isEmpty();
this.authenticator.setUserSearch(new MockUserSearch(null)); this.authenticator.setUserSearch(new MockUserSearch(null));
this.authenticator.afterPropertiesSet(); this.authenticator.afterPropertiesSet();
assertThatExceptionOfType(UsernameNotFoundException.class).isThrownBy( assertThatExceptionOfType(UsernameNotFoundException.class).isThrownBy(() -> this.authenticator
() -> this.authenticator.authenticate(new UsernamePasswordAuthenticationToken("Joe", "pass"))); .authenticate(UsernamePasswordAuthenticationToken.unauthenticated("Joe", "pass")));
} }
@Test @Test
public void testLdapPasswordCompareFailsWithWrongPassword() { public void testLdapPasswordCompareFailsWithWrongPassword() {
// Don't retrieve the password // Don't retrieve the password
this.authenticator.setUserAttributes(new String[] { "uid", "cn", "sn" }); this.authenticator.setUserAttributes(new String[] { "uid", "cn", "sn" });
assertThatExceptionOfType(BadCredentialsException.class).isThrownBy( assertThatExceptionOfType(BadCredentialsException.class).isThrownBy(() -> this.authenticator
() -> this.authenticator.authenticate(new UsernamePasswordAuthenticationToken("bob", "wrongpass"))); .authenticate(UsernamePasswordAuthenticationToken.unauthenticated("bob", "wrongpass")));
} }
@Test @Test
@ -131,14 +131,14 @@ public class PasswordComparisonAuthenticatorTests {
@Test @Test
public void testUseOfDifferentPasswordAttributeSucceeds() { public void testUseOfDifferentPasswordAttributeSucceeds() {
this.authenticator.setPasswordAttributeName("uid"); this.authenticator.setPasswordAttributeName("uid");
this.authenticator.authenticate(new UsernamePasswordAuthenticationToken("bob", "bob")); this.authenticator.authenticate(UsernamePasswordAuthenticationToken.unauthenticated("bob", "bob"));
} }
@Test @Test
public void testLdapCompareWithDifferentPasswordAttributeSucceeds() { public void testLdapCompareWithDifferentPasswordAttributeSucceeds() {
this.authenticator.setUserAttributes(new String[] { "uid" }); this.authenticator.setUserAttributes(new String[] { "uid" });
this.authenticator.setPasswordAttributeName("cn"); this.authenticator.setPasswordAttributeName("cn");
this.authenticator.authenticate(new UsernamePasswordAuthenticationToken("ben", "Ben Alex")); this.authenticator.authenticate(UsernamePasswordAuthenticationToken.unauthenticated("ben", "Ben Alex"));
} }
@Test @Test
@ -152,7 +152,8 @@ public class PasswordComparisonAuthenticatorTests {
ctx.setAttributeValue("userPassword", "bobspassword"); ctx.setAttributeValue("userPassword", "bobspassword");
this.authenticator.setUserSearch(new MockUserSearch(ctx)); this.authenticator.setUserSearch(new MockUserSearch(ctx));
this.authenticator.authenticate(new UsernamePasswordAuthenticationToken("shouldntbeused", "bobspassword")); this.authenticator
.authenticate(UsernamePasswordAuthenticationToken.unauthenticated("shouldntbeused", "bobspassword"));
} }
} }

View File

@ -192,8 +192,8 @@ public class LdapUserDetailsManagerTests {
this.mgr.createUser(p.createUserDetails()); this.mgr.createUser(p.createUserDetails());
SecurityContextHolder.getContext().setAuthentication( SecurityContextHolder.getContext().setAuthentication(UsernamePasswordAuthenticationToken
new UsernamePasswordAuthenticationToken("johnyossarian", "yossarianspassword", TEST_AUTHORITIES)); .authenticated("johnyossarian", "yossarianspassword", TEST_AUTHORITIES));
this.mgr.changePassword("yossarianspassword", "yossariansnewpassword"); this.mgr.changePassword("yossarianspassword", "yossariansnewpassword");
@ -211,8 +211,8 @@ public class LdapUserDetailsManagerTests {
p.setPassword("yossarianspassword"); p.setPassword("yossarianspassword");
p.setAuthorities(TEST_AUTHORITIES); p.setAuthorities(TEST_AUTHORITIES);
this.mgr.createUser(p.createUserDetails()); this.mgr.createUser(p.createUserDetails());
SecurityContextHolder.getContext().setAuthentication( SecurityContextHolder.getContext().setAuthentication(UsernamePasswordAuthenticationToken
new UsernamePasswordAuthenticationToken("johnyossarian", "yossarianspassword", TEST_AUTHORITIES)); .authenticated("johnyossarian", "yossarianspassword", TEST_AUTHORITIES));
assertThatExceptionOfType(BadCredentialsException.class) assertThatExceptionOfType(BadCredentialsException.class)
.isThrownBy(() -> this.mgr.changePassword("wrongpassword", "yossariansnewpassword")); .isThrownBy(() -> this.mgr.changePassword("wrongpassword", "yossariansnewpassword"));
} }

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2021 the original author or authors. * Copyright 2002-2022 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -99,7 +99,7 @@ public abstract class AbstractLdapAuthenticationProvider implements Authenticati
UserDetails user) { UserDetails user) {
Object password = this.useAuthenticationRequestCredentials ? authentication.getCredentials() Object password = this.useAuthenticationRequestCredentials ? authentication.getCredentials()
: user.getPassword(); : user.getPassword();
UsernamePasswordAuthenticationToken result = new UsernamePasswordAuthenticationToken(user, password, UsernamePasswordAuthenticationToken result = UsernamePasswordAuthenticationToken.authenticated(user, password,
this.authoritiesMapper.mapAuthorities(user.getAuthorities())); this.authoritiesMapper.mapAuthorities(user.getAuthorities()));
result.setDetails(authentication.getDetails()); result.setDetails(authentication.getDetails());
this.logger.debug("Authenticated user"); this.logger.debug("Authenticated user");

View File

@ -67,16 +67,17 @@ public class LdapAuthenticationProviderTests {
public void testEmptyOrNullUserNameThrowsException() { public void testEmptyOrNullUserNameThrowsException() {
LdapAuthenticationProvider ldapProvider = new LdapAuthenticationProvider(new MockAuthenticator(), LdapAuthenticationProvider ldapProvider = new LdapAuthenticationProvider(new MockAuthenticator(),
new MockAuthoritiesPopulator()); new MockAuthoritiesPopulator());
assertThatExceptionOfType(BadCredentialsException.class)
.isThrownBy(() -> ldapProvider.authenticate(new UsernamePasswordAuthenticationToken(null, "password")));
assertThatExceptionOfType(BadCredentialsException.class).isThrownBy( assertThatExceptionOfType(BadCredentialsException.class).isThrownBy(
() -> ldapProvider.authenticate(new UsernamePasswordAuthenticationToken("", "bobspassword"))); () -> ldapProvider.authenticate(UsernamePasswordAuthenticationToken.unauthenticated(null, "password")));
assertThatExceptionOfType(BadCredentialsException.class).isThrownBy(() -> ldapProvider
.authenticate(UsernamePasswordAuthenticationToken.unauthenticated("", "bobspassword")));
} }
@Test @Test
public void usernameNotFoundExceptionIsHiddenByDefault() { public void usernameNotFoundExceptionIsHiddenByDefault() {
final LdapAuthenticator authenticator = mock(LdapAuthenticator.class); final LdapAuthenticator authenticator = mock(LdapAuthenticator.class);
final UsernamePasswordAuthenticationToken joe = new UsernamePasswordAuthenticationToken("joe", "password"); final UsernamePasswordAuthenticationToken joe = UsernamePasswordAuthenticationToken.unauthenticated("joe",
"password");
given(authenticator.authenticate(joe)).willThrow(new UsernameNotFoundException("nobody")); given(authenticator.authenticate(joe)).willThrow(new UsernameNotFoundException("nobody"));
LdapAuthenticationProvider provider = new LdapAuthenticationProvider(authenticator); LdapAuthenticationProvider provider = new LdapAuthenticationProvider(authenticator);
assertThatExceptionOfType(BadCredentialsException.class).isThrownBy(() -> provider.authenticate(joe)); assertThatExceptionOfType(BadCredentialsException.class).isThrownBy(() -> provider.authenticate(joe));
@ -85,7 +86,8 @@ public class LdapAuthenticationProviderTests {
@Test @Test
public void usernameNotFoundExceptionIsNotHiddenIfConfigured() { public void usernameNotFoundExceptionIsNotHiddenIfConfigured() {
final LdapAuthenticator authenticator = mock(LdapAuthenticator.class); final LdapAuthenticator authenticator = mock(LdapAuthenticator.class);
final UsernamePasswordAuthenticationToken joe = new UsernamePasswordAuthenticationToken("joe", "password"); final UsernamePasswordAuthenticationToken joe = UsernamePasswordAuthenticationToken.unauthenticated("joe",
"password");
given(authenticator.authenticate(joe)).willThrow(new UsernameNotFoundException("nobody")); given(authenticator.authenticate(joe)).willThrow(new UsernameNotFoundException("nobody"));
LdapAuthenticationProvider provider = new LdapAuthenticationProvider(authenticator); LdapAuthenticationProvider provider = new LdapAuthenticationProvider(authenticator);
provider.setHideUserNotFoundExceptions(false); provider.setHideUserNotFoundExceptions(false);
@ -100,7 +102,7 @@ public class LdapAuthenticationProviderTests {
userMapper.setRoleAttributes(new String[] { "ou" }); userMapper.setRoleAttributes(new String[] { "ou" });
ldapProvider.setUserDetailsContextMapper(userMapper); ldapProvider.setUserDetailsContextMapper(userMapper);
assertThat(ldapProvider.getAuthoritiesPopulator()).isNotNull(); assertThat(ldapProvider.getAuthoritiesPopulator()).isNotNull();
UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken("ben", UsernamePasswordAuthenticationToken authRequest = UsernamePasswordAuthenticationToken.unauthenticated("ben",
"benspassword"); "benspassword");
Object authDetails = new Object(); Object authDetails = new Object();
authRequest.setDetails(authDetails); authRequest.setDetails(authDetails);
@ -121,7 +123,7 @@ public class LdapAuthenticationProviderTests {
LdapAuthenticationProvider ldapProvider = new LdapAuthenticationProvider(new MockAuthenticator(), LdapAuthenticationProvider ldapProvider = new LdapAuthenticationProvider(new MockAuthenticator(),
new MockAuthoritiesPopulator()); new MockAuthoritiesPopulator());
ldapProvider.setUseAuthenticationRequestCredentials(false); ldapProvider.setUseAuthenticationRequestCredentials(false);
UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken("ben", UsernamePasswordAuthenticationToken authRequest = UsernamePasswordAuthenticationToken.unauthenticated("ben",
"benspassword"); "benspassword");
Authentication authResult = ldapProvider.authenticate(authRequest); Authentication authResult = ldapProvider.authenticate(authRequest);
assertThat(authResult.getCredentials()).isEqualTo("{SHA}nFCebWjxfaLbHHG1Qk5UU4trbvQ="); assertThat(authResult.getCredentials()).isEqualTo("{SHA}nFCebWjxfaLbHHG1Qk5UU4trbvQ=");
@ -133,7 +135,7 @@ public class LdapAuthenticationProviderTests {
LdapUserDetailsMapper userMapper = new LdapUserDetailsMapper(); LdapUserDetailsMapper userMapper = new LdapUserDetailsMapper();
userMapper.setRoleAttributes(new String[] { "ou" }); userMapper.setRoleAttributes(new String[] { "ou" });
ldapProvider.setUserDetailsContextMapper(userMapper); ldapProvider.setUserDetailsContextMapper(userMapper);
UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken("ben", UsernamePasswordAuthenticationToken authRequest = UsernamePasswordAuthenticationToken.unauthenticated("ben",
"benspassword"); "benspassword");
UserDetails user = (UserDetails) ldapProvider.authenticate(authRequest).getPrincipal(); UserDetails user = (UserDetails) ldapProvider.authenticate(authRequest).getPrincipal();
assertThat(user.getAuthorities()).hasSize(1); assertThat(user.getAuthorities()).hasSize(1);
@ -142,7 +144,7 @@ public class LdapAuthenticationProviderTests {
@Test @Test
public void authenticateWithNamingException() { public void authenticateWithNamingException() {
UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken("ben", UsernamePasswordAuthenticationToken authRequest = UsernamePasswordAuthenticationToken.unauthenticated("ben",
"benspassword"); "benspassword");
LdapAuthenticator mockAuthenticator = mock(LdapAuthenticator.class); LdapAuthenticator mockAuthenticator = mock(LdapAuthenticator.class);
CommunicationException expectedCause = new CommunicationException(new javax.naming.CommunicationException()); CommunicationException expectedCause = new CommunicationException(new javax.naming.CommunicationException());

View File

@ -53,7 +53,7 @@ public class PasswordComparisonAuthenticatorMockTests {
final NamingEnumeration searchResults = new BasicAttributes("", null).getAll(); final NamingEnumeration searchResults = new BasicAttributes("", null).getAll();
given(dirCtx.search(eq("cn=Bob,ou=people"), eq("(userPassword={0})"), any(Object[].class), given(dirCtx.search(eq("cn=Bob,ou=people"), eq("(userPassword={0})"), any(Object[].class),
any(SearchControls.class))).willReturn(searchResults); any(SearchControls.class))).willReturn(searchResults);
authenticator.authenticate(new UsernamePasswordAuthenticationToken("Bob", "bobspassword")); authenticator.authenticate(UsernamePasswordAuthenticationToken.unauthenticated("Bob", "bobspassword"));
} }
} }

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2016 the original author or authors. * Copyright 2002-2022 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -68,7 +68,7 @@ public class ActiveDirectoryLdapAuthenticationProviderTests {
ActiveDirectoryLdapAuthenticationProvider provider; ActiveDirectoryLdapAuthenticationProvider provider;
UsernamePasswordAuthenticationToken joe = new UsernamePasswordAuthenticationToken("joe", "password"); UsernamePasswordAuthenticationToken joe = UsernamePasswordAuthenticationToken.unauthenticated("joe", "password");
@BeforeEach @BeforeEach
public void setUp() { public void setUp() {
@ -162,7 +162,7 @@ public class ActiveDirectoryLdapAuthenticationProviderTests {
any(SearchControls.class))).willReturn(new MockNamingEnumeration(sr)); any(SearchControls.class))).willReturn(new MockNamingEnumeration(sr));
this.provider.contextFactory = createContextFactoryReturning(ctx); this.provider.contextFactory = createContextFactoryReturning(ctx);
assertThatExceptionOfType(BadCredentialsException.class).isThrownBy(() -> this.provider.authenticate(this.joe)); assertThatExceptionOfType(BadCredentialsException.class).isThrownBy(() -> this.provider.authenticate(this.joe));
this.provider.authenticate(new UsernamePasswordAuthenticationToken("joe@mydomain.eu", "password")); this.provider.authenticate(UsernamePasswordAuthenticationToken.unauthenticated("joe@mydomain.eu", "password"));
} }
@Test @Test
@ -189,8 +189,8 @@ public class ActiveDirectoryLdapAuthenticationProviderTests {
// SEC-2500 // SEC-2500
@Test @Test
public void sec2500PreventAnonymousBind() { public void sec2500PreventAnonymousBind() {
assertThatExceptionOfType(BadCredentialsException.class) assertThatExceptionOfType(BadCredentialsException.class).isThrownBy(
.isThrownBy(() -> this.provider.authenticate(new UsernamePasswordAuthenticationToken("rwinch", ""))); () -> this.provider.authenticate(UsernamePasswordAuthenticationToken.unauthenticated("rwinch", "")));
} }
@Test @Test

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2019-2021 the original author or authors. * Copyright 2019-2022 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -96,7 +96,7 @@ public class AuthenticationPayloadExchangeConverter implements PayloadExchangeAu
String username = rawUsername.toString(StandardCharsets.UTF_8); String username = rawUsername.toString(StandardCharsets.UTF_8);
ByteBuf rawPassword = AuthMetadataCodec.readPassword(rawAuthentication); ByteBuf rawPassword = AuthMetadataCodec.readPassword(rawAuthentication);
String password = rawPassword.toString(StandardCharsets.UTF_8); String password = rawPassword.toString(StandardCharsets.UTF_8);
return new UsernamePasswordAuthenticationToken(username, password); return UsernamePasswordAuthenticationToken.unauthenticated(username, password);
} }
private Authentication bearer(ByteBuf rawAuthentication) { private Authentication bearer(ByteBuf rawAuthentication) {

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2019 the original author or authors. * Copyright 2019-2022 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -49,9 +49,8 @@ public class BasicAuthenticationPayloadExchangeConverter implements PayloadExcha
return Mono.fromCallable(() -> this.metadataExtractor.extract(exchange.getPayload(), this.metadataMimetype)) return Mono.fromCallable(() -> this.metadataExtractor.extract(exchange.getPayload(), this.metadataMimetype))
.flatMap((metadata) -> Mono .flatMap((metadata) -> Mono
.justOrEmpty(metadata.get(UsernamePasswordMetadata.BASIC_AUTHENTICATION_MIME_TYPE.toString()))) .justOrEmpty(metadata.get(UsernamePasswordMetadata.BASIC_AUTHENTICATION_MIME_TYPE.toString())))
.cast(UsernamePasswordMetadata.class) .cast(UsernamePasswordMetadata.class).map((credentials) -> UsernamePasswordAuthenticationToken
.map((credentials) -> new UsernamePasswordAuthenticationToken(credentials.getUsername(), .unauthenticated(credentials.getUsername(), credentials.getPassword()));
credentials.getPassword()));
} }
private static MetadataExtractor createDefaultExtractor() { private static MetadataExtractor createDefaultExtractor() {

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2019 the original author or authors. * Copyright 2019-2022 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -89,8 +89,8 @@ public class AuthenticationPayloadInterceptorTests {
interceptor.intercept(exchange, authenticationPayloadChain).block(); interceptor.intercept(exchange, authenticationPayloadChain).block();
Authentication authentication = authenticationPayloadChain.getAuthentication(); Authentication authentication = authenticationPayloadChain.getAuthentication();
verify(this.authenticationManager).authenticate(this.authenticationArg.capture()); verify(this.authenticationManager).authenticate(this.authenticationArg.capture());
assertThat(this.authenticationArg.getValue()) assertThat(this.authenticationArg.getValue()).isEqualToComparingFieldByField(
.isEqualToComparingFieldByField(new UsernamePasswordAuthenticationToken("user", "password")); UsernamePasswordAuthenticationToken.unauthenticated("user", "password"));
assertThat(authentication).isEqualTo(expectedAuthentication); assertThat(authentication).isEqualTo(expectedAuthentication);
} }

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2018 the original author or authors. * Copyright 2002-2022 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -58,8 +58,8 @@ final class WithMockUserSecurityContextFactory implements WithSecurityContextFac
+ " with authorities attribute " + Arrays.asList(withUser.authorities())); + " with authorities attribute " + Arrays.asList(withUser.authorities()));
} }
User principal = new User(username, withUser.password(), true, true, true, true, grantedAuthorities); User principal = new User(username, withUser.password(), true, true, true, true, grantedAuthorities);
Authentication authentication = new UsernamePasswordAuthenticationToken(principal, principal.getPassword(), Authentication authentication = UsernamePasswordAuthenticationToken.authenticated(principal,
principal.getAuthorities()); principal.getPassword(), principal.getAuthorities());
SecurityContext context = SecurityContextHolder.createEmptyContext(); SecurityContext context = SecurityContextHolder.createEmptyContext();
context.setAuthentication(authentication); context.setAuthentication(authentication);
return context; return context;

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2018 the original author or authors. * Copyright 2002-2022 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -59,8 +59,8 @@ final class WithUserDetailsSecurityContextFactory implements WithSecurityContext
String username = withUser.value(); String username = withUser.value();
Assert.hasLength(username, "value() must be non empty String"); Assert.hasLength(username, "value() must be non empty String");
UserDetails principal = userDetailsService.loadUserByUsername(username); UserDetails principal = userDetailsService.loadUserByUsername(username);
Authentication authentication = new UsernamePasswordAuthenticationToken(principal, principal.getPassword(), Authentication authentication = UsernamePasswordAuthenticationToken.authenticated(principal,
principal.getAuthorities()); principal.getPassword(), principal.getAuthorities());
SecurityContext context = SecurityContextHolder.createEmptyContext(); SecurityContext context = SecurityContextHolder.createEmptyContext();
context.setAuthentication(authentication); context.setAuthentication(authentication);
return context; return context;

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2021 the original author or authors. * Copyright 2002-2022 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -134,8 +134,8 @@ public final class SecurityMockServerConfigurers {
* @return the configurer to use * @return the configurer to use
*/ */
public static <T extends WebTestClientConfigurer & MockServerConfigurer> T mockUser(UserDetails userDetails) { public static <T extends WebTestClientConfigurer & MockServerConfigurer> T mockUser(UserDetails userDetails) {
return mockAuthentication(new UsernamePasswordAuthenticationToken(userDetails, userDetails.getPassword(), return mockAuthentication(UsernamePasswordAuthenticationToken.authenticated(userDetails,
userDetails.getAuthorities())); userDetails.getPassword(), userDetails.getAuthorities()));
} }
/** /**

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2021 the original author or authors. * Copyright 2002-2022 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -872,7 +872,7 @@ public final class SecurityMockMvcRequestPostProcessors {
private final RequestPostProcessor delegate; private final RequestPostProcessor delegate;
UserDetailsRequestPostProcessor(UserDetails user) { UserDetailsRequestPostProcessor(UserDetails user) {
Authentication token = new UsernamePasswordAuthenticationToken(user, user.getPassword(), Authentication token = UsernamePasswordAuthenticationToken.authenticated(user, user.getPassword(),
user.getAuthorities()); user.getAuthorities());
this.delegate = new AuthenticationRequestPostProcessor(token); this.delegate = new AuthenticationRequestPostProcessor(token);
} }

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2016 the original author or authors. * Copyright 2002-2022 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -31,7 +31,7 @@ public class WithMockCustomUserSecurityContextFactory implements WithSecurityCon
public SecurityContext createSecurityContext(WithMockCustomUser customUser) { public SecurityContext createSecurityContext(WithMockCustomUser customUser) {
SecurityContext context = SecurityContextHolder.createEmptyContext(); SecurityContext context = SecurityContextHolder.createEmptyContext();
CustomUserDetails principal = new CustomUserDetails(customUser.name(), customUser.username()); CustomUserDetails principal = new CustomUserDetails(customUser.name(), customUser.username());
Authentication auth = new UsernamePasswordAuthenticationToken(principal, "password", Authentication auth = UsernamePasswordAuthenticationToken.authenticated(principal, "password",
principal.getAuthorities()); principal.getAuthorities());
context.setAuthentication(auth); context.setAuthentication(auth);
return context; return context;

View File

@ -79,7 +79,8 @@ public class UsernamePasswordAuthenticationFilter extends AbstractAuthentication
username = username.trim(); username = username.trim();
String password = obtainPassword(request); String password = obtainPassword(request);
password = (password != null) ? password : ""; password = (password != null) ? password : "";
UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(username, password); UsernamePasswordAuthenticationToken authRequest = UsernamePasswordAuthenticationToken.unauthenticated(username,
password);
// Allow subclasses to set the "details" property // Allow subclasses to set the "details" property
setDetails(request, authRequest); setDetails(request, authRequest);
return this.getAuthenticationManager().authenticate(authRequest); return this.getAuthenticationManager().authenticate(authRequest);

View File

@ -297,7 +297,8 @@ public class SwitchUserFilter extends GenericFilterBean implements ApplicationEv
List<GrantedAuthority> newAuths = new ArrayList<>(orig); List<GrantedAuthority> newAuths = new ArrayList<>(orig);
newAuths.add(switchAuthority); newAuths.add(switchAuthority);
// create the new authentication token // create the new authentication token
targetUserRequest = new UsernamePasswordAuthenticationToken(targetUser, targetUser.getPassword(), newAuths); targetUserRequest = UsernamePasswordAuthenticationToken.authenticated(targetUser, targetUser.getPassword(),
newAuths);
// set details // set details
targetUserRequest.setDetails(this.authenticationDetailsSource.buildDetails(request)); targetUserRequest.setDetails(this.authenticationDetailsSource.buildDetails(request));
return targetUserRequest; return targetUserRequest;

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2019 the original author or authors. * Copyright 2002-2022 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -94,8 +94,8 @@ public class BasicAuthenticationConverter implements AuthenticationConverter {
if (delim == -1) { if (delim == -1) {
throw new BadCredentialsException("Invalid basic authentication token"); throw new BadCredentialsException("Invalid basic authentication token");
} }
UsernamePasswordAuthenticationToken result = new UsernamePasswordAuthenticationToken(token.substring(0, delim), UsernamePasswordAuthenticationToken result = UsernamePasswordAuthenticationToken
token.substring(delim + 1)); .unauthenticated(token.substring(0, delim), token.substring(delim + 1));
result.setDetails(this.authenticationDetailsSource.buildDetails(request)); result.setDetails(this.authenticationDetailsSource.buildDetails(request));
return result; return result;
} }

View File

@ -208,9 +208,9 @@ public class DigestAuthenticationFilter extends GenericFilterBean implements Mes
private UsernamePasswordAuthenticationToken getAuthRequest(UserDetails user) { private UsernamePasswordAuthenticationToken getAuthRequest(UserDetails user) {
if (this.createAuthenticatedToken) { if (this.createAuthenticatedToken) {
return new UsernamePasswordAuthenticationToken(user, user.getPassword(), user.getAuthorities()); return UsernamePasswordAuthenticationToken.authenticated(user, user.getPassword(), user.getAuthorities());
} }
return new UsernamePasswordAuthenticationToken(user, user.getPassword()); return UsernamePasswordAuthenticationToken.unauthenticated(user, user.getPassword());
} }
private void fail(HttpServletRequest request, HttpServletResponse response, AuthenticationException failed) private void fail(HttpServletRequest request, HttpServletResponse response, AuthenticationException failed)

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2017 the original author or authors. * Copyright 2002-2022 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -52,7 +52,7 @@ public class ServerFormLoginAuthenticationConverter implements Function<ServerWe
private UsernamePasswordAuthenticationToken createAuthentication(MultiValueMap<String, String> data) { private UsernamePasswordAuthenticationToken createAuthentication(MultiValueMap<String, String> data) {
String username = data.getFirst(this.usernameParameter); String username = data.getFirst(this.usernameParameter);
String password = data.getFirst(this.passwordParameter); String password = data.getFirst(this.passwordParameter);
return new UsernamePasswordAuthenticationToken(username, password); return UsernamePasswordAuthenticationToken.unauthenticated(username, password);
} }
/** /**

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2018 the original author or authors. * Copyright 2002-2022 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -58,7 +58,7 @@ public class ServerHttpBasicAuthenticationConverter implements Function<ServerWe
if (parts.length != 2) { if (parts.length != 2) {
return Mono.empty(); return Mono.empty();
} }
return Mono.just(new UsernamePasswordAuthenticationToken(parts[0], parts[1])); return Mono.just(UsernamePasswordAuthenticationToken.unauthenticated(parts[0], parts[1]));
} }
private byte[] base64Decode(String value) { private byte[] base64Decode(String value) {

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2020 the original author or authors. * Copyright 2002-2022 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -261,7 +261,7 @@ public class SwitchUserWebFilter implements WebFilter {
Collection<? extends GrantedAuthority> targetUserAuthorities = targetUser.getAuthorities(); Collection<? extends GrantedAuthority> targetUserAuthorities = targetUser.getAuthorities();
List<GrantedAuthority> extendedTargetUserAuthorities = new ArrayList<>(targetUserAuthorities); List<GrantedAuthority> extendedTargetUserAuthorities = new ArrayList<>(targetUserAuthorities);
extendedTargetUserAuthorities.add(switchAuthority); extendedTargetUserAuthorities.add(switchAuthority);
return new UsernamePasswordAuthenticationToken(targetUser, targetUser.getPassword(), return UsernamePasswordAuthenticationToken.authenticated(targetUser, targetUser.getPassword(),
extendedTargetUserAuthorities); extendedTargetUserAuthorities);
} }

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2021 the original author or authors. * Copyright 2002-2022 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -237,8 +237,8 @@ final class HttpServlet3RequestFactory implements HttpServletRequestFactory {
private Authentication getAuthentication(AuthenticationManager authManager, String username, String password) private Authentication getAuthentication(AuthenticationManager authManager, String username, String password)
throws ServletException { throws ServletException {
try { try {
UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(username, UsernamePasswordAuthenticationToken authentication = UsernamePasswordAuthenticationToken
password); .unauthenticated(username, password);
Object details = HttpServlet3RequestFactory.this.authenticationDetailsSource.buildDetails(this); Object details = HttpServlet3RequestFactory.this.authenticationDetailsSource.buildDetails(this);
authentication.setDetails(details); authentication.setDetails(details);
return authManager.authenticate(authentication); return authManager.authenticate(authentication);

View File

@ -440,7 +440,7 @@ public class AbstractAuthenticationProcessingFilterTests {
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
throws AuthenticationException { throws AuthenticationException {
if (this.grantAccess) { if (this.grantAccess) {
return new UsernamePasswordAuthenticationToken("test", "test", return UsernamePasswordAuthenticationToken.authenticated("test", "test",
AuthorityUtils.createAuthorityList("TEST")); AuthorityUtils.createAuthorityList("TEST"));
} }
else { else {

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2016 the original author or authors. * Copyright 2002-2022 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -280,8 +280,8 @@ public class AbstractPreAuthenticatedProcessingFilterTests {
@Test @Test
public void requiresAuthenticationFalsePrincipalUser() throws Exception { public void requiresAuthenticationFalsePrincipalUser() throws Exception {
User currentPrincipal = new User("user", "password", AuthorityUtils.createAuthorityList("ROLE_USER")); User currentPrincipal = new User("user", "password", AuthorityUtils.createAuthorityList("ROLE_USER"));
UsernamePasswordAuthenticationToken currentAuthentication = new UsernamePasswordAuthenticationToken( UsernamePasswordAuthenticationToken currentAuthentication = UsernamePasswordAuthenticationToken
currentPrincipal, currentPrincipal.getPassword(), currentPrincipal.getAuthorities()); .authenticated(currentPrincipal, currentPrincipal.getPassword(), currentPrincipal.getAuthorities());
SecurityContextHolder.getContext().setAuthentication(currentAuthentication); SecurityContextHolder.getContext().setAuthentication(currentAuthentication);
MockHttpServletRequest request = new MockHttpServletRequest(); MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse(); MockHttpServletResponse response = new MockHttpServletResponse();

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2016 the original author or authors. * Copyright 2002-2022 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -46,7 +46,7 @@ public class PreAuthenticatedAuthenticationProviderTests {
public final void authenticateInvalidToken() throws Exception { public final void authenticateInvalidToken() throws Exception {
UserDetails ud = new User("dummyUser", "dummyPwd", true, true, true, true, AuthorityUtils.NO_AUTHORITIES); UserDetails ud = new User("dummyUser", "dummyPwd", true, true, true, true, AuthorityUtils.NO_AUTHORITIES);
PreAuthenticatedAuthenticationProvider provider = getProvider(ud); PreAuthenticatedAuthenticationProvider provider = getProvider(ud);
Authentication request = new UsernamePasswordAuthenticationToken("dummyUser", "dummyPwd"); Authentication request = UsernamePasswordAuthenticationToken.unauthenticated("dummyUser", "dummyPwd");
Authentication result = provider.authenticate(request); Authentication result = provider.authenticate(request);
assertThat(result).isNull(); assertThat(result).isNull();
} }

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2020 the original author or authors. * Copyright 2002-2022 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -287,7 +287,7 @@ public class AbstractRememberMeServicesTests {
MockRememberMeServices services = new MockRememberMeServices(this.uds); MockRememberMeServices services = new MockRememberMeServices(this.uds);
MockHttpServletRequest request = new MockHttpServletRequest(); MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse(); MockHttpServletResponse response = new MockHttpServletResponse();
Authentication auth = new UsernamePasswordAuthenticationToken("joe", "password"); Authentication auth = UsernamePasswordAuthenticationToken.unauthenticated("joe", "password");
// No parameter set // No parameter set
services.loginSuccess(request, response, auth); services.loginSuccess(request, response, auth);
assertThat(services.loginSuccessCalled).isFalse(); assertThat(services.loginSuccessCalled).isFalse();

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2017 the original author or authors. * Copyright 2002-2022 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -108,7 +108,7 @@ public class PersistentTokenBasedRememberMeServicesTests {
this.services.setSeriesLength(12); this.services.setSeriesLength(12);
MockHttpServletResponse response = new MockHttpServletResponse(); MockHttpServletResponse response = new MockHttpServletResponse();
this.services.loginSuccess(new MockHttpServletRequest(), response, this.services.loginSuccess(new MockHttpServletRequest(), response,
new UsernamePasswordAuthenticationToken("joe", "password")); UsernamePasswordAuthenticationToken.unauthenticated("joe", "password"));
assertThat(this.repo.getStoredToken().getSeries().length()).isEqualTo(16); assertThat(this.repo.getStoredToken().getSeries().length()).isEqualTo(16);
assertThat(this.repo.getStoredToken().getTokenValue().length()).isEqualTo(16); assertThat(this.repo.getStoredToken().getTokenValue().length()).isEqualTo(16);
String[] cookie = this.services.decodeCookie(response.getCookie("mycookiename").getValue()); String[] cookie = this.services.decodeCookie(response.getCookie("mycookiename").getValue());

View File

@ -66,7 +66,8 @@ public class SwitchUserFilterTests {
@BeforeEach @BeforeEach
public void authenticateCurrentUser() { public void authenticateCurrentUser() {
UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken("dano", "hawaii50"); UsernamePasswordAuthenticationToken auth = UsernamePasswordAuthenticationToken.unauthenticated("dano",
"hawaii50");
SecurityContextHolder.getContext().setAuthentication(auth); SecurityContextHolder.getContext().setAuthentication(auth);
} }
@ -278,14 +279,14 @@ public class SwitchUserFilterTests {
@Test @Test
public void exitUserJackLordToDanoSucceeds() throws Exception { public void exitUserJackLordToDanoSucceeds() throws Exception {
// original user // original user
UsernamePasswordAuthenticationToken source = new UsernamePasswordAuthenticationToken("dano", "hawaii50", UsernamePasswordAuthenticationToken source = UsernamePasswordAuthenticationToken.authenticated("dano",
ROLES_12); "hawaii50", ROLES_12);
// set current user (Admin) // set current user (Admin)
List<GrantedAuthority> adminAuths = new ArrayList<>(); List<GrantedAuthority> adminAuths = new ArrayList<>();
adminAuths.addAll(ROLES_12); adminAuths.addAll(ROLES_12);
adminAuths.add(new SwitchUserGrantedAuthority("PREVIOUS_ADMINISTRATOR", source)); adminAuths.add(new SwitchUserGrantedAuthority("PREVIOUS_ADMINISTRATOR", source));
UsernamePasswordAuthenticationToken admin = new UsernamePasswordAuthenticationToken("jacklord", "hawaii50", UsernamePasswordAuthenticationToken admin = UsernamePasswordAuthenticationToken.authenticated("jacklord",
adminAuths); "hawaii50", adminAuths);
SecurityContextHolder.getContext().setAuthentication(admin); SecurityContextHolder.getContext().setAuthentication(admin);
MockHttpServletRequest request = createMockSwitchRequest(); MockHttpServletRequest request = createMockSwitchRequest();
request.setRequestURI("/logout/impersonate"); request.setRequestURI("/logout/impersonate");
@ -343,7 +344,8 @@ public class SwitchUserFilterTests {
@Test @Test
public void redirectOmitsContextPathIfUseRelativeContextSet() throws Exception { public void redirectOmitsContextPathIfUseRelativeContextSet() throws Exception {
// set current user // set current user
UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken("dano", "hawaii50"); UsernamePasswordAuthenticationToken auth = UsernamePasswordAuthenticationToken.unauthenticated("dano",
"hawaii50");
SecurityContextHolder.getContext().setAuthentication(auth); SecurityContextHolder.getContext().setAuthentication(auth);
MockHttpServletRequest request = createMockSwitchRequest(); MockHttpServletRequest request = createMockSwitchRequest();
request.setContextPath("/webapp"); request.setContextPath("/webapp");
@ -368,7 +370,8 @@ public class SwitchUserFilterTests {
@Test @Test
public void testSwitchRequestFromDanoToJackLord() throws Exception { public void testSwitchRequestFromDanoToJackLord() throws Exception {
// set current user // set current user
UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken("dano", "hawaii50"); UsernamePasswordAuthenticationToken auth = UsernamePasswordAuthenticationToken.unauthenticated("dano",
"hawaii50");
SecurityContextHolder.getContext().setAuthentication(auth); SecurityContextHolder.getContext().setAuthentication(auth);
// http request // http request
MockHttpServletRequest request = new MockHttpServletRequest(); MockHttpServletRequest request = new MockHttpServletRequest();
@ -395,7 +398,8 @@ public class SwitchUserFilterTests {
@Test @Test
public void modificationOfAuthoritiesWorks() { public void modificationOfAuthoritiesWorks() {
UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken("dano", "hawaii50"); UsernamePasswordAuthenticationToken auth = UsernamePasswordAuthenticationToken.unauthenticated("dano",
"hawaii50");
SecurityContextHolder.getContext().setAuthentication(auth); SecurityContextHolder.getContext().setAuthentication(auth);
MockHttpServletRequest request = new MockHttpServletRequest(); MockHttpServletRequest request = new MockHttpServletRequest();
request.addParameter(SwitchUserFilter.SPRING_SECURITY_SWITCH_USERNAME_KEY, "jacklord"); request.addParameter(SwitchUserFilter.SPRING_SECURITY_SWITCH_USERNAME_KEY, "jacklord");
@ -416,8 +420,8 @@ public class SwitchUserFilterTests {
@Test @Test
public void nestedSwitchesAreNotAllowed() { public void nestedSwitchesAreNotAllowed() {
// original user // original user
UsernamePasswordAuthenticationToken source = new UsernamePasswordAuthenticationToken("orig", "hawaii50", UsernamePasswordAuthenticationToken source = UsernamePasswordAuthenticationToken.authenticated("orig",
ROLES_12); "hawaii50", ROLES_12);
SecurityContextHolder.getContext().setAuthentication(source); SecurityContextHolder.getContext().setAuthentication(source);
SecurityContextHolder.getContext().setAuthentication(switchToUser("jacklord")); SecurityContextHolder.getContext().setAuthentication(switchToUser("jacklord"));
Authentication switched = switchToUser("dano"); Authentication switched = switchToUser("dano");
@ -444,8 +448,8 @@ public class SwitchUserFilterTests {
public void switchAuthorityRoleCanBeChanged() { public void switchAuthorityRoleCanBeChanged() {
String switchAuthorityRole = "PREVIOUS_ADMINISTRATOR"; String switchAuthorityRole = "PREVIOUS_ADMINISTRATOR";
// original user // original user
UsernamePasswordAuthenticationToken source = new UsernamePasswordAuthenticationToken("orig", "hawaii50", UsernamePasswordAuthenticationToken source = UsernamePasswordAuthenticationToken.authenticated("orig",
ROLES_12); "hawaii50", ROLES_12);
SecurityContextHolder.getContext().setAuthentication(source); SecurityContextHolder.getContext().setAuthentication(source);
SecurityContextHolder.getContext().setAuthentication(switchToUser("jacklord")); SecurityContextHolder.getContext().setAuthentication(switchToUser("jacklord"));
Authentication switched = switchToUserWithAuthorityRole("dano", switchAuthorityRole); Authentication switched = switchToUserWithAuthorityRole("dano", switchAuthorityRole);

View File

@ -67,9 +67,10 @@ public class BasicAuthenticationFilterTests {
@BeforeEach @BeforeEach
public void setUp() { public void setUp() {
SecurityContextHolder.clearContext(); SecurityContextHolder.clearContext();
UsernamePasswordAuthenticationToken rodRequest = new UsernamePasswordAuthenticationToken("rod", "koala"); UsernamePasswordAuthenticationToken rodRequest = UsernamePasswordAuthenticationToken.unauthenticated("rod",
"koala");
rodRequest.setDetails(new WebAuthenticationDetails(new MockHttpServletRequest())); rodRequest.setDetails(new WebAuthenticationDetails(new MockHttpServletRequest()));
Authentication rod = new UsernamePasswordAuthenticationToken("rod", "koala", Authentication rod = UsernamePasswordAuthenticationToken.authenticated("rod", "koala",
AuthorityUtils.createAuthorityList("ROLE_1")); AuthorityUtils.createAuthorityList("ROLE_1"));
this.manager = mock(AuthenticationManager.class); this.manager = mock(AuthenticationManager.class);
given(this.manager.authenticate(rodRequest)).willReturn(rod); given(this.manager.authenticate(rodRequest)).willReturn(rod);
@ -274,9 +275,10 @@ public class BasicAuthenticationFilterTests {
@Test @Test
public void doFilterWhenTokenAndFilterCharsetMatchDefaultThenAuthenticated() throws Exception { public void doFilterWhenTokenAndFilterCharsetMatchDefaultThenAuthenticated() throws Exception {
SecurityContextHolder.clearContext(); SecurityContextHolder.clearContext();
UsernamePasswordAuthenticationToken rodRequest = new UsernamePasswordAuthenticationToken("rod", "äöü"); UsernamePasswordAuthenticationToken rodRequest = UsernamePasswordAuthenticationToken.unauthenticated("rod",
"äöü");
rodRequest.setDetails(new WebAuthenticationDetails(new MockHttpServletRequest())); rodRequest.setDetails(new WebAuthenticationDetails(new MockHttpServletRequest()));
Authentication rod = new UsernamePasswordAuthenticationToken("rod", "äöü", Authentication rod = UsernamePasswordAuthenticationToken.authenticated("rod", "äöü",
AuthorityUtils.createAuthorityList("ROLE_1")); AuthorityUtils.createAuthorityList("ROLE_1"));
this.manager = mock(AuthenticationManager.class); this.manager = mock(AuthenticationManager.class);
given(this.manager.authenticate(rodRequest)).willReturn(rod); given(this.manager.authenticate(rodRequest)).willReturn(rod);
@ -301,9 +303,10 @@ public class BasicAuthenticationFilterTests {
@Test @Test
public void doFilterWhenTokenAndFilterCharsetMatchNonDefaultThenAuthenticated() throws Exception { public void doFilterWhenTokenAndFilterCharsetMatchNonDefaultThenAuthenticated() throws Exception {
SecurityContextHolder.clearContext(); SecurityContextHolder.clearContext();
UsernamePasswordAuthenticationToken rodRequest = new UsernamePasswordAuthenticationToken("rod", "äöü"); UsernamePasswordAuthenticationToken rodRequest = UsernamePasswordAuthenticationToken.unauthenticated("rod",
"äöü");
rodRequest.setDetails(new WebAuthenticationDetails(new MockHttpServletRequest())); rodRequest.setDetails(new WebAuthenticationDetails(new MockHttpServletRequest()));
Authentication rod = new UsernamePasswordAuthenticationToken("rod", "äöü", Authentication rod = UsernamePasswordAuthenticationToken.authenticated("rod", "äöü",
AuthorityUtils.createAuthorityList("ROLE_1")); AuthorityUtils.createAuthorityList("ROLE_1"));
this.manager = mock(AuthenticationManager.class); this.manager = mock(AuthenticationManager.class);
given(this.manager.authenticate(rodRequest)).willReturn(rod); given(this.manager.authenticate(rodRequest)).willReturn(rod);
@ -329,9 +332,10 @@ public class BasicAuthenticationFilterTests {
@Test @Test
public void doFilterWhenTokenAndFilterCharsetDoNotMatchThenUnauthorized() throws Exception { public void doFilterWhenTokenAndFilterCharsetDoNotMatchThenUnauthorized() throws Exception {
SecurityContextHolder.clearContext(); SecurityContextHolder.clearContext();
UsernamePasswordAuthenticationToken rodRequest = new UsernamePasswordAuthenticationToken("rod", "äöü"); UsernamePasswordAuthenticationToken rodRequest = UsernamePasswordAuthenticationToken.unauthenticated("rod",
"äöü");
rodRequest.setDetails(new WebAuthenticationDetails(new MockHttpServletRequest())); rodRequest.setDetails(new WebAuthenticationDetails(new MockHttpServletRequest()));
Authentication rod = new UsernamePasswordAuthenticationToken("rod", "äöü", Authentication rod = UsernamePasswordAuthenticationToken.authenticated("rod", "äöü",
AuthorityUtils.createAuthorityList("ROLE_1")); AuthorityUtils.createAuthorityList("ROLE_1"));
this.manager = mock(AuthenticationManager.class); this.manager = mock(AuthenticationManager.class);
given(this.manager.authenticate(rodRequest)).willReturn(rod); given(this.manager.authenticate(rodRequest)).willReturn(rod);

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2021 the original author or authors. * Copyright 2002-2022 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -728,7 +728,7 @@ public class HttpSessionSecurityContextRepositoryTests {
} }
private SecurityContext createSecurityContext(UserDetails userDetails) { private SecurityContext createSecurityContext(UserDetails userDetails) {
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(userDetails, UsernamePasswordAuthenticationToken token = UsernamePasswordAuthenticationToken.authenticated(userDetails,
userDetails.getPassword(), userDetails.getAuthorities()); userDetails.getPassword(), userDetails.getAuthorities());
SecurityContext securityContext = new SecurityContextImpl(token); SecurityContext securityContext = new SecurityContextImpl(token);
return securityContext; return securityContext;

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2020 the original author or authors. * Copyright 2002-2022 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -110,7 +110,7 @@ public class SwitchUserWebFilterTests {
final MockServerWebExchange exchange = MockServerWebExchange final MockServerWebExchange exchange = MockServerWebExchange
.from(MockServerHttpRequest.post("/login/impersonate?username={targetUser}", targetUsername)); .from(MockServerHttpRequest.post("/login/impersonate?username={targetUser}", targetUsername));
final WebFilterChain chain = mock(WebFilterChain.class); final WebFilterChain chain = mock(WebFilterChain.class);
final Authentication originalAuthentication = new UsernamePasswordAuthenticationToken("principal", final Authentication originalAuthentication = UsernamePasswordAuthenticationToken.unauthenticated("principal",
"credentials"); "credentials");
final SecurityContextImpl securityContext = new SecurityContextImpl(originalAuthentication); final SecurityContextImpl securityContext = new SecurityContextImpl(originalAuthentication);
given(this.userDetailsService.findByUsername(targetUsername)).willReturn(Mono.just(switchUserDetails)); given(this.userDetailsService.findByUsername(targetUsername)).willReturn(Mono.just(switchUserDetails));
@ -143,12 +143,12 @@ public class SwitchUserWebFilterTests {
@Test @Test
public void switchUserWhenUserAlreadySwitchedThenExitSwitchAndSwitchAgain() { public void switchUserWhenUserAlreadySwitchedThenExitSwitchAndSwitchAgain() {
final Authentication originalAuthentication = new UsernamePasswordAuthenticationToken("origPrincipal", final Authentication originalAuthentication = UsernamePasswordAuthenticationToken
"origCredentials"); .unauthenticated("origPrincipal", "origCredentials");
final GrantedAuthority switchAuthority = new SwitchUserGrantedAuthority( final GrantedAuthority switchAuthority = new SwitchUserGrantedAuthority(
SwitchUserWebFilter.ROLE_PREVIOUS_ADMINISTRATOR, originalAuthentication); SwitchUserWebFilter.ROLE_PREVIOUS_ADMINISTRATOR, originalAuthentication);
final Authentication switchUserAuthentication = new UsernamePasswordAuthenticationToken("switchPrincipal", final Authentication switchUserAuthentication = UsernamePasswordAuthenticationToken
"switchCredentials", Collections.singleton(switchAuthority)); .authenticated("switchPrincipal", "switchCredentials", Collections.singleton(switchAuthority));
final SecurityContextImpl securityContext = new SecurityContextImpl(switchUserAuthentication); final SecurityContextImpl securityContext = new SecurityContextImpl(switchUserAuthentication);
final String targetUsername = "newSwitchPrincipal"; final String targetUsername = "newSwitchPrincipal";
final MockServerWebExchange exchange = MockServerWebExchange final MockServerWebExchange exchange = MockServerWebExchange
@ -228,12 +228,12 @@ public class SwitchUserWebFilterTests {
public void exitSwitchThenReturnToOriginalAuthentication() { public void exitSwitchThenReturnToOriginalAuthentication() {
final MockServerWebExchange exchange = MockServerWebExchange final MockServerWebExchange exchange = MockServerWebExchange
.from(MockServerHttpRequest.post("/logout/impersonate")); .from(MockServerHttpRequest.post("/logout/impersonate"));
final Authentication originalAuthentication = new UsernamePasswordAuthenticationToken("origPrincipal", final Authentication originalAuthentication = UsernamePasswordAuthenticationToken
"origCredentials"); .unauthenticated("origPrincipal", "origCredentials");
final GrantedAuthority switchAuthority = new SwitchUserGrantedAuthority( final GrantedAuthority switchAuthority = new SwitchUserGrantedAuthority(
SwitchUserWebFilter.ROLE_PREVIOUS_ADMINISTRATOR, originalAuthentication); SwitchUserWebFilter.ROLE_PREVIOUS_ADMINISTRATOR, originalAuthentication);
final Authentication switchUserAuthentication = new UsernamePasswordAuthenticationToken("switchPrincipal", final Authentication switchUserAuthentication = UsernamePasswordAuthenticationToken
"switchCredentials", Collections.singleton(switchAuthority)); .authenticated("switchPrincipal", "switchCredentials", Collections.singleton(switchAuthority));
final WebFilterChain chain = mock(WebFilterChain.class); final WebFilterChain chain = mock(WebFilterChain.class);
final SecurityContextImpl securityContext = new SecurityContextImpl(switchUserAuthentication); final SecurityContextImpl securityContext = new SecurityContextImpl(switchUserAuthentication);
given(this.serverSecurityContextRepository.save(eq(exchange), any(SecurityContext.class))) given(this.serverSecurityContextRepository.save(eq(exchange), any(SecurityContext.class)))
@ -259,8 +259,8 @@ public class SwitchUserWebFilterTests {
public void exitSwitchWhenUserNotSwitchedThenThrowError() { public void exitSwitchWhenUserNotSwitchedThenThrowError() {
final MockServerWebExchange exchange = MockServerWebExchange final MockServerWebExchange exchange = MockServerWebExchange
.from(MockServerHttpRequest.post("/logout/impersonate")); .from(MockServerHttpRequest.post("/logout/impersonate"));
final Authentication originalAuthentication = new UsernamePasswordAuthenticationToken("origPrincipal", final Authentication originalAuthentication = UsernamePasswordAuthenticationToken
"origCredentials"); .unauthenticated("origPrincipal", "origCredentials");
final WebFilterChain chain = mock(WebFilterChain.class); final WebFilterChain chain = mock(WebFilterChain.class);
final SecurityContextImpl securityContext = new SecurityContextImpl(originalAuthentication); final SecurityContextImpl securityContext = new SecurityContextImpl(originalAuthentication);
assertThatExceptionOfType(AuthenticationCredentialsNotFoundException.class).isThrownBy(() -> { assertThatExceptionOfType(AuthenticationCredentialsNotFoundException.class).isThrownBy(() -> {