Skip to content

Commit

Permalink
Add UsernamePasswordAuthenticationToken factory methods
Browse files Browse the repository at this point in the history
 - 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 spring-projectsgh-10790
  • Loading branch information
nor-ek authored and jzheaux committed Mar 9, 2022
1 parent 28c7a4b commit abd3338
Show file tree
Hide file tree
Showing 88 changed files with 439 additions and 346 deletions.
Original file line number Diff line number Diff line change
@@ -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.
Expand Down Expand Up @@ -56,7 +56,7 @@ public void simpleProviderAuthenticatesCorrectly() {
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);
}
Expand Down Expand Up @@ -89,7 +89,7 @@ public void supportsPasswordComparisonAuthentication() {
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();
}
Expand All @@ -104,7 +104,8 @@ public void supportsPasswordComparisonAuthenticationWithPasswordEncoder() {

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();
}
Expand All @@ -121,7 +122,7 @@ public void supportsCryptoPasswordEncoder() {
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();
}
Expand Down
Original file line number Diff line number Diff line change
@@ -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.
Expand Down Expand Up @@ -93,8 +93,8 @@ public void customAuthenticationEventPublisherWithWeb() throws Exception {
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());
}

Expand All @@ -103,7 +103,8 @@ public void getAuthenticationManagerWhenGlobalPasswordEncoderBeanThenUsed() thro
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");
}
Expand All @@ -113,7 +114,8 @@ public void getAuthenticationManagerWhenProtectedPasswordEncoderBeanThenUsed() t
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");
}
Expand Down
Original file line number Diff line number Diff line change
@@ -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.
Expand Down Expand Up @@ -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);
}

Expand Down
Original file line number Diff line number Diff line change
@@ -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.
Expand Down Expand Up @@ -129,7 +129,8 @@ public void getAuthenticationManagerWhenNoOpGlobalAuthenticationConfigurerAdapte

@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)
Expand All @@ -139,7 +140,8 @@ public void getAuthenticationWhenGlobalAuthenticationConfigurerAdapterThenAuthen

@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)
Expand All @@ -165,9 +167,9 @@ public void getAuthenticationWhenConfiguredThenBootNotTrigger() throws Exception
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
Expand All @@ -176,7 +178,7 @@ public void getAuthenticationWhenNotConfiguredThenBootTrigger() throws Exception
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
Expand Down Expand Up @@ -206,9 +208,9 @@ public void getAuthenticationWhenUserDetailsServiceBeanThenAuthenticationManager
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
Expand All @@ -221,9 +223,9 @@ public void getAuthenticationWhenUserDetailsServiceAndPasswordEncoderBeanThenEnc
.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
Expand All @@ -237,7 +239,7 @@ public void getAuthenticationWhenUserDetailsServiceAndPasswordManagerThenManager
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}"));
}

Expand All @@ -250,7 +252,7 @@ public void getAuthenticationWhenAuthenticationProviderAndUserDetailsBeanThenAut
.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
Expand All @@ -262,7 +264,7 @@ public void getAuthenticationWhenAuthenticationProviderBeanThenUsed() throws Exc
.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
Expand Down
Original file line number Diff line number Diff line change
@@ -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.
Expand Down Expand Up @@ -75,21 +75,21 @@ public void loadWhenGlobalMethodSecurityConfigurationThenAuthenticationManagerLa
@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");
}

Expand All @@ -98,7 +98,7 @@ public void globalMethodSecurityIsEnabledWhenNotAllowedThenAccessDenied() {
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")));
}

}
Original file line number Diff line number Diff line change
@@ -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.
Expand Down Expand Up @@ -106,8 +106,8 @@ public void configureWhenGlobalMethodSecurityHasCustomMetadataSourceThenNoEnabli
@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);
}
Expand Down
Original file line number Diff line number Diff line change
@@ -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.
Expand Down Expand Up @@ -65,7 +65,7 @@ public void authenticationPrincipalExpressionWhenBeanExpressionSuppliedThenBeanU
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
Expand Down
Original file line number Diff line number Diff line change
@@ -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.
Expand Down Expand Up @@ -60,7 +60,7 @@ public void configureWhenOverrideAuthenticationManagerBeanThenAuthenticationMana
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();
}

Expand Down
Original file line number Diff line number Diff line change
@@ -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.
Expand Down Expand Up @@ -1013,7 +1013,7 @@ static AuthenticationManager authenticationManager1() {
return new ProviderManager(new AuthenticationProvider() {
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
return new UsernamePasswordAuthenticationToken("user", "credentials");
return UsernamePasswordAuthenticationToken.unauthenticated("user", "credentials");
}

@Override
Expand All @@ -1028,7 +1028,7 @@ static AuthenticationManager authenticationManager2() {
return new ProviderManager(new AuthenticationProvider() {
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
return new UsernamePasswordAuthenticationToken("subuser", "credentials");
return UsernamePasswordAuthenticationToken.unauthenticated("subuser", "credentials");
}

@Override
Expand Down
Original file line number Diff line number Diff line change
@@ -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.
Expand Down Expand Up @@ -150,7 +150,7 @@ public void antMatchersPathVariablesCaseInsensitiveCamelCaseVariables() throws E
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);
Expand Down
Original file line number Diff line number Diff line change
@@ -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.
Expand Down Expand Up @@ -100,7 +100,8 @@ public void requestWhenRequiresChannelThenBehaviorMatchesNamespace() throws Exce
}

private static Authentication user(String role) {
return new UsernamePasswordAuthenticationToken("user", null, AuthorityUtils.createAuthorityList(role));
return UsernamePasswordAuthenticationToken.authenticated("user", null,
AuthorityUtils.createAuthorityList(role));
}

@EnableWebSecurity
Expand Down
Original file line number Diff line number Diff line change
@@ -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.
Expand Down Expand Up @@ -97,7 +97,7 @@ public void requestWhenCustomAccessDeniedHandlerInLambdaThenBehaviorMatchesNames
}

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) {
Expand Down
Loading

0 comments on commit abd3338

Please sign in to comment.