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");
* 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.class);
Authentication auth = authenticationManager
.authenticate(new UsernamePasswordAuthenticationToken("ben", "benspassword"));
.authenticate(UsernamePasswordAuthenticationToken.unauthenticated("ben", "benspassword"));
UserDetails ben = (UserDetails) auth.getPrincipal();
assertThat(ben.getAuthorities()).hasSize(3);
}
@ -89,7 +89,7 @@ public class LdapProviderBeanDefinitionParserTests {
AuthenticationManager authenticationManager = this.appCtx.getBean(BeanIds.AUTHENTICATION_MANAGER,
AuthenticationManager.class);
Authentication auth = authenticationManager
.authenticate(new UsernamePasswordAuthenticationToken("ben", "benspassword"));
.authenticate(UsernamePasswordAuthenticationToken.unauthenticated("ben", "benspassword"));
assertThat(auth).isNotNull();
}
@ -104,7 +104,8 @@ public class LdapProviderBeanDefinitionParserTests {
AuthenticationManager authenticationManager = this.appCtx.getBean(BeanIds.AUTHENTICATION_MANAGER,
AuthenticationManager.class);
Authentication auth = authenticationManager.authenticate(new UsernamePasswordAuthenticationToken("ben", "ben"));
Authentication auth = authenticationManager
.authenticate(UsernamePasswordAuthenticationToken.unauthenticated("ben", "ben"));
assertThat(auth).isNotNull();
}
@ -121,7 +122,7 @@ public class LdapProviderBeanDefinitionParserTests {
AuthenticationManager authenticationManager = this.appCtx.getBean(BeanIds.AUTHENTICATION_MANAGER,
AuthenticationManager.class);
Authentication auth = authenticationManager
.authenticate(new UsernamePasswordAuthenticationToken("bcrypt", "password"));
.authenticate(UsernamePasswordAuthenticationToken.unauthenticated("bcrypt", "password"));
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");
* 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));
AuthenticationManager am = new AuthenticationManagerBuilder(opp).authenticationEventPublisher(aep)
.inMemoryAuthentication().and().build();
assertThatExceptionOfType(AuthenticationException.class)
.isThrownBy(() -> am.authenticate(new UsernamePasswordAuthenticationToken("user", "password")));
assertThatExceptionOfType(AuthenticationException.class).isThrownBy(
() -> am.authenticate(UsernamePasswordAuthenticationToken.unauthenticated("user", "password")));
verify(aep).publishAuthenticationFailure(any(), any());
}
@ -103,7 +103,8 @@ public class AuthenticationManagerBuilderTests {
this.spring.register(PasswordEncoderGlobalConfig.class).autowire();
AuthenticationManager manager = this.spring.getContext().getBean(AuthenticationConfiguration.class)
.getAuthenticationManager();
Authentication auth = manager.authenticate(new UsernamePasswordAuthenticationToken("user", "password"));
Authentication auth = manager
.authenticate(UsernamePasswordAuthenticationToken.unauthenticated("user", "password"));
assertThat(auth.getName()).isEqualTo("user");
assertThat(auth.getAuthorities()).extracting(GrantedAuthority::getAuthority).containsOnly("ROLE_USER");
}
@ -113,7 +114,8 @@ public class AuthenticationManagerBuilderTests {
this.spring.register(PasswordEncoderGlobalConfig.class).autowire();
AuthenticationManager manager = this.spring.getContext().getBean(AuthenticationConfiguration.class)
.getAuthenticationManager();
Authentication auth = manager.authenticate(new UsernamePasswordAuthenticationToken("user", "password"));
Authentication auth = manager
.authenticate(UsernamePasswordAuthenticationToken.unauthenticated("user", "password"));
assertThat(auth.getName()).isEqualTo("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");
* you may not use this file except in compliance with the License.
@ -47,7 +47,8 @@ public class AuthenticationConfigurationPublishTests {
// gh-4940
@Test
public void authenticationEventPublisherBeanUsedByDefault() {
this.authenticationManager.authenticate(new UsernamePasswordAuthenticationToken("user", "password"));
this.authenticationManager
.authenticate(UsernamePasswordAuthenticationToken.unauthenticated("user", "password"));
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");
* you may not use this file except in compliance with the License.
@ -129,7 +129,8 @@ public class AuthenticationConfigurationTests {
@Test
public void getAuthenticationWhenGlobalAuthenticationConfigurerAdapterThenAuthenticates() throws Exception {
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("user", "password");
UsernamePasswordAuthenticationToken token = UsernamePasswordAuthenticationToken.unauthenticated("user",
"password");
this.spring.register(AuthenticationConfiguration.class, ObjectPostProcessorConfiguration.class,
UserGlobalAuthenticationConfigurerAdapter.class).autowire();
AuthenticationManager authentication = this.spring.getContext().getBean(AuthenticationConfiguration.class)
@ -139,7 +140,8 @@ public class AuthenticationConfigurationTests {
@Test
public void getAuthenticationWhenAuthenticationManagerBeanThenAuthenticates() throws Exception {
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("user", "password");
UsernamePasswordAuthenticationToken token = UsernamePasswordAuthenticationToken.unauthenticated("user",
"password");
this.spring.register(AuthenticationConfiguration.class, ObjectPostProcessorConfiguration.class,
AuthenticationManagerBeanConfig.class).autowire();
AuthenticationManager authentication = this.spring.getContext().getBean(AuthenticationConfiguration.class)
@ -165,9 +167,9 @@ public class AuthenticationConfigurationTests {
config.setGlobalAuthenticationConfigurers(Arrays.asList(new ConfiguresInMemoryConfigurerAdapter(),
new BootGlobalAuthenticationConfigurerAdapter()));
AuthenticationManager authenticationManager = config.getAuthenticationManager();
authenticationManager.authenticate(new UsernamePasswordAuthenticationToken("user", "password"));
assertThatExceptionOfType(AuthenticationException.class).isThrownBy(
() -> authenticationManager.authenticate(new UsernamePasswordAuthenticationToken("boot", "password")));
authenticationManager.authenticate(UsernamePasswordAuthenticationToken.unauthenticated("user", "password"));
assertThatExceptionOfType(AuthenticationException.class).isThrownBy(() -> authenticationManager
.authenticate(UsernamePasswordAuthenticationToken.unauthenticated("boot", "password")));
}
@Test
@ -176,7 +178,7 @@ public class AuthenticationConfigurationTests {
AuthenticationConfiguration config = this.spring.getContext().getBean(AuthenticationConfiguration.class);
config.setGlobalAuthenticationConfigurers(Arrays.asList(new BootGlobalAuthenticationConfigurerAdapter()));
AuthenticationManager authenticationManager = config.getAuthenticationManager();
authenticationManager.authenticate(new UsernamePasswordAuthenticationToken("boot", "password"));
authenticationManager.authenticate(UsernamePasswordAuthenticationToken.unauthenticated("boot", "password"));
}
// gh-2531
@ -206,9 +208,9 @@ public class AuthenticationConfigurationTests {
AuthenticationManager am = this.spring.getContext().getBean(AuthenticationConfiguration.class)
.getAuthenticationManager();
given(uds.loadUserByUsername("user")).willReturn(PasswordEncodedUser.user(), PasswordEncodedUser.user());
am.authenticate(new UsernamePasswordAuthenticationToken("user", "password"));
assertThatExceptionOfType(AuthenticationException.class)
.isThrownBy(() -> am.authenticate(new UsernamePasswordAuthenticationToken("user", "invalid")));
am.authenticate(UsernamePasswordAuthenticationToken.unauthenticated("user", "password"));
assertThatExceptionOfType(AuthenticationException.class).isThrownBy(
() -> am.authenticate(UsernamePasswordAuthenticationToken.unauthenticated("user", "invalid")));
}
@Test
@ -221,9 +223,9 @@ public class AuthenticationConfigurationTests {
.getAuthenticationManager();
given(uds.loadUserByUsername("user")).willReturn(User.withUserDetails(user).build(),
User.withUserDetails(user).build());
am.authenticate(new UsernamePasswordAuthenticationToken("user", "password"));
assertThatExceptionOfType(AuthenticationException.class)
.isThrownBy(() -> am.authenticate(new UsernamePasswordAuthenticationToken("user", "invalid")));
am.authenticate(UsernamePasswordAuthenticationToken.unauthenticated("user", "password"));
assertThatExceptionOfType(AuthenticationException.class).isThrownBy(
() -> am.authenticate(UsernamePasswordAuthenticationToken.unauthenticated("user", "invalid")));
}
@Test
@ -237,7 +239,7 @@ public class AuthenticationConfigurationTests {
given(manager.loadUserByUsername("user")).willReturn(User.withUserDetails(user).build(),
User.withUserDetails(user).build());
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}"));
}
@ -250,7 +252,7 @@ public class AuthenticationConfigurationTests {
.getAuthenticationManager();
given(ap.supports(any())).willReturn(true);
given(ap.authenticate(any())).willReturn(TestAuthentication.authenticatedUser());
am.authenticate(new UsernamePasswordAuthenticationToken("user", "password"));
am.authenticate(UsernamePasswordAuthenticationToken.unauthenticated("user", "password"));
}
// gh-3091
@ -262,7 +264,7 @@ public class AuthenticationConfigurationTests {
.getAuthenticationManager();
given(ap.supports(any())).willReturn(true);
given(ap.authenticate(any())).willReturn(TestAuthentication.authenticatedUser());
am.authenticate(new UsernamePasswordAuthenticationToken("user", "password"));
am.authenticate(UsernamePasswordAuthenticationToken.unauthenticated("user", "password"));
}
@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");
* you may not use this file except in compliance with the License.
@ -75,21 +75,21 @@ public class Issue50Tests {
@Test
public void authenticateWhenMissingUserThenUsernameNotFoundException() {
assertThatExceptionOfType(UsernameNotFoundException.class).isThrownBy(() -> this.authenticationManager
.authenticate(new UsernamePasswordAuthenticationToken("test", "password")));
.authenticate(UsernamePasswordAuthenticationToken.unauthenticated("test", "password")));
}
@Test
public void authenticateWhenInvalidPasswordThenBadCredentialsException() {
this.userRepo.save(User.withUsernameAndPassword("test", "password"));
assertThatExceptionOfType(BadCredentialsException.class).isThrownBy(() -> this.authenticationManager
.authenticate(new UsernamePasswordAuthenticationToken("test", "invalid")));
.authenticate(UsernamePasswordAuthenticationToken.unauthenticated("test", "invalid")));
}
@Test
public void authenticateWhenValidUserThenAuthenticates() {
this.userRepo.save(User.withUsernameAndPassword("test", "password"));
Authentication result = this.authenticationManager
.authenticate(new UsernamePasswordAuthenticationToken("test", "password"));
.authenticate(UsernamePasswordAuthenticationToken.unauthenticated("test", "password"));
assertThat(result.getName()).isEqualTo("test");
}
@ -98,7 +98,7 @@ public class Issue50Tests {
SecurityContextHolder.getContext().setAuthentication(new TestingAuthenticationToken("test", null, "ROLE_USER"));
this.userRepo.save(User.withUsernameAndPassword("denied", "password"));
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");
* you may not use this file except in compliance with the License.
@ -106,8 +106,8 @@ public class GlobalMethodSecurityConfigurationTests {
@Test
public void methodSecurityAuthenticationManagerPublishesEvent() {
this.spring.register(InMemoryAuthWithGlobalMethodSecurityConfig.class).autowire();
assertThatExceptionOfType(AuthenticationException.class).isThrownBy(
() -> this.authenticationManager.authenticate(new UsernamePasswordAuthenticationToken("foo", "bar")));
assertThatExceptionOfType(AuthenticationException.class).isThrownBy(() -> this.authenticationManager
.authenticate(UsernamePasswordAuthenticationToken.unauthenticated("foo", "bar")));
assertThat(this.events.getEvents()).extracting(Object::getClass)
.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");
* 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"));
SecurityContext context = SecurityContextHolder.createEmptyContext();
context.setAuthentication(
new UsernamePasswordAuthenticationToken(user, user.getPassword(), user.getAuthorities()));
UsernamePasswordAuthenticationToken.authenticated(user, user.getPassword(), user.getAuthorities()));
SecurityContextHolder.setContext(context);
MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build();
// @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");
* 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();
AuthenticationManager authenticationManager = this.spring.getContext().getBean(AuthenticationManager.class);
Authentication authentication = authenticationManager
.authenticate(new UsernamePasswordAuthenticationToken("user", "password"));
.authenticate(UsernamePasswordAuthenticationToken.unauthenticated("user", "password"));
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");
* you may not use this file except in compliance with the License.
@ -1013,7 +1013,7 @@ public class WebSecurityConfigurationTests {
return new ProviderManager(new AuthenticationProvider() {
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
return new UsernamePasswordAuthenticationToken("user", "credentials");
return UsernamePasswordAuthenticationToken.unauthenticated("user", "credentials");
}
@Override
@ -1028,7 +1028,7 @@ public class WebSecurityConfigurationTests {
return new ProviderManager(new AuthenticationProvider() {
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
return new UsernamePasswordAuthenticationToken("subuser", "credentials");
return UsernamePasswordAuthenticationToken.unauthenticated("subuser", "credentials");
}
@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");
* you may not use this file except in compliance with the License.
@ -150,7 +150,7 @@ public class AuthorizeRequestsTests {
public void roleHiearchy() throws Exception {
loadConfig(RoleHiearchyConfig.class);
SecurityContext securityContext = new SecurityContextImpl();
securityContext.setAuthentication(new UsernamePasswordAuthenticationToken("test", "notused",
securityContext.setAuthentication(UsernamePasswordAuthenticationToken.authenticated("test", "notused",
AuthorityUtils.createAuthorityList("ROLE_USER")));
this.request.getSession().setAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY,
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");
* 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) {
return new UsernamePasswordAuthenticationToken("user", null, AuthorityUtils.createAuthorityList(role));
return UsernamePasswordAuthenticationToken.authenticated("user", null,
AuthorityUtils.createAuthorityList(role));
}
@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");
* you may not use this file except in compliance with the License.
@ -97,7 +97,7 @@ public class NamespaceHttpServerAccessDeniedHandlerTests {
}
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) {

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");
* you may not use this file except in compliance with the License.
@ -72,7 +72,7 @@ public class AuthenticationConfigurationGh3935Tests {
AuthenticationManager authenticationManager = this.adapter.authenticationManager;
assertThat(authenticationManager).isNotNull();
Authentication auth = authenticationManager
.authenticate(new UsernamePasswordAuthenticationToken(username, password));
.authenticate(UsernamePasswordAuthenticationToken.unauthenticated(username, password));
verify(this.uds).loadUserByUsername(username);
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");
* 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");
assertThat(eventPublisher).isNotNull();
assertThat(eventPublisher instanceof DefaultAuthenticationEventPublisher).isTrue();
pm.authenticate(new UsernamePasswordAuthenticationToken("bob", "bobspassword"));
pm.authenticate(UsernamePasswordAuthenticationToken.unauthenticated("bob", "bobspassword"));
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");
* you may not use this file except in compliance with the License.
@ -42,7 +42,8 @@ public class AuthenticationProviderBeanDefinitionParserTests {
private AbstractXmlApplicationContext appContext;
private UsernamePasswordAuthenticationToken bob = new UsernamePasswordAuthenticationToken("bob", "bobspassword");
private UsernamePasswordAuthenticationToken bob = UsernamePasswordAuthenticationToken.unauthenticated("bob",
"bobspassword");
@AfterEach
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");
* you may not use this file except in compliance with the License.
@ -129,7 +129,7 @@ public class JdbcUserServiceBeanDefinitionParserTests {
+ DATA_SOURCE);
// @formatter:on
AuthenticationManager mgr = (AuthenticationManager) this.appContext.getBean(BeanIds.AUTHENTICATION_MANAGER);
mgr.authenticate(new UsernamePasswordAuthenticationToken("rod", "koala"));
mgr.authenticate(UsernamePasswordAuthenticationToken.unauthenticated("rod", "koala"));
}
@Test
@ -146,7 +146,7 @@ public class JdbcUserServiceBeanDefinitionParserTests {
ProviderManager mgr = (ProviderManager) this.appContext.getBean(BeanIds.AUTHENTICATION_MANAGER);
DaoAuthenticationProvider provider = (DaoAuthenticationProvider) mgr.getProviders().get(0);
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()
.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");
* 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 {
private final UsernamePasswordAuthenticationToken bob = new UsernamePasswordAuthenticationToken("bob",
private final UsernamePasswordAuthenticationToken bob = UsernamePasswordAuthenticationToken.unauthenticated("bob",
"bobspassword");
private AbstractXmlApplicationContext appContext;
@ -106,7 +106,8 @@ public class GlobalMethodSecurityBeanDefinitionParserTests {
@Test
public void targetShouldAllowProtectedMethodInvocationWithCorrectRole() {
loadContext();
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("user", "password");
UsernamePasswordAuthenticationToken token = UsernamePasswordAuthenticationToken.unauthenticated("user",
"password");
SecurityContextHolder.getContext().setAuthentication(token);
this.target.someUserMethod1();
// SEC-1213. Check the order
@ -153,8 +154,8 @@ public class GlobalMethodSecurityBeanDefinitionParserTests {
+ "</authentication-manager>");
// @formatter:on
UserDetailsService service = (UserDetailsService) this.appContext.getBean("myUserService");
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("Test", "Password",
AuthorityUtils.createAuthorityList("ROLE_SOMEOTHERROLE"));
UsernamePasswordAuthenticationToken token = UsernamePasswordAuthenticationToken.authenticated("Test",
"Password", AuthorityUtils.createAuthorityList("ROLE_SOMEOTHERROLE"));
SecurityContextHolder.getContext().setAuthentication(token);
assertThatExceptionOfType(AccessDeniedException.class).isThrownBy(() -> service.loadUserByUsername("notused"));
}
@ -170,7 +171,7 @@ public class GlobalMethodSecurityBeanDefinitionParserTests {
+ ConfigTestUtils.AUTH_PROVIDER_XML);
// @formatter:on
SecurityContextHolder.getContext()
.setAuthentication(new UsernamePasswordAuthenticationToken("user", "password"));
.setAuthentication(UsernamePasswordAuthenticationToken.unauthenticated("user", "password"));
this.target = (BusinessService) this.appContext.getBean("target");
// someOther(int) should not be matched by someOther(String), but should require
// ROLE_USER
@ -198,7 +199,7 @@ public class GlobalMethodSecurityBeanDefinitionParserTests {
assertThatExceptionOfType(AuthenticationCredentialsNotFoundException.class)
.isThrownBy(() -> this.target.someOther(0));
SecurityContextHolder.getContext()
.setAuthentication(new UsernamePasswordAuthenticationToken("user", "password"));
.setAuthentication(UsernamePasswordAuthenticationToken.unauthenticated("user", "password"));
this.target.someOther(0);
}
@ -366,7 +367,7 @@ public class GlobalMethodSecurityBeanDefinitionParserTests {
Foo foo = (Foo) this.appContext.getBean("target");
assertThatExceptionOfType(AccessDeniedException.class).isThrownBy(() -> foo.foo(new SecurityConfig("A")));
SecurityContextHolder.getContext()
.setAuthentication(new UsernamePasswordAuthenticationToken("admin", "password"));
.setAuthentication(UsernamePasswordAuthenticationToken.unauthenticated("admin", "password"));
foo.foo(new SecurityConfig("A"));
}
@ -387,7 +388,7 @@ public class GlobalMethodSecurityBeanDefinitionParserTests {
Foo foo = (Foo) this.appContext.getBean("target");
assertThatExceptionOfType(AccessDeniedException.class).isThrownBy(() -> foo.foo(new SecurityConfig("A")));
SecurityContextHolder.getContext()
.setAuthentication(new UsernamePasswordAuthenticationToken("admin", "password"));
.setAuthentication(UsernamePasswordAuthenticationToken.unauthenticated("admin", "password"));
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");
* you may not use this file except in compliance with the License.
@ -91,16 +91,16 @@ public class InterceptMethodsBeanDefinitionDecoratorTests implements Application
@Test
public void targetShouldAllowProtectedMethodInvocationWithCorrectRole() {
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("Test", "Password",
AuthorityUtils.createAuthorityList("ROLE_USER"));
UsernamePasswordAuthenticationToken token = UsernamePasswordAuthenticationToken.authenticated("Test",
"Password", AuthorityUtils.createAuthorityList("ROLE_USER"));
SecurityContextHolder.getContext().setAuthentication(token);
this.target.doSomething();
}
@Test
public void targetShouldPreventProtectedMethodInvocationWithIncorrectRole() {
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("Test", "Password",
AuthorityUtils.createAuthorityList("ROLE_SOMEOTHERROLE"));
UsernamePasswordAuthenticationToken token = UsernamePasswordAuthenticationToken.authenticated("Test",
"Password", AuthorityUtils.createAuthorityList("ROLE_SOMEOTHERROLE"));
SecurityContextHolder.getContext().setAuthentication(token);
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");
* you may not use this file except in compliance with the License.
@ -67,32 +67,32 @@ public class Jsr250AnnotationDrivenBeanDefinitionParserTests {
@Test
public void permitAllShouldBeDefaultAttribute() {
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("Test", "Password",
AuthorityUtils.createAuthorityList("ROLE_USER"));
UsernamePasswordAuthenticationToken token = UsernamePasswordAuthenticationToken.authenticated("Test",
"Password", AuthorityUtils.createAuthorityList("ROLE_USER"));
SecurityContextHolder.getContext().setAuthentication(token);
this.target.someOther(0);
}
@Test
public void targetShouldAllowProtectedMethodInvocationWithCorrectRole() {
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("Test", "Password",
AuthorityUtils.createAuthorityList("ROLE_USER"));
UsernamePasswordAuthenticationToken token = UsernamePasswordAuthenticationToken.authenticated("Test",
"Password", AuthorityUtils.createAuthorityList("ROLE_USER"));
SecurityContextHolder.getContext().setAuthentication(token);
this.target.someUserMethod1();
}
@Test
public void targetShouldPreventProtectedMethodInvocationWithIncorrectRole() {
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("Test", "Password",
AuthorityUtils.createAuthorityList("ROLE_SOMEOTHERROLE"));
UsernamePasswordAuthenticationToken token = UsernamePasswordAuthenticationToken.authenticated("Test",
"Password", AuthorityUtils.createAuthorityList("ROLE_SOMEOTHERROLE"));
SecurityContextHolder.getContext().setAuthentication(token);
assertThatExceptionOfType(AccessDeniedException.class).isThrownBy(this.target::someAdminMethod);
}
@Test
public void hasAnyRoleAddsDefaultPrefix() {
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("Test", "Password",
AuthorityUtils.createAuthorityList("ROLE_USER"));
UsernamePasswordAuthenticationToken token = UsernamePasswordAuthenticationToken.authenticated("Test",
"Password", AuthorityUtils.createAuthorityList("ROLE_USER"));
SecurityContextHolder.getContext().setAuthentication(token);
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");
* 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 final UsernamePasswordAuthenticationToken bob = new UsernamePasswordAuthenticationToken("bob",
private final UsernamePasswordAuthenticationToken bob = UsernamePasswordAuthenticationToken.unauthenticated("bob",
"bobspassword");
@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");
* you may not use this file except in compliance with the License.
@ -73,16 +73,16 @@ public class SecuredAnnotationDrivenBeanDefinitionParserTests {
@Test
public void targetShouldAllowProtectedMethodInvocationWithCorrectRole() {
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("Test", "Password",
AuthorityUtils.createAuthorityList("ROLE_USER"));
UsernamePasswordAuthenticationToken token = UsernamePasswordAuthenticationToken.authenticated("Test",
"Password", AuthorityUtils.createAuthorityList("ROLE_USER"));
SecurityContextHolder.getContext().setAuthentication(token);
this.target.someUserMethod1();
}
@Test
public void targetShouldPreventProtectedMethodInvocationWithIncorrectRole() {
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("Test", "Password",
AuthorityUtils.createAuthorityList("ROLE_SOMEOTHER"));
UsernamePasswordAuthenticationToken token = UsernamePasswordAuthenticationToken.authenticated("Test",
"Password", AuthorityUtils.createAuthorityList("ROLE_SOMEOTHER"));
SecurityContextHolder.getContext().setAuthentication(token);
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");
* 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) {
return new UsernamePasswordAuthenticationToken(userDetails, userDetails.getPassword(),
return UsernamePasswordAuthenticationToken.authenticated(userDetails, userDetails.getPassword(),
userDetails.getAuthorities());
}

View File

@ -32,6 +32,7 @@ import org.springframework.util.Assert;
* <code>String</code>.
*
* @author Ben Alex
* @author Norbert Nowak
*/
public class UsernamePasswordAuthenticationToken extends AbstractAuthenticationToken {
@ -71,6 +72,33 @@ public class UsernamePasswordAuthenticationToken extends AbstractAuthenticationT
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
public Object getCredentials() {
return this.credentials;

View File

@ -193,7 +193,7 @@ public abstract class AbstractUserDetailsAuthenticationProvider
// so subsequent attempts are successful even with encoded passwords.
// Also ensure we return the original getDetails(), so that future
// 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()));
result.setDetails(authentication.getDetails());
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");
* 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),
GRANTED_AUTHORITY_LIST);
UsernamePasswordAuthenticationToken token = (!authenticated)
? new UsernamePasswordAuthenticationToken(principal, credentials)
: new UsernamePasswordAuthenticationToken(principal, credentials, authorities);
? UsernamePasswordAuthenticationToken.unauthenticated(principal, credentials)
: UsernamePasswordAuthenticationToken.authenticated(principal, credentials, authorities);
JsonNode detailsNode = readJsonNode(jsonNode, "details");
if (detailsNode.isNull() || detailsNode.isMissingNode()) {
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");
* you may not use this file except in compliance with the License.
@ -125,7 +125,8 @@ public class InMemoryUserDetailsManager implements UserDetailsManager, UserDetai
// supplied password.
if (this.authenticationManager != null) {
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 {
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");
* 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.
if (this.authenticationManager != null) {
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 {
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) {
UserDetails user = loadUserByUsername(currentAuth.getName());
UsernamePasswordAuthenticationToken newAuthentication = new UsernamePasswordAuthenticationToken(user, null,
user.getAuthorities());
UsernamePasswordAuthenticationToken newAuthentication = UsernamePasswordAuthenticationToken.authenticated(user,
null, user.getAuthorities());
newAuthentication.setDetails(currentAuth.getDetails());
return newAuthentication;
}

View File

@ -34,7 +34,8 @@ import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException
*/
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");

View File

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

View File

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

View File

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

View File

@ -66,12 +66,13 @@ public class ProviderManagerTests {
@Test
public void credentialsAreClearedByDefault() {
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("Test", "Password");
UsernamePasswordAuthenticationToken token = UsernamePasswordAuthenticationToken.unauthenticated("Test",
"Password");
ProviderManager mgr = makeProviderManager();
Authentication result = mgr.authenticate(token);
assertThat(result.getCredentials()).isNull();
mgr.setEraseCredentialsAfterAuthentication(false);
token = new UsernamePasswordAuthenticationToken("Test", "Password");
token = UsernamePasswordAuthenticationToken.unauthenticated("Test", "Password");
result = mgr.authenticate(token);
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");
* you may not use this file except in compliance with the License.
@ -72,7 +72,7 @@ public class ReactiveUserDetailsServiceAuthenticationManagerTests {
@Test
public void authenticateWhenUserNotFoundThenBadCredentials() {
given(this.repository.findByUsername(this.username)).willReturn(Mono.empty());
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(this.username,
UsernamePasswordAuthenticationToken token = UsernamePasswordAuthenticationToken.unauthenticated(this.username,
this.password);
Mono<Authentication> authentication = this.manager.authenticate(token);
// @formatter:off
@ -91,7 +91,7 @@ public class ReactiveUserDetailsServiceAuthenticationManagerTests {
.build();
// @formatter:on
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");
Mono<Authentication> authentication = this.manager.authenticate(token);
// @formatter:off
@ -110,7 +110,7 @@ public class ReactiveUserDetailsServiceAuthenticationManagerTests {
.build();
// @formatter:on
given(this.repository.findByUsername(user.getUsername())).willReturn(Mono.just(user));
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(this.username,
UsernamePasswordAuthenticationToken token = UsernamePasswordAuthenticationToken.unauthenticated(this.username,
this.password);
Authentication authentication = this.manager.authenticate(token).block();
assertThat(authentication).isEqualTo(authentication);
@ -122,7 +122,7 @@ public class ReactiveUserDetailsServiceAuthenticationManagerTests {
given(this.passwordEncoder.matches(any(), any())).willReturn(true);
User user = new User(this.username, this.password, AuthorityUtils.createAuthorityList("ROLE_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);
Authentication authentication = this.manager.authenticate(token).block();
assertThat(authentication).isEqualTo(authentication);
@ -134,7 +134,7 @@ public class ReactiveUserDetailsServiceAuthenticationManagerTests {
given(this.passwordEncoder.matches(any(), any())).willReturn(false);
User user = new User(this.username, this.password, AuthorityUtils.createAuthorityList("ROLE_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);
Mono<Authentication> authentication = this.manager.authenticate(token);
// @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");
* 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) {
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");
* 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);
this.manager.setScheduler(this.scheduler);
this.manager.setPasswordEncoder(this.encoder);
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(this.user,
UsernamePasswordAuthenticationToken token = UsernamePasswordAuthenticationToken.unauthenticated(this.user,
this.user.getPassword());
Authentication result = this.manager.authenticate(token).block();
verify(this.scheduler).schedule(any());
@ -111,7 +111,7 @@ public class UserDetailsRepositoryReactiveAuthenticationManagerTests {
given(this.userDetailsPasswordService.updatePassword(any(), any())).willReturn(Mono.just(this.user));
this.manager.setPasswordEncoder(this.encoder);
this.manager.setUserDetailsPasswordService(this.userDetailsPasswordService);
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(this.user,
UsernamePasswordAuthenticationToken token = UsernamePasswordAuthenticationToken.unauthenticated(this.user,
this.user.getPassword());
Authentication result = this.manager.authenticate(token).block();
verify(this.encoder).encode(this.user.getPassword());
@ -124,7 +124,7 @@ public class UserDetailsRepositoryReactiveAuthenticationManagerTests {
given(this.encoder.matches(any(), any())).willReturn(false);
this.manager.setPasswordEncoder(this.encoder);
this.manager.setUserDetailsPasswordService(this.userDetailsPasswordService);
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(this.user,
UsernamePasswordAuthenticationToken token = UsernamePasswordAuthenticationToken.unauthenticated(this.user,
this.user.getPassword());
assertThatExceptionOfType(BadCredentialsException.class)
.isThrownBy(() -> this.manager.authenticate(token).block());
@ -138,7 +138,7 @@ public class UserDetailsRepositoryReactiveAuthenticationManagerTests {
given(this.encoder.upgradeEncoding(any())).willReturn(false);
this.manager.setPasswordEncoder(this.encoder);
this.manager.setUserDetailsPasswordService(this.userDetailsPasswordService);
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(this.user,
UsernamePasswordAuthenticationToken token = UsernamePasswordAuthenticationToken.unauthenticated(this.user,
this.user.getPassword());
Authentication result = this.manager.authenticate(token).block();
verifyZeroInteractions(this.userDetailsPasswordService);
@ -152,8 +152,8 @@ public class UserDetailsRepositoryReactiveAuthenticationManagerTests {
this.manager.setPasswordEncoder(this.encoder);
this.manager.setPostAuthenticationChecks(this.postAuthenticationChecks);
assertThatExceptionOfType(LockedException.class).isThrownBy(() -> this.manager
.authenticate(new UsernamePasswordAuthenticationToken(this.user, this.user.getPassword())).block())
.withMessage("account is locked");
.authenticate(UsernamePasswordAuthenticationToken.unauthenticated(this.user, this.user.getPassword()))
.block()).withMessage("account is locked");
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.encoder.matches(any(), any())).willReturn(true);
this.manager.setPasswordEncoder(this.encoder);
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(this.user,
UsernamePasswordAuthenticationToken token = UsernamePasswordAuthenticationToken.unauthenticated(this.user,
this.user.getPassword());
this.manager.authenticate(token).block();
verifyZeroInteractions(this.postAuthenticationChecks);
@ -179,7 +179,7 @@ public class UserDetailsRepositoryReactiveAuthenticationManagerTests {
.build();
// @formatter:on
given(this.userDetailsService.findByUsername(any())).willReturn(Mono.just(expiredUser));
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(expiredUser,
UsernamePasswordAuthenticationToken token = UsernamePasswordAuthenticationToken.unauthenticated(expiredUser,
expiredUser.getPassword());
assertThatExceptionOfType(AccountExpiredException.class)
.isThrownBy(() -> this.manager.authenticate(token).block());
@ -196,7 +196,7 @@ public class UserDetailsRepositoryReactiveAuthenticationManagerTests {
.build();
// @formatter:on
given(this.userDetailsService.findByUsername(any())).willReturn(Mono.just(lockedUser));
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(lockedUser,
UsernamePasswordAuthenticationToken token = UsernamePasswordAuthenticationToken.unauthenticated(lockedUser,
lockedUser.getPassword());
assertThatExceptionOfType(LockedException.class).isThrownBy(() -> this.manager.authenticate(token).block());
}
@ -212,7 +212,7 @@ public class UserDetailsRepositoryReactiveAuthenticationManagerTests {
.build();
// @formatter:on
given(this.userDetailsService.findByUsername(any())).willReturn(Mono.just(disabledUser));
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(disabledUser,
UsernamePasswordAuthenticationToken token = UsernamePasswordAuthenticationToken.unauthenticated(disabledUser,
disabledUser.getPassword());
assertThatExceptionOfType(DisabledException.class).isThrownBy(() -> this.manager.authenticate(token).block());
}

View File

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

View File

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

View File

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

View File

@ -30,8 +30,8 @@ import org.springframework.security.core.Authentication;
public class LoggerListenerTests {
private Authentication getAuthentication() {
UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken("Principal",
"Credentials");
UsernamePasswordAuthenticationToken authentication = UsernamePasswordAuthenticationToken
.unauthenticated("Principal", "Credentials");
authentication.setDetails("127.0.0.1");
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");
* 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,
Collections.<String, Object>emptyMap()) };
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);
}
@ -113,15 +113,15 @@ public class DefaultJaasAuthenticationProviderTests {
@Test
public void authenticateBadPassword() {
assertThatExceptionOfType(AuthenticationException.class)
.isThrownBy(() -> this.provider.authenticate(new UsernamePasswordAuthenticationToken("user", "asdf")));
assertThatExceptionOfType(AuthenticationException.class).isThrownBy(
() -> this.provider.authenticate(UsernamePasswordAuthenticationToken.unauthenticated("user", "asdf")));
verifyFailedLogin();
}
@Test
public void authenticateBadUser() {
assertThatExceptionOfType(AuthenticationException.class).isThrownBy(
() -> this.provider.authenticate(new UsernamePasswordAuthenticationToken("asdf", "password")));
assertThatExceptionOfType(AuthenticationException.class).isThrownBy(() -> this.provider
.authenticate(UsernamePasswordAuthenticationToken.unauthenticated("asdf", "password")));
verifyFailedLogin();
}

View File

@ -75,8 +75,8 @@ public class JaasAuthenticationProviderTests {
@Test
public void testBadPassword() {
assertThatExceptionOfType(AuthenticationException.class).isThrownBy(
() -> this.jaasProvider.authenticate(new UsernamePasswordAuthenticationToken("user", "asdf")));
assertThatExceptionOfType(AuthenticationException.class).isThrownBy(() -> this.jaasProvider
.authenticate(UsernamePasswordAuthenticationToken.unauthenticated("user", "asdf")));
assertThat(this.eventCheck.failedEvent).as("Failure event not fired").isNotNull();
assertThat(this.eventCheck.failedEvent.getException()).withFailMessage("Failure event exception was null")
.isNotNull();
@ -85,8 +85,8 @@ public class JaasAuthenticationProviderTests {
@Test
public void testBadUser() {
assertThatExceptionOfType(AuthenticationException.class).isThrownBy(
() -> this.jaasProvider.authenticate(new UsernamePasswordAuthenticationToken("asdf", "password")));
assertThatExceptionOfType(AuthenticationException.class).isThrownBy(() -> this.jaasProvider
.authenticate(UsernamePasswordAuthenticationToken.unauthenticated("asdf", "password")));
assertThat(this.eventCheck.failedEvent).as("Failure event not fired").isNotNull();
assertThat(this.eventCheck.failedEvent.getException()).withFailMessage("Failure event exception was null")
.isNotNull();
@ -158,8 +158,8 @@ public class JaasAuthenticationProviderTests {
@Test
public void testFull() {
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("user", "password",
AuthorityUtils.createAuthorityList("ROLE_ONE"));
UsernamePasswordAuthenticationToken token = UsernamePasswordAuthenticationToken.authenticated("user",
"password", AuthorityUtils.createAuthorityList("ROLE_ONE"));
assertThat(this.jaasProvider.supports(UsernamePasswordAuthenticationToken.class)).isTrue();
Authentication auth = this.jaasProvider.authenticate(token);
assertThat(this.jaasProvider.getAuthorityGranters()).isNotNull();
@ -198,7 +198,7 @@ public class JaasAuthenticationProviderTests {
assertThat(this.jaasProvider.getLoginExceptionResolver()).isNotNull();
this.jaasProvider.setLoginExceptionResolver((e) -> new LockedException("This is just a test!"));
try {
this.jaasProvider.authenticate(new UsernamePasswordAuthenticationToken("user", "password"));
this.jaasProvider.authenticate(UsernamePasswordAuthenticationToken.unauthenticated("user", "password"));
}
catch (LockedException ex) {
}
@ -221,7 +221,8 @@ public class JaasAuthenticationProviderTests {
@Test
public void testNullDefaultAuthorities() {
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("user", "password");
UsernamePasswordAuthenticationToken token = UsernamePasswordAuthenticationToken.unauthenticated("user",
"password");
assertThat(this.jaasProvider.supports(UsernamePasswordAuthenticationToken.class)).isTrue();
Authentication auth = this.jaasProvider.authenticate(token);
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");
* you may not use this file except in compliance with the License.
@ -56,8 +56,8 @@ public class Sec760Tests {
}
private void testAuthenticate(JaasAuthenticationProvider p1) {
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("user", "password",
AuthorityUtils.createAuthorityList("ROLE_ONE", "ROLE_TWO"));
UsernamePasswordAuthenticationToken token = UsernamePasswordAuthenticationToken.authenticated("user",
"password", AuthorityUtils.createAuthorityList("ROLE_ONE", "ROLE_TWO"));
Authentication auth = p1.authenticate(token);
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 UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken("principal",
private UsernamePasswordAuthenticationToken auth = UsernamePasswordAuthenticationToken.unauthenticated("principal",
"credentials");
@BeforeEach

View File

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

View File

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

View File

@ -40,7 +40,7 @@ public class SecurityContextImplTests {
@Test
public void testSecurityContextCorrectOperation() {
SecurityContext context = new SecurityContextImpl();
Authentication auth = new UsernamePasswordAuthenticationToken("rod", "koala");
Authentication auth = UsernamePasswordAuthenticationToken.unauthenticated("rod", "koala");
context.setAuthentication(auth);
assertThat(context.getAuthentication()).isEqualTo(auth);
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");
* you may not use this file except in compliance with the License.
@ -47,7 +47,7 @@ public class SecurityContextMixinTests extends AbstractMixinTests {
@Test
public void securityContextSerializeTest() throws JsonProcessingException, JSONException {
SecurityContext context = new SecurityContextImpl();
context.setAuthentication(new UsernamePasswordAuthenticationToken("admin", "1234",
context.setAuthentication(UsernamePasswordAuthenticationToken.authenticated("admin", "1234",
Collections.singleton(new SimpleGrantedAuthority("ROLE_USER"))));
String actualJson = this.mapper.writeValueAsString(context);
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");
* you may not use this file except in compliance with the License.
@ -71,7 +71,8 @@ public class UsernamePasswordAuthenticationTokenMixinTests extends AbstractMixin
@Test
public void serializeUnauthenticatedUsernamePasswordAuthenticationTokenMixinTest()
throws JsonProcessingException, JSONException {
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("admin", "1234");
UsernamePasswordAuthenticationToken token = UsernamePasswordAuthenticationToken.unauthenticated("admin",
"1234");
String serializedJson = this.mapper.writeValueAsString(token);
JSONAssert.assertEquals(UNAUTHENTICATED_STRINGPRINCIPAL_JSON, serializedJson, true);
}
@ -80,8 +81,8 @@ public class UsernamePasswordAuthenticationTokenMixinTests extends AbstractMixin
public void serializeAuthenticatedUsernamePasswordAuthenticationTokenMixinTest()
throws JsonProcessingException, JSONException {
User user = createDefaultUser();
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(user.getUsername(),
user.getPassword(), user.getAuthorities());
UsernamePasswordAuthenticationToken token = UsernamePasswordAuthenticationToken
.authenticated(user.getUsername(), user.getPassword(), user.getAuthorities());
String serializedJson = this.mapper.writeValueAsString(token);
JSONAssert.assertEquals(AUTHENTICATED_STRINGPRINCIPAL_JSON, serializedJson, true);
}
@ -140,7 +141,7 @@ public class UsernamePasswordAuthenticationTokenMixinTests extends AbstractMixin
throws JsonProcessingException, JSONException {
NonUserPrincipal principal = new NonUserPrincipal();
principal.setUsername("admin");
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(principal, null,
UsernamePasswordAuthenticationToken token = UsernamePasswordAuthenticationToken.authenticated(principal, null,
new ArrayList<>());
String actualJson = this.mapper.writeValueAsString(token);
JSONAssert.assertEquals(AUTHENTICATED_NON_USER_PRINCIPAL_JSON, actualJson, true);
@ -170,7 +171,8 @@ public class UsernamePasswordAuthenticationTokenMixinTests extends AbstractMixin
@Test
public void serializingThenDeserializingWithNoCredentialsOrDetailsShouldWork() throws IOException {
UsernamePasswordAuthenticationToken original = new UsernamePasswordAuthenticationToken("Frodo", null);
UsernamePasswordAuthenticationToken original = UsernamePasswordAuthenticationToken.unauthenticated("Frodo",
null);
String serialized = this.mapper.writeValueAsString(original);
UsernamePasswordAuthenticationToken deserialized = this.mapper.readValue(serialized,
UsernamePasswordAuthenticationToken.class);
@ -181,7 +183,8 @@ public class UsernamePasswordAuthenticationTokenMixinTests extends AbstractMixin
public void serializingThenDeserializingWithConfiguredObjectMapperShouldWork() throws IOException {
this.mapper.setDefaultPropertyInclusion(Value.construct(Include.ALWAYS, Include.NON_NULL))
.setSerializationInclusion(Include.NON_ABSENT);
UsernamePasswordAuthenticationToken original = new UsernamePasswordAuthenticationToken("Frodo", null);
UsernamePasswordAuthenticationToken original = UsernamePasswordAuthenticationToken.unauthenticated("Frodo",
null);
String serialized = this.mapper.writeValueAsString(original);
UsernamePasswordAuthenticationToken deserialized = this.mapper.readValue(serialized,
UsernamePasswordAuthenticationToken.class);
@ -190,8 +193,8 @@ public class UsernamePasswordAuthenticationTokenMixinTests extends AbstractMixin
private UsernamePasswordAuthenticationToken createToken() {
User user = createDefaultUser();
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(user, user.getPassword(),
user.getAuthorities());
UsernamePasswordAuthenticationToken token = UsernamePasswordAuthenticationToken.authenticated(user,
user.getPassword(), user.getAuthorities());
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");
* you may not use this file except in compliance with the License.
@ -344,14 +344,14 @@ public class JdbcUserDetailsManagerTests {
@Test
public void createNewAuthenticationUsesNullPasswordToKeepPassordsSave() {
insertJoe();
UsernamePasswordAuthenticationToken currentAuth = new UsernamePasswordAuthenticationToken("joe", null,
UsernamePasswordAuthenticationToken currentAuth = UsernamePasswordAuthenticationToken.authenticated("joe", null,
AuthorityUtils.createAuthorityList("ROLE_USER"));
Authentication updatedAuth = this.manager.createNewAuthentication(currentAuth, "new");
assertThat(updatedAuth.getCredentials()).isNull();
}
private Authentication authenticateJoe() {
UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken("joe", "password",
UsernamePasswordAuthenticationToken auth = UsernamePasswordAuthenticationToken.authenticated("joe", "password",
joe.getAuthorities());
SecurityContextHolder.getContext().setAuthentication(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();
Authentication authentication =
new UsernamePasswordAuthenticationToken("user","doesnotmatter", AuthorityUtils.createAuthorityList("ROLE_USER"));
UsernamePasswordAuthenticationToken.authenticated("user","doesnotmatter", AuthorityUtils.createAuthorityList("ROLE_USER"));
context.setAuthentication(authentication);
SimpleAsyncTaskExecutor delegateExecutor =

View File

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

View File

@ -529,7 +529,7 @@ public class WithMockCustomUserSecurityContextFactory
CustomUserDetails principal =
new CustomUserDetails(customUser.name(), customUser.username());
Authentication auth =
new UsernamePasswordAuthenticationToken(principal, "password", principal.getAuthorities());
UsernamePasswordAuthenticationToken.authenticated(principal, "password", principal.getAuthorities());
context.setAuthentication(auth);
return context;
}
@ -575,7 +575,7 @@ final class WithUserDetailsSecurityContextFactory
String username = withUser.value();
Assert.hasLength(username, "value() must be non-empty String");
UserDetails principal = userDetailsService.loadUserByUsername(username);
Authentication authentication = new UsernamePasswordAuthenticationToken(principal, principal.getPassword(), principal.getAuthorities());
Authentication authentication = UsernamePasswordAuthenticationToken.authenticated(principal, principal.getPassword(), principal.getAuthorities());
SecurityContext context = SecurityContextHolder.createEmptyContext();
context.setAuthentication(authentication);
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");
* you may not use this file except in compliance with the License.
@ -35,7 +35,7 @@ public class PythonInterpreterBasedSecurityTests {
@Test
public void serviceMethod() {
SecurityContextHolder.getContext()
.setAuthentication(new UsernamePasswordAuthenticationToken("bob", "bobspassword"));
.setAuthentication(UsernamePasswordAuthenticationToken.unauthenticated("bob", "bobspassword"));
// for (int i=0; i < 1000; i++) {
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");
* 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 final UsernamePasswordAuthenticationToken user = new UsernamePasswordAuthenticationToken("bob",
private final UsernamePasswordAuthenticationToken user = UsernamePasswordAuthenticationToken.authenticated("bob",
"bobspassword", createRoles(N_AUTHORITIES));
private HttpSession session;
@ -129,8 +129,8 @@ public class FilterChainPerformanceTests {
StopWatch sw = new StopWatch("Scaling with nAuthorities");
for (int user = 0; user < N_AUTHORITIES / 10; user++) {
int nAuthorities = (user != 0) ? user * 10 : 1;
SecurityContextHolder.getContext().setAuthentication(
new UsernamePasswordAuthenticationToken("bob", "bobspassword", createRoles(nAuthorities)));
SecurityContextHolder.getContext().setAuthentication(UsernamePasswordAuthenticationToken
.authenticated("bob", "bobspassword", createRoles(nAuthorities)));
this.session.setAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY,
SecurityContextHolder.getContext());
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");
* you may not use this file except in compliance with the License.
@ -117,7 +117,7 @@ public class SecurityContextHolderMTTests extends TestCase{
} else if (expectAllThreadsToUseIdenticalAuthentication) {
// A global
SecurityContextHolder.getContext()
.setAuthentication(new UsernamePasswordAuthenticationToken("GLOBAL_USERNAME",
.setAuthentication(UsernamePasswordAuthenticationToken.unauthenticated("GLOBAL_USERNAME",
"pass"));
for (int i = 0; i < threads.length; i++) {
@ -182,7 +182,7 @@ public class SecurityContextHolderMTTests extends TestCase{
public void run() {
if (injectAuthIntoCurrentThread) {
// Set authentication in this thread
SecurityContextHolder.getContext().setAuthentication(new UsernamePasswordAuthenticationToken(
SecurityContextHolder.getContext().setAuthentication(UsernamePasswordAuthenticationToken.authenticated(
expectedUsername, "pass"));
//System.out.println(threadIdentifier + " - set to " + SecurityContextHolder.getContext().getAuthentication());

View File

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

View File

@ -63,8 +63,8 @@ public class PasswordComparisonAuthenticatorTests {
this.authenticator = new PasswordComparisonAuthenticator(this.contextSource);
this.authenticator.setPasswordEncoder(NoOpPasswordEncoder.getInstance());
this.authenticator.setUserDnPatterns(new String[] { "uid={0},ou=people" });
this.bob = new UsernamePasswordAuthenticationToken("bob", "bobspassword");
this.ben = new UsernamePasswordAuthenticationToken("ben", "benspassword");
this.bob = UsernamePasswordAuthenticationToken.unauthenticated("bob", "bobspassword");
this.ben = UsernamePasswordAuthenticationToken.unauthenticated("ben", "benspassword");
}
@Test
@ -81,16 +81,16 @@ public class PasswordComparisonAuthenticatorTests {
.isEmpty();
this.authenticator.setUserSearch(new MockUserSearch(null));
this.authenticator.afterPropertiesSet();
assertThatExceptionOfType(UsernameNotFoundException.class).isThrownBy(
() -> this.authenticator.authenticate(new UsernamePasswordAuthenticationToken("Joe", "pass")));
assertThatExceptionOfType(UsernameNotFoundException.class).isThrownBy(() -> this.authenticator
.authenticate(UsernamePasswordAuthenticationToken.unauthenticated("Joe", "pass")));
}
@Test
public void testLdapPasswordCompareFailsWithWrongPassword() {
// Don't retrieve the password
this.authenticator.setUserAttributes(new String[] { "uid", "cn", "sn" });
assertThatExceptionOfType(BadCredentialsException.class).isThrownBy(
() -> this.authenticator.authenticate(new UsernamePasswordAuthenticationToken("bob", "wrongpass")));
assertThatExceptionOfType(BadCredentialsException.class).isThrownBy(() -> this.authenticator
.authenticate(UsernamePasswordAuthenticationToken.unauthenticated("bob", "wrongpass")));
}
@Test
@ -131,14 +131,14 @@ public class PasswordComparisonAuthenticatorTests {
@Test
public void testUseOfDifferentPasswordAttributeSucceeds() {
this.authenticator.setPasswordAttributeName("uid");
this.authenticator.authenticate(new UsernamePasswordAuthenticationToken("bob", "bob"));
this.authenticator.authenticate(UsernamePasswordAuthenticationToken.unauthenticated("bob", "bob"));
}
@Test
public void testLdapCompareWithDifferentPasswordAttributeSucceeds() {
this.authenticator.setUserAttributes(new String[] { "uid" });
this.authenticator.setPasswordAttributeName("cn");
this.authenticator.authenticate(new UsernamePasswordAuthenticationToken("ben", "Ben Alex"));
this.authenticator.authenticate(UsernamePasswordAuthenticationToken.unauthenticated("ben", "Ben Alex"));
}
@Test
@ -152,7 +152,8 @@ public class PasswordComparisonAuthenticatorTests {
ctx.setAttributeValue("userPassword", "bobspassword");
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());
SecurityContextHolder.getContext().setAuthentication(
new UsernamePasswordAuthenticationToken("johnyossarian", "yossarianspassword", TEST_AUTHORITIES));
SecurityContextHolder.getContext().setAuthentication(UsernamePasswordAuthenticationToken
.authenticated("johnyossarian", "yossarianspassword", TEST_AUTHORITIES));
this.mgr.changePassword("yossarianspassword", "yossariansnewpassword");
@ -211,8 +211,8 @@ public class LdapUserDetailsManagerTests {
p.setPassword("yossarianspassword");
p.setAuthorities(TEST_AUTHORITIES);
this.mgr.createUser(p.createUserDetails());
SecurityContextHolder.getContext().setAuthentication(
new UsernamePasswordAuthenticationToken("johnyossarian", "yossarianspassword", TEST_AUTHORITIES));
SecurityContextHolder.getContext().setAuthentication(UsernamePasswordAuthenticationToken
.authenticated("johnyossarian", "yossarianspassword", TEST_AUTHORITIES));
assertThatExceptionOfType(BadCredentialsException.class)
.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");
* you may not use this file except in compliance with the License.
@ -99,7 +99,7 @@ public abstract class AbstractLdapAuthenticationProvider implements Authenticati
UserDetails user) {
Object password = this.useAuthenticationRequestCredentials ? authentication.getCredentials()
: user.getPassword();
UsernamePasswordAuthenticationToken result = new UsernamePasswordAuthenticationToken(user, password,
UsernamePasswordAuthenticationToken result = UsernamePasswordAuthenticationToken.authenticated(user, password,
this.authoritiesMapper.mapAuthorities(user.getAuthorities()));
result.setDetails(authentication.getDetails());
this.logger.debug("Authenticated user");

View File

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

View File

@ -53,7 +53,7 @@ public class PasswordComparisonAuthenticatorMockTests {
final NamingEnumeration searchResults = new BasicAttributes("", null).getAll();
given(dirCtx.search(eq("cn=Bob,ou=people"), eq("(userPassword={0})"), any(Object[].class),
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");
* you may not use this file except in compliance with the License.
@ -68,7 +68,7 @@ public class ActiveDirectoryLdapAuthenticationProviderTests {
ActiveDirectoryLdapAuthenticationProvider provider;
UsernamePasswordAuthenticationToken joe = new UsernamePasswordAuthenticationToken("joe", "password");
UsernamePasswordAuthenticationToken joe = UsernamePasswordAuthenticationToken.unauthenticated("joe", "password");
@BeforeEach
public void setUp() {
@ -162,7 +162,7 @@ public class ActiveDirectoryLdapAuthenticationProviderTests {
any(SearchControls.class))).willReturn(new MockNamingEnumeration(sr));
this.provider.contextFactory = createContextFactoryReturning(ctx);
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
@ -189,8 +189,8 @@ public class ActiveDirectoryLdapAuthenticationProviderTests {
// SEC-2500
@Test
public void sec2500PreventAnonymousBind() {
assertThatExceptionOfType(BadCredentialsException.class)
.isThrownBy(() -> this.provider.authenticate(new UsernamePasswordAuthenticationToken("rwinch", "")));
assertThatExceptionOfType(BadCredentialsException.class).isThrownBy(
() -> this.provider.authenticate(UsernamePasswordAuthenticationToken.unauthenticated("rwinch", "")));
}
@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");
* 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);
ByteBuf rawPassword = AuthMetadataCodec.readPassword(rawAuthentication);
String password = rawPassword.toString(StandardCharsets.UTF_8);
return new UsernamePasswordAuthenticationToken(username, password);
return UsernamePasswordAuthenticationToken.unauthenticated(username, password);
}
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");
* 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))
.flatMap((metadata) -> Mono
.justOrEmpty(metadata.get(UsernamePasswordMetadata.BASIC_AUTHENTICATION_MIME_TYPE.toString())))
.cast(UsernamePasswordMetadata.class)
.map((credentials) -> new UsernamePasswordAuthenticationToken(credentials.getUsername(),
credentials.getPassword()));
.cast(UsernamePasswordMetadata.class).map((credentials) -> UsernamePasswordAuthenticationToken
.unauthenticated(credentials.getUsername(), credentials.getPassword()));
}
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");
* you may not use this file except in compliance with the License.
@ -89,8 +89,8 @@ public class AuthenticationPayloadInterceptorTests {
interceptor.intercept(exchange, authenticationPayloadChain).block();
Authentication authentication = authenticationPayloadChain.getAuthentication();
verify(this.authenticationManager).authenticate(this.authenticationArg.capture());
assertThat(this.authenticationArg.getValue())
.isEqualToComparingFieldByField(new UsernamePasswordAuthenticationToken("user", "password"));
assertThat(this.authenticationArg.getValue()).isEqualToComparingFieldByField(
UsernamePasswordAuthenticationToken.unauthenticated("user", "password"));
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");
* 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()));
}
User principal = new User(username, withUser.password(), true, true, true, true, grantedAuthorities);
Authentication authentication = new UsernamePasswordAuthenticationToken(principal, principal.getPassword(),
principal.getAuthorities());
Authentication authentication = UsernamePasswordAuthenticationToken.authenticated(principal,
principal.getPassword(), principal.getAuthorities());
SecurityContext context = SecurityContextHolder.createEmptyContext();
context.setAuthentication(authentication);
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");
* 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();
Assert.hasLength(username, "value() must be non empty String");
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();
context.setAuthentication(authentication);
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");
* 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
*/
public static <T extends WebTestClientConfigurer & MockServerConfigurer> T mockUser(UserDetails userDetails) {
return mockAuthentication(new UsernamePasswordAuthenticationToken(userDetails, userDetails.getPassword(),
userDetails.getAuthorities()));
return mockAuthentication(UsernamePasswordAuthenticationToken.authenticated(userDetails,
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");
* you may not use this file except in compliance with the License.
@ -872,7 +872,7 @@ public final class SecurityMockMvcRequestPostProcessors {
private final RequestPostProcessor delegate;
UserDetailsRequestPostProcessor(UserDetails user) {
Authentication token = new UsernamePasswordAuthenticationToken(user, user.getPassword(),
Authentication token = UsernamePasswordAuthenticationToken.authenticated(user, user.getPassword(),
user.getAuthorities());
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");
* 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) {
SecurityContext context = SecurityContextHolder.createEmptyContext();
CustomUserDetails principal = new CustomUserDetails(customUser.name(), customUser.username());
Authentication auth = new UsernamePasswordAuthenticationToken(principal, "password",
Authentication auth = UsernamePasswordAuthenticationToken.authenticated(principal, "password",
principal.getAuthorities());
context.setAuthentication(auth);
return context;

View File

@ -79,7 +79,8 @@ public class UsernamePasswordAuthenticationFilter extends AbstractAuthentication
username = username.trim();
String password = obtainPassword(request);
password = (password != null) ? password : "";
UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(username, password);
UsernamePasswordAuthenticationToken authRequest = UsernamePasswordAuthenticationToken.unauthenticated(username,
password);
// Allow subclasses to set the "details" property
setDetails(request, 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);
newAuths.add(switchAuthority);
// create the new authentication token
targetUserRequest = new UsernamePasswordAuthenticationToken(targetUser, targetUser.getPassword(), newAuths);
targetUserRequest = UsernamePasswordAuthenticationToken.authenticated(targetUser, targetUser.getPassword(),
newAuths);
// set details
targetUserRequest.setDetails(this.authenticationDetailsSource.buildDetails(request));
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");
* you may not use this file except in compliance with the License.
@ -94,8 +94,8 @@ public class BasicAuthenticationConverter implements AuthenticationConverter {
if (delim == -1) {
throw new BadCredentialsException("Invalid basic authentication token");
}
UsernamePasswordAuthenticationToken result = new UsernamePasswordAuthenticationToken(token.substring(0, delim),
token.substring(delim + 1));
UsernamePasswordAuthenticationToken result = UsernamePasswordAuthenticationToken
.unauthenticated(token.substring(0, delim), token.substring(delim + 1));
result.setDetails(this.authenticationDetailsSource.buildDetails(request));
return result;
}

View File

@ -208,9 +208,9 @@ public class DigestAuthenticationFilter extends GenericFilterBean implements Mes
private UsernamePasswordAuthenticationToken getAuthRequest(UserDetails user) {
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)

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");
* 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) {
String username = data.getFirst(this.usernameParameter);
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");
* 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) {
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) {

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");
* 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();
List<GrantedAuthority> extendedTargetUserAuthorities = new ArrayList<>(targetUserAuthorities);
extendedTargetUserAuthorities.add(switchAuthority);
return new UsernamePasswordAuthenticationToken(targetUser, targetUser.getPassword(),
return UsernamePasswordAuthenticationToken.authenticated(targetUser, targetUser.getPassword(),
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");
* 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)
throws ServletException {
try {
UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(username,
password);
UsernamePasswordAuthenticationToken authentication = UsernamePasswordAuthenticationToken
.unauthenticated(username, password);
Object details = HttpServlet3RequestFactory.this.authenticationDetailsSource.buildDetails(this);
authentication.setDetails(details);
return authManager.authenticate(authentication);

View File

@ -440,7 +440,7 @@ public class AbstractAuthenticationProcessingFilterTests {
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
throws AuthenticationException {
if (this.grantAccess) {
return new UsernamePasswordAuthenticationToken("test", "test",
return UsernamePasswordAuthenticationToken.authenticated("test", "test",
AuthorityUtils.createAuthorityList("TEST"));
}
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");
* you may not use this file except in compliance with the License.
@ -280,8 +280,8 @@ public class AbstractPreAuthenticatedProcessingFilterTests {
@Test
public void requiresAuthenticationFalsePrincipalUser() throws Exception {
User currentPrincipal = new User("user", "password", AuthorityUtils.createAuthorityList("ROLE_USER"));
UsernamePasswordAuthenticationToken currentAuthentication = new UsernamePasswordAuthenticationToken(
currentPrincipal, currentPrincipal.getPassword(), currentPrincipal.getAuthorities());
UsernamePasswordAuthenticationToken currentAuthentication = UsernamePasswordAuthenticationToken
.authenticated(currentPrincipal, currentPrincipal.getPassword(), currentPrincipal.getAuthorities());
SecurityContextHolder.getContext().setAuthentication(currentAuthentication);
MockHttpServletRequest request = new MockHttpServletRequest();
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");
* 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 {
UserDetails ud = new User("dummyUser", "dummyPwd", true, true, true, true, AuthorityUtils.NO_AUTHORITIES);
PreAuthenticatedAuthenticationProvider provider = getProvider(ud);
Authentication request = new UsernamePasswordAuthenticationToken("dummyUser", "dummyPwd");
Authentication request = UsernamePasswordAuthenticationToken.unauthenticated("dummyUser", "dummyPwd");
Authentication result = provider.authenticate(request);
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");
* 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);
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
Authentication auth = new UsernamePasswordAuthenticationToken("joe", "password");
Authentication auth = UsernamePasswordAuthenticationToken.unauthenticated("joe", "password");
// No parameter set
services.loginSuccess(request, response, auth);
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");
* you may not use this file except in compliance with the License.
@ -108,7 +108,7 @@ public class PersistentTokenBasedRememberMeServicesTests {
this.services.setSeriesLength(12);
MockHttpServletResponse response = new MockHttpServletResponse();
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().getTokenValue().length()).isEqualTo(16);
String[] cookie = this.services.decodeCookie(response.getCookie("mycookiename").getValue());

View File

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

View File

@ -67,9 +67,10 @@ public class BasicAuthenticationFilterTests {
@BeforeEach
public void setUp() {
SecurityContextHolder.clearContext();
UsernamePasswordAuthenticationToken rodRequest = new UsernamePasswordAuthenticationToken("rod", "koala");
UsernamePasswordAuthenticationToken rodRequest = UsernamePasswordAuthenticationToken.unauthenticated("rod",
"koala");
rodRequest.setDetails(new WebAuthenticationDetails(new MockHttpServletRequest()));
Authentication rod = new UsernamePasswordAuthenticationToken("rod", "koala",
Authentication rod = UsernamePasswordAuthenticationToken.authenticated("rod", "koala",
AuthorityUtils.createAuthorityList("ROLE_1"));
this.manager = mock(AuthenticationManager.class);
given(this.manager.authenticate(rodRequest)).willReturn(rod);
@ -274,9 +275,10 @@ public class BasicAuthenticationFilterTests {
@Test
public void doFilterWhenTokenAndFilterCharsetMatchDefaultThenAuthenticated() throws Exception {
SecurityContextHolder.clearContext();
UsernamePasswordAuthenticationToken rodRequest = new UsernamePasswordAuthenticationToken("rod", "äöü");
UsernamePasswordAuthenticationToken rodRequest = UsernamePasswordAuthenticationToken.unauthenticated("rod",
"äöü");
rodRequest.setDetails(new WebAuthenticationDetails(new MockHttpServletRequest()));
Authentication rod = new UsernamePasswordAuthenticationToken("rod", "äöü",
Authentication rod = UsernamePasswordAuthenticationToken.authenticated("rod", "äöü",
AuthorityUtils.createAuthorityList("ROLE_1"));
this.manager = mock(AuthenticationManager.class);
given(this.manager.authenticate(rodRequest)).willReturn(rod);
@ -301,9 +303,10 @@ public class BasicAuthenticationFilterTests {
@Test
public void doFilterWhenTokenAndFilterCharsetMatchNonDefaultThenAuthenticated() throws Exception {
SecurityContextHolder.clearContext();
UsernamePasswordAuthenticationToken rodRequest = new UsernamePasswordAuthenticationToken("rod", "äöü");
UsernamePasswordAuthenticationToken rodRequest = UsernamePasswordAuthenticationToken.unauthenticated("rod",
"äöü");
rodRequest.setDetails(new WebAuthenticationDetails(new MockHttpServletRequest()));
Authentication rod = new UsernamePasswordAuthenticationToken("rod", "äöü",
Authentication rod = UsernamePasswordAuthenticationToken.authenticated("rod", "äöü",
AuthorityUtils.createAuthorityList("ROLE_1"));
this.manager = mock(AuthenticationManager.class);
given(this.manager.authenticate(rodRequest)).willReturn(rod);
@ -329,9 +332,10 @@ public class BasicAuthenticationFilterTests {
@Test
public void doFilterWhenTokenAndFilterCharsetDoNotMatchThenUnauthorized() throws Exception {
SecurityContextHolder.clearContext();
UsernamePasswordAuthenticationToken rodRequest = new UsernamePasswordAuthenticationToken("rod", "äöü");
UsernamePasswordAuthenticationToken rodRequest = UsernamePasswordAuthenticationToken.unauthenticated("rod",
"äöü");
rodRequest.setDetails(new WebAuthenticationDetails(new MockHttpServletRequest()));
Authentication rod = new UsernamePasswordAuthenticationToken("rod", "äöü",
Authentication rod = UsernamePasswordAuthenticationToken.authenticated("rod", "äöü",
AuthorityUtils.createAuthorityList("ROLE_1"));
this.manager = mock(AuthenticationManager.class);
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");
* you may not use this file except in compliance with the License.
@ -728,7 +728,7 @@ public class HttpSessionSecurityContextRepositoryTests {
}
private SecurityContext createSecurityContext(UserDetails userDetails) {
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(userDetails,
UsernamePasswordAuthenticationToken token = UsernamePasswordAuthenticationToken.authenticated(userDetails,
userDetails.getPassword(), userDetails.getAuthorities());
SecurityContext securityContext = new SecurityContextImpl(token);
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");
* you may not use this file except in compliance with the License.
@ -110,7 +110,7 @@ public class SwitchUserWebFilterTests {
final MockServerWebExchange exchange = MockServerWebExchange
.from(MockServerHttpRequest.post("/login/impersonate?username={targetUser}", targetUsername));
final WebFilterChain chain = mock(WebFilterChain.class);
final Authentication originalAuthentication = new UsernamePasswordAuthenticationToken("principal",
final Authentication originalAuthentication = UsernamePasswordAuthenticationToken.unauthenticated("principal",
"credentials");
final SecurityContextImpl securityContext = new SecurityContextImpl(originalAuthentication);
given(this.userDetailsService.findByUsername(targetUsername)).willReturn(Mono.just(switchUserDetails));
@ -143,12 +143,12 @@ public class SwitchUserWebFilterTests {
@Test
public void switchUserWhenUserAlreadySwitchedThenExitSwitchAndSwitchAgain() {
final Authentication originalAuthentication = new UsernamePasswordAuthenticationToken("origPrincipal",
"origCredentials");
final Authentication originalAuthentication = UsernamePasswordAuthenticationToken
.unauthenticated("origPrincipal", "origCredentials");
final GrantedAuthority switchAuthority = new SwitchUserGrantedAuthority(
SwitchUserWebFilter.ROLE_PREVIOUS_ADMINISTRATOR, originalAuthentication);
final Authentication switchUserAuthentication = new UsernamePasswordAuthenticationToken("switchPrincipal",
"switchCredentials", Collections.singleton(switchAuthority));
final Authentication switchUserAuthentication = UsernamePasswordAuthenticationToken
.authenticated("switchPrincipal", "switchCredentials", Collections.singleton(switchAuthority));
final SecurityContextImpl securityContext = new SecurityContextImpl(switchUserAuthentication);
final String targetUsername = "newSwitchPrincipal";
final MockServerWebExchange exchange = MockServerWebExchange
@ -228,12 +228,12 @@ public class SwitchUserWebFilterTests {
public void exitSwitchThenReturnToOriginalAuthentication() {
final MockServerWebExchange exchange = MockServerWebExchange
.from(MockServerHttpRequest.post("/logout/impersonate"));
final Authentication originalAuthentication = new UsernamePasswordAuthenticationToken("origPrincipal",
"origCredentials");
final Authentication originalAuthentication = UsernamePasswordAuthenticationToken
.unauthenticated("origPrincipal", "origCredentials");
final GrantedAuthority switchAuthority = new SwitchUserGrantedAuthority(
SwitchUserWebFilter.ROLE_PREVIOUS_ADMINISTRATOR, originalAuthentication);
final Authentication switchUserAuthentication = new UsernamePasswordAuthenticationToken("switchPrincipal",
"switchCredentials", Collections.singleton(switchAuthority));
final Authentication switchUserAuthentication = UsernamePasswordAuthenticationToken
.authenticated("switchPrincipal", "switchCredentials", Collections.singleton(switchAuthority));
final WebFilterChain chain = mock(WebFilterChain.class);
final SecurityContextImpl securityContext = new SecurityContextImpl(switchUserAuthentication);
given(this.serverSecurityContextRepository.save(eq(exchange), any(SecurityContext.class)))
@ -259,8 +259,8 @@ public class SwitchUserWebFilterTests {
public void exitSwitchWhenUserNotSwitchedThenThrowError() {
final MockServerWebExchange exchange = MockServerWebExchange
.from(MockServerHttpRequest.post("/logout/impersonate"));
final Authentication originalAuthentication = new UsernamePasswordAuthenticationToken("origPrincipal",
"origCredentials");
final Authentication originalAuthentication = UsernamePasswordAuthenticationToken
.unauthenticated("origPrincipal", "origCredentials");
final WebFilterChain chain = mock(WebFilterChain.class);
final SecurityContextImpl securityContext = new SecurityContextImpl(originalAuthentication);
assertThatExceptionOfType(AuthenticationCredentialsNotFoundException.class).isThrownBy(() -> {