diff --git a/config/src/integration-test/java/org/springframework/security/config/ldap/LdapProviderBeanDefinitionParserTests.java b/config/src/integration-test/java/org/springframework/security/config/ldap/LdapProviderBeanDefinitionParserTests.java index 43b2909477..d3b0f5c20c 100644 --- a/config/src/integration-test/java/org/springframework/security/config/ldap/LdapProviderBeanDefinitionParserTests.java +++ b/config/src/integration-test/java/org/springframework/security/config/ldap/LdapProviderBeanDefinitionParserTests.java @@ -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(); } diff --git a/config/src/test/java/org/springframework/security/config/annotation/authentication/AuthenticationManagerBuilderTests.java b/config/src/test/java/org/springframework/security/config/annotation/authentication/AuthenticationManagerBuilderTests.java index ddf6c5d930..1565ea5c90 100644 --- a/config/src/test/java/org/springframework/security/config/annotation/authentication/AuthenticationManagerBuilderTests.java +++ b/config/src/test/java/org/springframework/security/config/annotation/authentication/AuthenticationManagerBuilderTests.java @@ -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"); } diff --git a/config/src/test/java/org/springframework/security/config/annotation/authentication/configuration/AuthenticationConfigurationPublishTests.java b/config/src/test/java/org/springframework/security/config/annotation/authentication/configuration/AuthenticationConfigurationPublishTests.java index c313502b36..fc0931cf96 100644 --- a/config/src/test/java/org/springframework/security/config/annotation/authentication/configuration/AuthenticationConfigurationPublishTests.java +++ b/config/src/test/java/org/springframework/security/config/annotation/authentication/configuration/AuthenticationConfigurationPublishTests.java @@ -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); } diff --git a/config/src/test/java/org/springframework/security/config/annotation/authentication/configuration/AuthenticationConfigurationTests.java b/config/src/test/java/org/springframework/security/config/annotation/authentication/configuration/AuthenticationConfigurationTests.java index 412768d124..243bb0284e 100644 --- a/config/src/test/java/org/springframework/security/config/annotation/authentication/configuration/AuthenticationConfigurationTests.java +++ b/config/src/test/java/org/springframework/security/config/annotation/authentication/configuration/AuthenticationConfigurationTests.java @@ -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 diff --git a/config/src/test/java/org/springframework/security/config/annotation/issue50/Issue50Tests.java b/config/src/test/java/org/springframework/security/config/annotation/issue50/Issue50Tests.java index 1a2b82b004..4f1f12bdeb 100644 --- a/config/src/test/java/org/springframework/security/config/annotation/issue50/Issue50Tests.java +++ b/config/src/test/java/org/springframework/security/config/annotation/issue50/Issue50Tests.java @@ -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"))); } } diff --git a/config/src/test/java/org/springframework/security/config/annotation/method/configuration/GlobalMethodSecurityConfigurationTests.java b/config/src/test/java/org/springframework/security/config/annotation/method/configuration/GlobalMethodSecurityConfigurationTests.java index 2a0ae08bbe..b7f0a2cf85 100644 --- a/config/src/test/java/org/springframework/security/config/annotation/method/configuration/GlobalMethodSecurityConfigurationTests.java +++ b/config/src/test/java/org/springframework/security/config/annotation/method/configuration/GlobalMethodSecurityConfigurationTests.java @@ -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); } diff --git a/config/src/test/java/org/springframework/security/config/annotation/web/configuration/AuthenticationPrincipalArgumentResolverTests.java b/config/src/test/java/org/springframework/security/config/annotation/web/configuration/AuthenticationPrincipalArgumentResolverTests.java index 0899165c92..2272e476df 100644 --- a/config/src/test/java/org/springframework/security/config/annotation/web/configuration/AuthenticationPrincipalArgumentResolverTests.java +++ b/config/src/test/java/org/springframework/security/config/annotation/web/configuration/AuthenticationPrincipalArgumentResolverTests.java @@ -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 diff --git a/config/src/test/java/org/springframework/security/config/annotation/web/configuration/EnableWebSecurityTests.java b/config/src/test/java/org/springframework/security/config/annotation/web/configuration/EnableWebSecurityTests.java index dd05d35cc0..0f50a172fa 100644 --- a/config/src/test/java/org/springframework/security/config/annotation/web/configuration/EnableWebSecurityTests.java +++ b/config/src/test/java/org/springframework/security/config/annotation/web/configuration/EnableWebSecurityTests.java @@ -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(); } diff --git a/config/src/test/java/org/springframework/security/config/annotation/web/configuration/WebSecurityConfigurationTests.java b/config/src/test/java/org/springframework/security/config/annotation/web/configuration/WebSecurityConfigurationTests.java index 9a4985cc55..e73141c244 100644 --- a/config/src/test/java/org/springframework/security/config/annotation/web/configuration/WebSecurityConfigurationTests.java +++ b/config/src/test/java/org/springframework/security/config/annotation/web/configuration/WebSecurityConfigurationTests.java @@ -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 diff --git a/config/src/test/java/org/springframework/security/config/annotation/web/configurers/AuthorizeRequestsTests.java b/config/src/test/java/org/springframework/security/config/annotation/web/configurers/AuthorizeRequestsTests.java index d3e972094a..4fb51e6125 100644 --- a/config/src/test/java/org/springframework/security/config/annotation/web/configurers/AuthorizeRequestsTests.java +++ b/config/src/test/java/org/springframework/security/config/annotation/web/configurers/AuthorizeRequestsTests.java @@ -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); diff --git a/config/src/test/java/org/springframework/security/config/annotation/web/configurers/NamespaceHttpInterceptUrlTests.java b/config/src/test/java/org/springframework/security/config/annotation/web/configurers/NamespaceHttpInterceptUrlTests.java index 6f5c5aec5d..4301210456 100644 --- a/config/src/test/java/org/springframework/security/config/annotation/web/configurers/NamespaceHttpInterceptUrlTests.java +++ b/config/src/test/java/org/springframework/security/config/annotation/web/configurers/NamespaceHttpInterceptUrlTests.java @@ -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 diff --git a/config/src/test/java/org/springframework/security/config/annotation/web/configurers/NamespaceHttpServerAccessDeniedHandlerTests.java b/config/src/test/java/org/springframework/security/config/annotation/web/configurers/NamespaceHttpServerAccessDeniedHandlerTests.java index 0414368d7e..3a140a2b20 100644 --- a/config/src/test/java/org/springframework/security/config/annotation/web/configurers/NamespaceHttpServerAccessDeniedHandlerTests.java +++ b/config/src/test/java/org/springframework/security/config/annotation/web/configurers/NamespaceHttpServerAccessDeniedHandlerTests.java @@ -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 verifyBean(Class beanClass) { diff --git a/config/src/test/java/org/springframework/security/config/authentication/AuthenticationConfigurationGh3935Tests.java b/config/src/test/java/org/springframework/security/config/authentication/AuthenticationConfigurationGh3935Tests.java index 6d5c0d50d7..5f71fabd98 100644 --- a/config/src/test/java/org/springframework/security/config/authentication/AuthenticationConfigurationGh3935Tests.java +++ b/config/src/test/java/org/springframework/security/config/authentication/AuthenticationConfigurationGh3935Tests.java @@ -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()); } diff --git a/config/src/test/java/org/springframework/security/config/authentication/AuthenticationManagerBeanDefinitionParserTests.java b/config/src/test/java/org/springframework/security/config/authentication/AuthenticationManagerBeanDefinitionParserTests.java index df39c4b8b3..0d16101f62 100644 --- a/config/src/test/java/org/springframework/security/config/authentication/AuthenticationManagerBeanDefinitionParserTests.java +++ b/config/src/test/java/org/springframework/security/config/authentication/AuthenticationManagerBeanDefinitionParserTests.java @@ -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); } diff --git a/config/src/test/java/org/springframework/security/config/authentication/AuthenticationProviderBeanDefinitionParserTests.java b/config/src/test/java/org/springframework/security/config/authentication/AuthenticationProviderBeanDefinitionParserTests.java index b32069216d..eccb380c6b 100644 --- a/config/src/test/java/org/springframework/security/config/authentication/AuthenticationProviderBeanDefinitionParserTests.java +++ b/config/src/test/java/org/springframework/security/config/authentication/AuthenticationProviderBeanDefinitionParserTests.java @@ -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() { diff --git a/config/src/test/java/org/springframework/security/config/authentication/JdbcUserServiceBeanDefinitionParserTests.java b/config/src/test/java/org/springframework/security/config/authentication/JdbcUserServiceBeanDefinitionParserTests.java index 75ae43bebf..6cd758bbc2 100644 --- a/config/src/test/java/org/springframework/security/config/authentication/JdbcUserServiceBeanDefinitionParserTests.java +++ b/config/src/test/java/org/springframework/security/config/authentication/JdbcUserServiceBeanDefinitionParserTests.java @@ -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"); } diff --git a/config/src/test/java/org/springframework/security/config/method/GlobalMethodSecurityBeanDefinitionParserTests.java b/config/src/test/java/org/springframework/security/config/method/GlobalMethodSecurityBeanDefinitionParserTests.java index 378abd27ee..a899204892 100644 --- a/config/src/test/java/org/springframework/security/config/method/GlobalMethodSecurityBeanDefinitionParserTests.java +++ b/config/src/test/java/org/springframework/security/config/method/GlobalMethodSecurityBeanDefinitionParserTests.java @@ -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 { + ""); // @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")); } diff --git a/config/src/test/java/org/springframework/security/config/method/InterceptMethodsBeanDefinitionDecoratorTests.java b/config/src/test/java/org/springframework/security/config/method/InterceptMethodsBeanDefinitionDecoratorTests.java index 15e375b618..e7dd933100 100644 --- a/config/src/test/java/org/springframework/security/config/method/InterceptMethodsBeanDefinitionDecoratorTests.java +++ b/config/src/test/java/org/springframework/security/config/method/InterceptMethodsBeanDefinitionDecoratorTests.java @@ -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); } diff --git a/config/src/test/java/org/springframework/security/config/method/Jsr250AnnotationDrivenBeanDefinitionParserTests.java b/config/src/test/java/org/springframework/security/config/method/Jsr250AnnotationDrivenBeanDefinitionParserTests.java index 0e699b7366..654a01b2f3 100644 --- a/config/src/test/java/org/springframework/security/config/method/Jsr250AnnotationDrivenBeanDefinitionParserTests.java +++ b/config/src/test/java/org/springframework/security/config/method/Jsr250AnnotationDrivenBeanDefinitionParserTests.java @@ -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(); } diff --git a/config/src/test/java/org/springframework/security/config/method/MethodSecurityBeanDefinitionParserTests.java b/config/src/test/java/org/springframework/security/config/method/MethodSecurityBeanDefinitionParserTests.java index c458528f2e..adcb526a72 100644 --- a/config/src/test/java/org/springframework/security/config/method/MethodSecurityBeanDefinitionParserTests.java +++ b/config/src/test/java/org/springframework/security/config/method/MethodSecurityBeanDefinitionParserTests.java @@ -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) diff --git a/config/src/test/java/org/springframework/security/config/method/SecuredAnnotationDrivenBeanDefinitionParserTests.java b/config/src/test/java/org/springframework/security/config/method/SecuredAnnotationDrivenBeanDefinitionParserTests.java index 4b760367df..4995df4369 100644 --- a/config/src/test/java/org/springframework/security/config/method/SecuredAnnotationDrivenBeanDefinitionParserTests.java +++ b/config/src/test/java/org/springframework/security/config/method/SecuredAnnotationDrivenBeanDefinitionParserTests.java @@ -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); } diff --git a/core/src/main/java/org/springframework/security/authentication/AbstractUserDetailsReactiveAuthenticationManager.java b/core/src/main/java/org/springframework/security/authentication/AbstractUserDetailsReactiveAuthenticationManager.java index d75a2775cd..5a08efd019 100644 --- a/core/src/main/java/org/springframework/security/authentication/AbstractUserDetailsReactiveAuthenticationManager.java +++ b/core/src/main/java/org/springframework/security/authentication/AbstractUserDetailsReactiveAuthenticationManager.java @@ -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()); } diff --git a/core/src/main/java/org/springframework/security/authentication/UsernamePasswordAuthenticationToken.java b/core/src/main/java/org/springframework/security/authentication/UsernamePasswordAuthenticationToken.java index 55963150a6..be796d04a4 100644 --- a/core/src/main/java/org/springframework/security/authentication/UsernamePasswordAuthenticationToken.java +++ b/core/src/main/java/org/springframework/security/authentication/UsernamePasswordAuthenticationToken.java @@ -32,6 +32,7 @@ import org.springframework.util.Assert; * String. * * @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 UsernamePasswordAuthenticationToken. + * @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 UsernamePasswordAuthenticationToken. + * @param principal + * @param credentials + * @return UsernamePasswordAuthenticationToken with true isAuthenticated() result + * + * @since 5.7 + */ + public static UsernamePasswordAuthenticationToken authenticated(Object principal, Object credentials, + Collection authorities) { + return new UsernamePasswordAuthenticationToken(principal, credentials, authorities); + } + @Override public Object getCredentials() { return this.credentials; diff --git a/core/src/main/java/org/springframework/security/authentication/dao/AbstractUserDetailsAuthenticationProvider.java b/core/src/main/java/org/springframework/security/authentication/dao/AbstractUserDetailsAuthenticationProvider.java index f85306cdd3..7d5b434d52 100644 --- a/core/src/main/java/org/springframework/security/authentication/dao/AbstractUserDetailsAuthenticationProvider.java +++ b/core/src/main/java/org/springframework/security/authentication/dao/AbstractUserDetailsAuthenticationProvider.java @@ -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"); diff --git a/core/src/main/java/org/springframework/security/jackson2/UsernamePasswordAuthenticationTokenDeserializer.java b/core/src/main/java/org/springframework/security/jackson2/UsernamePasswordAuthenticationTokenDeserializer.java index c5d815ad79..aebdf3c827 100644 --- a/core/src/main/java/org/springframework/security/jackson2/UsernamePasswordAuthenticationTokenDeserializer.java +++ b/core/src/main/java/org/springframework/security/jackson2/UsernamePasswordAuthenticationTokenDeserializer.java @@ -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 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); diff --git a/core/src/main/java/org/springframework/security/provisioning/InMemoryUserDetailsManager.java b/core/src/main/java/org/springframework/security/provisioning/InMemoryUserDetailsManager.java index c613035a05..8e7b6b254d 100644 --- a/core/src/main/java/org/springframework/security/provisioning/InMemoryUserDetailsManager.java +++ b/core/src/main/java/org/springframework/security/provisioning/InMemoryUserDetailsManager.java @@ -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."); diff --git a/core/src/main/java/org/springframework/security/provisioning/JdbcUserDetailsManager.java b/core/src/main/java/org/springframework/security/provisioning/JdbcUserDetailsManager.java index 2cfda0ab06..264568f49f 100644 --- a/core/src/main/java/org/springframework/security/provisioning/JdbcUserDetailsManager.java +++ b/core/src/main/java/org/springframework/security/provisioning/JdbcUserDetailsManager.java @@ -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; } diff --git a/core/src/test/java/org/springframework/security/access/AuthorizationFailureEventTests.java b/core/src/test/java/org/springframework/security/access/AuthorizationFailureEventTests.java index fde3f5e700..cd1c569907 100644 --- a/core/src/test/java/org/springframework/security/access/AuthorizationFailureEventTests.java +++ b/core/src/test/java/org/springframework/security/access/AuthorizationFailureEventTests.java @@ -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 attributes = SecurityConfig.createList("TEST"); diff --git a/core/src/test/java/org/springframework/security/access/AuthorizedEventTests.java b/core/src/test/java/org/springframework/security/access/AuthorizedEventTests.java index b55a060eb8..c5655ec282 100644 --- a/core/src/test/java/org/springframework/security/access/AuthorizedEventTests.java +++ b/core/src/test/java/org/springframework/security/access/AuthorizedEventTests.java @@ -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 diff --git a/core/src/test/java/org/springframework/security/access/intercept/RunAsManagerImplTests.java b/core/src/test/java/org/springframework/security/access/intercept/RunAsManagerImplTests.java index 41eddcd218..cd877b09cd 100644 --- a/core/src/test/java/org/springframework/security/access/intercept/RunAsManagerImplTests.java +++ b/core/src/test/java/org/springframework/security/access/intercept/RunAsManagerImplTests.java @@ -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(), diff --git a/core/src/test/java/org/springframework/security/access/vote/AuthenticatedVoterTests.java b/core/src/test/java/org/springframework/security/access/vote/AuthenticatedVoterTests.java index 1d2cfa3657..bff472e362 100644 --- a/core/src/test/java/org/springframework/security/access/vote/AuthenticatedVoterTests.java +++ b/core/src/test/java/org/springframework/security/access/vote/AuthenticatedVoterTests.java @@ -44,7 +44,7 @@ public class AuthenticatedVoterTests { } private Authentication createFullyAuthenticated() { - return new UsernamePasswordAuthenticationToken("ignored", "ignored", + return UsernamePasswordAuthenticationToken.authenticated("ignored", "ignored", AuthorityUtils.createAuthorityList("ignored")); } diff --git a/core/src/test/java/org/springframework/security/authentication/ProviderManagerTests.java b/core/src/test/java/org/springframework/security/authentication/ProviderManagerTests.java index e0a1fe336c..b64dbce4fe 100644 --- a/core/src/test/java/org/springframework/security/authentication/ProviderManagerTests.java +++ b/core/src/test/java/org/springframework/security/authentication/ProviderManagerTests.java @@ -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(); } diff --git a/core/src/test/java/org/springframework/security/authentication/ReactiveUserDetailsServiceAuthenticationManagerTests.java b/core/src/test/java/org/springframework/security/authentication/ReactiveUserDetailsServiceAuthenticationManagerTests.java index eabd9256c5..cca23a0dae 100644 --- a/core/src/test/java/org/springframework/security/authentication/ReactiveUserDetailsServiceAuthenticationManagerTests.java +++ b/core/src/test/java/org/springframework/security/authentication/ReactiveUserDetailsServiceAuthenticationManagerTests.java @@ -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 = 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 = 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 = this.manager.authenticate(token); // @formatter:off diff --git a/core/src/test/java/org/springframework/security/authentication/TestAuthentication.java b/core/src/test/java/org/springframework/security/authentication/TestAuthentication.java index 0583c42a48..cdeb4ba1d8 100644 --- a/core/src/test/java/org/springframework/security/authentication/TestAuthentication.java +++ b/core/src/test/java/org/springframework/security/authentication/TestAuthentication.java @@ -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()); } } diff --git a/core/src/test/java/org/springframework/security/authentication/UserDetailsRepositoryReactiveAuthenticationManagerTests.java b/core/src/test/java/org/springframework/security/authentication/UserDetailsRepositoryReactiveAuthenticationManagerTests.java index 50e73593d2..c8f39d52e3 100644 --- a/core/src/test/java/org/springframework/security/authentication/UserDetailsRepositoryReactiveAuthenticationManagerTests.java +++ b/core/src/test/java/org/springframework/security/authentication/UserDetailsRepositoryReactiveAuthenticationManagerTests.java @@ -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()); } diff --git a/core/src/test/java/org/springframework/security/authentication/UsernamePasswordAuthenticationTokenTests.java b/core/src/test/java/org/springframework/security/authentication/UsernamePasswordAuthenticationTokenTests.java index 8c3eda3dd8..4f9e38e766 100644 --- a/core/src/test/java/org/springframework/security/authentication/UsernamePasswordAuthenticationTokenTests.java +++ b/core/src/test/java/org/springframework/security/authentication/UsernamePasswordAuthenticationTokenTests.java @@ -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(); + } + } diff --git a/core/src/test/java/org/springframework/security/authentication/anonymous/AnonymousAuthenticationTokenTests.java b/core/src/test/java/org/springframework/security/authentication/anonymous/AnonymousAuthenticationTokenTests.java index 4910b622d5..780d391418 100644 --- a/core/src/test/java/org/springframework/security/authentication/anonymous/AnonymousAuthenticationTokenTests.java +++ b/core/src/test/java/org/springframework/security/authentication/anonymous/AnonymousAuthenticationTokenTests.java @@ -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(); } diff --git a/core/src/test/java/org/springframework/security/authentication/dao/DaoAuthenticationProviderTests.java b/core/src/test/java/org/springframework/security/authentication/dao/DaoAuthenticationProviderTests.java index 4292ce3703..5d523c2a3e 100644 --- a/core/src/test/java/org/springframework/security/authentication/dao/DaoAuthenticationProviderTests.java +++ b/core/src/test/java/org/springframework/security/authentication/dao/DaoAuthenticationProviderTests.java @@ -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); diff --git a/core/src/test/java/org/springframework/security/authentication/event/AuthenticationEventTests.java b/core/src/test/java/org/springframework/security/authentication/event/AuthenticationEventTests.java index f2ecf729c8..605a161546 100644 --- a/core/src/test/java/org/springframework/security/authentication/event/AuthenticationEventTests.java +++ b/core/src/test/java/org/springframework/security/authentication/event/AuthenticationEventTests.java @@ -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; } diff --git a/core/src/test/java/org/springframework/security/authentication/event/LoggerListenerTests.java b/core/src/test/java/org/springframework/security/authentication/event/LoggerListenerTests.java index 1efd1e083e..07133b8864 100644 --- a/core/src/test/java/org/springframework/security/authentication/event/LoggerListenerTests.java +++ b/core/src/test/java/org/springframework/security/authentication/event/LoggerListenerTests.java @@ -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; } diff --git a/core/src/test/java/org/springframework/security/authentication/jaas/DefaultJaasAuthenticationProviderTests.java b/core/src/test/java/org/springframework/security/authentication/jaas/DefaultJaasAuthenticationProviderTests.java index 4aa8862111..3df2268f58 100644 --- a/core/src/test/java/org/springframework/security/authentication/jaas/DefaultJaasAuthenticationProviderTests.java +++ b/core/src/test/java/org/springframework/security/authentication/jaas/DefaultJaasAuthenticationProviderTests.java @@ -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.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(); } diff --git a/core/src/test/java/org/springframework/security/authentication/jaas/JaasAuthenticationProviderTests.java b/core/src/test/java/org/springframework/security/authentication/jaas/JaasAuthenticationProviderTests.java index 46ade0722d..4da9805811 100644 --- a/core/src/test/java/org/springframework/security/authentication/jaas/JaasAuthenticationProviderTests.java +++ b/core/src/test/java/org/springframework/security/authentication/jaas/JaasAuthenticationProviderTests.java @@ -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") diff --git a/core/src/test/java/org/springframework/security/authentication/jaas/Sec760Tests.java b/core/src/test/java/org/springframework/security/authentication/jaas/Sec760Tests.java index 6dd80ffe06..8fe9cdfa22 100644 --- a/core/src/test/java/org/springframework/security/authentication/jaas/Sec760Tests.java +++ b/core/src/test/java/org/springframework/security/authentication/jaas/Sec760Tests.java @@ -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(); } diff --git a/core/src/test/java/org/springframework/security/authentication/jaas/SecurityContextLoginModuleTests.java b/core/src/test/java/org/springframework/security/authentication/jaas/SecurityContextLoginModuleTests.java index 9b631a303a..293d85bd44 100644 --- a/core/src/test/java/org/springframework/security/authentication/jaas/SecurityContextLoginModuleTests.java +++ b/core/src/test/java/org/springframework/security/authentication/jaas/SecurityContextLoginModuleTests.java @@ -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 diff --git a/core/src/test/java/org/springframework/security/authentication/rememberme/RememberMeAuthenticationTokenTests.java b/core/src/test/java/org/springframework/security/authentication/rememberme/RememberMeAuthenticationTokenTests.java index fa6b817768..fc89bc3760 100644 --- a/core/src/test/java/org/springframework/security/authentication/rememberme/RememberMeAuthenticationTokenTests.java +++ b/core/src/test/java/org/springframework/security/authentication/rememberme/RememberMeAuthenticationTokenTests.java @@ -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(); } diff --git a/core/src/test/java/org/springframework/security/core/context/SecurityContextHolderTests.java b/core/src/test/java/org/springframework/security/core/context/SecurityContextHolderTests.java index 563f7a307a..6aecd517ac 100644 --- a/core/src/test/java/org/springframework/security/core/context/SecurityContextHolderTests.java +++ b/core/src/test/java/org/springframework/security/core/context/SecurityContextHolderTests.java @@ -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(); diff --git a/core/src/test/java/org/springframework/security/core/context/SecurityContextImplTests.java b/core/src/test/java/org/springframework/security/core/context/SecurityContextImplTests.java index 645151b7cf..3e15ea5723 100644 --- a/core/src/test/java/org/springframework/security/core/context/SecurityContextImplTests.java +++ b/core/src/test/java/org/springframework/security/core/context/SecurityContextImplTests.java @@ -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(); diff --git a/core/src/test/java/org/springframework/security/jackson2/SecurityContextMixinTests.java b/core/src/test/java/org/springframework/security/jackson2/SecurityContextMixinTests.java index ced0820357..524d75d99d 100644 --- a/core/src/test/java/org/springframework/security/jackson2/SecurityContextMixinTests.java +++ b/core/src/test/java/org/springframework/security/jackson2/SecurityContextMixinTests.java @@ -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); diff --git a/core/src/test/java/org/springframework/security/jackson2/UsernamePasswordAuthenticationTokenMixinTests.java b/core/src/test/java/org/springframework/security/jackson2/UsernamePasswordAuthenticationTokenMixinTests.java index f28bfae6e9..21d8815642 100644 --- a/core/src/test/java/org/springframework/security/jackson2/UsernamePasswordAuthenticationTokenMixinTests.java +++ b/core/src/test/java/org/springframework/security/jackson2/UsernamePasswordAuthenticationTokenMixinTests.java @@ -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; } diff --git a/core/src/test/java/org/springframework/security/provisioning/JdbcUserDetailsManagerTests.java b/core/src/test/java/org/springframework/security/provisioning/JdbcUserDetailsManagerTests.java index 4192377632..a04b84bdc3 100644 --- a/core/src/test/java/org/springframework/security/provisioning/JdbcUserDetailsManagerTests.java +++ b/core/src/test/java/org/springframework/security/provisioning/JdbcUserDetailsManagerTests.java @@ -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; diff --git a/docs/modules/ROOT/pages/features/integrations/concurrency.adoc b/docs/modules/ROOT/pages/features/integrations/concurrency.adoc index 32535f2720..69c5978bcb 100644 --- a/docs/modules/ROOT/pages/features/integrations/concurrency.adoc +++ b/docs/modules/ROOT/pages/features/integrations/concurrency.adoc @@ -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 = diff --git a/docs/modules/ROOT/pages/servlet/integrations/concurrency.adoc b/docs/modules/ROOT/pages/servlet/integrations/concurrency.adoc index c3a597650d..f3bf98ab69 100644 --- a/docs/modules/ROOT/pages/servlet/integrations/concurrency.adoc +++ b/docs/modules/ROOT/pages/servlet/integrations/concurrency.adoc @@ -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 = diff --git a/docs/modules/ROOT/pages/servlet/test/method.adoc b/docs/modules/ROOT/pages/servlet/test/method.adoc index bb52c1ad9d..1c3cb96730 100644 --- a/docs/modules/ROOT/pages/servlet/test/method.adoc +++ b/docs/modules/ROOT/pages/servlet/test/method.adoc @@ -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; diff --git a/itest/context/src/integration-test/java/org/springframework/security/integration/python/PythonInterpreterBasedSecurityTests.java b/itest/context/src/integration-test/java/org/springframework/security/integration/python/PythonInterpreterBasedSecurityTests.java index 2958b435fc..df4c34f69d 100644 --- a/itest/context/src/integration-test/java/org/springframework/security/integration/python/PythonInterpreterBasedSecurityTests.java +++ b/itest/context/src/integration-test/java/org/springframework/security/integration/python/PythonInterpreterBasedSecurityTests.java @@ -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(); diff --git a/itest/context/src/integration-test/java/org/springframework/security/performance/FilterChainPerformanceTests.java b/itest/context/src/integration-test/java/org/springframework/security/performance/FilterChainPerformanceTests.java index a450851c4f..e951cda356 100644 --- a/itest/context/src/integration-test/java/org/springframework/security/performance/FilterChainPerformanceTests.java +++ b/itest/context/src/integration-test/java/org/springframework/security/performance/FilterChainPerformanceTests.java @@ -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(); diff --git a/itest/misc/src/integration-test/java/org/springframework/security/context/SecurityContextHolderMTTests.java b/itest/misc/src/integration-test/java/org/springframework/security/context/SecurityContextHolderMTTests.java index 4a09b0afc3..380941cad6 100644 --- a/itest/misc/src/integration-test/java/org/springframework/security/context/SecurityContextHolderMTTests.java +++ b/itest/misc/src/integration-test/java/org/springframework/security/context/SecurityContextHolderMTTests.java @@ -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()); diff --git a/ldap/src/integration-test/java/org/springframework/security/ldap/authentication/BindAuthenticatorTests.java b/ldap/src/integration-test/java/org/springframework/security/ldap/authentication/BindAuthenticatorTests.java index bfffaa17de..789df1813d 100644 --- a/ldap/src/integration-test/java/org/springframework/security/ldap/authentication/BindAuthenticatorTests.java +++ b/ldap/src/integration-test/java/org/springframework/security/ldap/authentication/BindAuthenticatorTests.java @@ -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 diff --git a/ldap/src/integration-test/java/org/springframework/security/ldap/authentication/PasswordComparisonAuthenticatorTests.java b/ldap/src/integration-test/java/org/springframework/security/ldap/authentication/PasswordComparisonAuthenticatorTests.java index 645da5c962..0994a2b4b4 100644 --- a/ldap/src/integration-test/java/org/springframework/security/ldap/authentication/PasswordComparisonAuthenticatorTests.java +++ b/ldap/src/integration-test/java/org/springframework/security/ldap/authentication/PasswordComparisonAuthenticatorTests.java @@ -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")); } } diff --git a/ldap/src/integration-test/java/org/springframework/security/ldap/userdetails/LdapUserDetailsManagerTests.java b/ldap/src/integration-test/java/org/springframework/security/ldap/userdetails/LdapUserDetailsManagerTests.java index ee2d1be55e..db29d64880 100644 --- a/ldap/src/integration-test/java/org/springframework/security/ldap/userdetails/LdapUserDetailsManagerTests.java +++ b/ldap/src/integration-test/java/org/springframework/security/ldap/userdetails/LdapUserDetailsManagerTests.java @@ -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")); } diff --git a/ldap/src/main/java/org/springframework/security/ldap/authentication/AbstractLdapAuthenticationProvider.java b/ldap/src/main/java/org/springframework/security/ldap/authentication/AbstractLdapAuthenticationProvider.java index 5b7fb37ce5..5263f9cecb 100644 --- a/ldap/src/main/java/org/springframework/security/ldap/authentication/AbstractLdapAuthenticationProvider.java +++ b/ldap/src/main/java/org/springframework/security/ldap/authentication/AbstractLdapAuthenticationProvider.java @@ -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"); diff --git a/ldap/src/test/java/org/springframework/security/ldap/authentication/LdapAuthenticationProviderTests.java b/ldap/src/test/java/org/springframework/security/ldap/authentication/LdapAuthenticationProviderTests.java index c006829f18..092523f227 100644 --- a/ldap/src/test/java/org/springframework/security/ldap/authentication/LdapAuthenticationProviderTests.java +++ b/ldap/src/test/java/org/springframework/security/ldap/authentication/LdapAuthenticationProviderTests.java @@ -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()); diff --git a/ldap/src/test/java/org/springframework/security/ldap/authentication/PasswordComparisonAuthenticatorMockTests.java b/ldap/src/test/java/org/springframework/security/ldap/authentication/PasswordComparisonAuthenticatorMockTests.java index 3cc38176eb..ec5432367c 100644 --- a/ldap/src/test/java/org/springframework/security/ldap/authentication/PasswordComparisonAuthenticatorMockTests.java +++ b/ldap/src/test/java/org/springframework/security/ldap/authentication/PasswordComparisonAuthenticatorMockTests.java @@ -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")); } } diff --git a/ldap/src/test/java/org/springframework/security/ldap/authentication/ad/ActiveDirectoryLdapAuthenticationProviderTests.java b/ldap/src/test/java/org/springframework/security/ldap/authentication/ad/ActiveDirectoryLdapAuthenticationProviderTests.java index 4d0a5bc2a6..e0d28f9392 100644 --- a/ldap/src/test/java/org/springframework/security/ldap/authentication/ad/ActiveDirectoryLdapAuthenticationProviderTests.java +++ b/ldap/src/test/java/org/springframework/security/ldap/authentication/ad/ActiveDirectoryLdapAuthenticationProviderTests.java @@ -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 diff --git a/rsocket/src/main/java/org/springframework/security/rsocket/authentication/AuthenticationPayloadExchangeConverter.java b/rsocket/src/main/java/org/springframework/security/rsocket/authentication/AuthenticationPayloadExchangeConverter.java index b804004ae5..bbe90e5eb8 100644 --- a/rsocket/src/main/java/org/springframework/security/rsocket/authentication/AuthenticationPayloadExchangeConverter.java +++ b/rsocket/src/main/java/org/springframework/security/rsocket/authentication/AuthenticationPayloadExchangeConverter.java @@ -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) { diff --git a/rsocket/src/main/java/org/springframework/security/rsocket/authentication/BasicAuthenticationPayloadExchangeConverter.java b/rsocket/src/main/java/org/springframework/security/rsocket/authentication/BasicAuthenticationPayloadExchangeConverter.java index 1a806c3bb8..0d3a9cc76d 100644 --- a/rsocket/src/main/java/org/springframework/security/rsocket/authentication/BasicAuthenticationPayloadExchangeConverter.java +++ b/rsocket/src/main/java/org/springframework/security/rsocket/authentication/BasicAuthenticationPayloadExchangeConverter.java @@ -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() { diff --git a/rsocket/src/test/java/org/springframework/security/rsocket/authentication/AuthenticationPayloadInterceptorTests.java b/rsocket/src/test/java/org/springframework/security/rsocket/authentication/AuthenticationPayloadInterceptorTests.java index c622ef7cc8..82495f2cb9 100644 --- a/rsocket/src/test/java/org/springframework/security/rsocket/authentication/AuthenticationPayloadInterceptorTests.java +++ b/rsocket/src/test/java/org/springframework/security/rsocket/authentication/AuthenticationPayloadInterceptorTests.java @@ -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); } diff --git a/test/src/main/java/org/springframework/security/test/context/support/WithMockUserSecurityContextFactory.java b/test/src/main/java/org/springframework/security/test/context/support/WithMockUserSecurityContextFactory.java index 513723c1f1..323e130680 100644 --- a/test/src/main/java/org/springframework/security/test/context/support/WithMockUserSecurityContextFactory.java +++ b/test/src/main/java/org/springframework/security/test/context/support/WithMockUserSecurityContextFactory.java @@ -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; diff --git a/test/src/main/java/org/springframework/security/test/context/support/WithUserDetailsSecurityContextFactory.java b/test/src/main/java/org/springframework/security/test/context/support/WithUserDetailsSecurityContextFactory.java index cabc9e348b..b9d6b7ce53 100644 --- a/test/src/main/java/org/springframework/security/test/context/support/WithUserDetailsSecurityContextFactory.java +++ b/test/src/main/java/org/springframework/security/test/context/support/WithUserDetailsSecurityContextFactory.java @@ -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; diff --git a/test/src/main/java/org/springframework/security/test/web/reactive/server/SecurityMockServerConfigurers.java b/test/src/main/java/org/springframework/security/test/web/reactive/server/SecurityMockServerConfigurers.java index c77a889f8f..174a318879 100644 --- a/test/src/main/java/org/springframework/security/test/web/reactive/server/SecurityMockServerConfigurers.java +++ b/test/src/main/java/org/springframework/security/test/web/reactive/server/SecurityMockServerConfigurers.java @@ -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 mockUser(UserDetails userDetails) { - return mockAuthentication(new UsernamePasswordAuthenticationToken(userDetails, userDetails.getPassword(), - userDetails.getAuthorities())); + return mockAuthentication(UsernamePasswordAuthenticationToken.authenticated(userDetails, + userDetails.getPassword(), userDetails.getAuthorities())); } /** diff --git a/test/src/main/java/org/springframework/security/test/web/servlet/request/SecurityMockMvcRequestPostProcessors.java b/test/src/main/java/org/springframework/security/test/web/servlet/request/SecurityMockMvcRequestPostProcessors.java index caceea21f6..193b6a558e 100644 --- a/test/src/main/java/org/springframework/security/test/web/servlet/request/SecurityMockMvcRequestPostProcessors.java +++ b/test/src/main/java/org/springframework/security/test/web/servlet/request/SecurityMockMvcRequestPostProcessors.java @@ -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); } diff --git a/test/src/test/java/org/springframework/security/test/context/showcase/WithMockCustomUserSecurityContextFactory.java b/test/src/test/java/org/springframework/security/test/context/showcase/WithMockCustomUserSecurityContextFactory.java index d174584cb1..79f59ded86 100644 --- a/test/src/test/java/org/springframework/security/test/context/showcase/WithMockCustomUserSecurityContextFactory.java +++ b/test/src/test/java/org/springframework/security/test/context/showcase/WithMockCustomUserSecurityContextFactory.java @@ -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; diff --git a/web/src/main/java/org/springframework/security/web/authentication/UsernamePasswordAuthenticationFilter.java b/web/src/main/java/org/springframework/security/web/authentication/UsernamePasswordAuthenticationFilter.java index 4b9b16b903..c5323077d8 100644 --- a/web/src/main/java/org/springframework/security/web/authentication/UsernamePasswordAuthenticationFilter.java +++ b/web/src/main/java/org/springframework/security/web/authentication/UsernamePasswordAuthenticationFilter.java @@ -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); diff --git a/web/src/main/java/org/springframework/security/web/authentication/switchuser/SwitchUserFilter.java b/web/src/main/java/org/springframework/security/web/authentication/switchuser/SwitchUserFilter.java index 256f2e7d43..140a344996 100644 --- a/web/src/main/java/org/springframework/security/web/authentication/switchuser/SwitchUserFilter.java +++ b/web/src/main/java/org/springframework/security/web/authentication/switchuser/SwitchUserFilter.java @@ -297,7 +297,8 @@ public class SwitchUserFilter extends GenericFilterBean implements ApplicationEv List 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; diff --git a/web/src/main/java/org/springframework/security/web/authentication/www/BasicAuthenticationConverter.java b/web/src/main/java/org/springframework/security/web/authentication/www/BasicAuthenticationConverter.java index 25cd4d095d..a45baed753 100644 --- a/web/src/main/java/org/springframework/security/web/authentication/www/BasicAuthenticationConverter.java +++ b/web/src/main/java/org/springframework/security/web/authentication/www/BasicAuthenticationConverter.java @@ -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; } diff --git a/web/src/main/java/org/springframework/security/web/authentication/www/DigestAuthenticationFilter.java b/web/src/main/java/org/springframework/security/web/authentication/www/DigestAuthenticationFilter.java index 34cc3c7162..54e633f333 100644 --- a/web/src/main/java/org/springframework/security/web/authentication/www/DigestAuthenticationFilter.java +++ b/web/src/main/java/org/springframework/security/web/authentication/www/DigestAuthenticationFilter.java @@ -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) diff --git a/web/src/main/java/org/springframework/security/web/server/ServerFormLoginAuthenticationConverter.java b/web/src/main/java/org/springframework/security/web/server/ServerFormLoginAuthenticationConverter.java index 9d538ad0aa..01fa28c6b0 100644 --- a/web/src/main/java/org/springframework/security/web/server/ServerFormLoginAuthenticationConverter.java +++ b/web/src/main/java/org/springframework/security/web/server/ServerFormLoginAuthenticationConverter.java @@ -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 data) { String username = data.getFirst(this.usernameParameter); String password = data.getFirst(this.passwordParameter); - return new UsernamePasswordAuthenticationToken(username, password); + return UsernamePasswordAuthenticationToken.unauthenticated(username, password); } /** diff --git a/web/src/main/java/org/springframework/security/web/server/ServerHttpBasicAuthenticationConverter.java b/web/src/main/java/org/springframework/security/web/server/ServerHttpBasicAuthenticationConverter.java index 3f58b31ec7..db33e5e107 100644 --- a/web/src/main/java/org/springframework/security/web/server/ServerHttpBasicAuthenticationConverter.java +++ b/web/src/main/java/org/springframework/security/web/server/ServerHttpBasicAuthenticationConverter.java @@ -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 targetUserAuthorities = targetUser.getAuthorities(); List extendedTargetUserAuthorities = new ArrayList<>(targetUserAuthorities); extendedTargetUserAuthorities.add(switchAuthority); - return new UsernamePasswordAuthenticationToken(targetUser, targetUser.getPassword(), + return UsernamePasswordAuthenticationToken.authenticated(targetUser, targetUser.getPassword(), extendedTargetUserAuthorities); } diff --git a/web/src/main/java/org/springframework/security/web/servletapi/HttpServlet3RequestFactory.java b/web/src/main/java/org/springframework/security/web/servletapi/HttpServlet3RequestFactory.java index 2acfb4f75b..f3c8959536 100644 --- a/web/src/main/java/org/springframework/security/web/servletapi/HttpServlet3RequestFactory.java +++ b/web/src/main/java/org/springframework/security/web/servletapi/HttpServlet3RequestFactory.java @@ -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); diff --git a/web/src/test/java/org/springframework/security/web/authentication/AbstractAuthenticationProcessingFilterTests.java b/web/src/test/java/org/springframework/security/web/authentication/AbstractAuthenticationProcessingFilterTests.java index b9948c435f..f7cdabce5c 100644 --- a/web/src/test/java/org/springframework/security/web/authentication/AbstractAuthenticationProcessingFilterTests.java +++ b/web/src/test/java/org/springframework/security/web/authentication/AbstractAuthenticationProcessingFilterTests.java @@ -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 { diff --git a/web/src/test/java/org/springframework/security/web/authentication/preauth/AbstractPreAuthenticatedProcessingFilterTests.java b/web/src/test/java/org/springframework/security/web/authentication/preauth/AbstractPreAuthenticatedProcessingFilterTests.java index e8dc80f882..5acbb6dd62 100644 --- a/web/src/test/java/org/springframework/security/web/authentication/preauth/AbstractPreAuthenticatedProcessingFilterTests.java +++ b/web/src/test/java/org/springframework/security/web/authentication/preauth/AbstractPreAuthenticatedProcessingFilterTests.java @@ -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(); diff --git a/web/src/test/java/org/springframework/security/web/authentication/preauth/PreAuthenticatedAuthenticationProviderTests.java b/web/src/test/java/org/springframework/security/web/authentication/preauth/PreAuthenticatedAuthenticationProviderTests.java index 671385b8f8..b278c8c2ce 100644 --- a/web/src/test/java/org/springframework/security/web/authentication/preauth/PreAuthenticatedAuthenticationProviderTests.java +++ b/web/src/test/java/org/springframework/security/web/authentication/preauth/PreAuthenticatedAuthenticationProviderTests.java @@ -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(); } diff --git a/web/src/test/java/org/springframework/security/web/authentication/rememberme/AbstractRememberMeServicesTests.java b/web/src/test/java/org/springframework/security/web/authentication/rememberme/AbstractRememberMeServicesTests.java index 7de3bef577..5d18684375 100644 --- a/web/src/test/java/org/springframework/security/web/authentication/rememberme/AbstractRememberMeServicesTests.java +++ b/web/src/test/java/org/springframework/security/web/authentication/rememberme/AbstractRememberMeServicesTests.java @@ -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(); diff --git a/web/src/test/java/org/springframework/security/web/authentication/rememberme/PersistentTokenBasedRememberMeServicesTests.java b/web/src/test/java/org/springframework/security/web/authentication/rememberme/PersistentTokenBasedRememberMeServicesTests.java index 7d8a821958..2801240e23 100644 --- a/web/src/test/java/org/springframework/security/web/authentication/rememberme/PersistentTokenBasedRememberMeServicesTests.java +++ b/web/src/test/java/org/springframework/security/web/authentication/rememberme/PersistentTokenBasedRememberMeServicesTests.java @@ -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()); diff --git a/web/src/test/java/org/springframework/security/web/authentication/switchuser/SwitchUserFilterTests.java b/web/src/test/java/org/springframework/security/web/authentication/switchuser/SwitchUserFilterTests.java index d483c4fddc..e6a51eab42 100644 --- a/web/src/test/java/org/springframework/security/web/authentication/switchuser/SwitchUserFilterTests.java +++ b/web/src/test/java/org/springframework/security/web/authentication/switchuser/SwitchUserFilterTests.java @@ -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 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); diff --git a/web/src/test/java/org/springframework/security/web/authentication/www/BasicAuthenticationFilterTests.java b/web/src/test/java/org/springframework/security/web/authentication/www/BasicAuthenticationFilterTests.java index a274e80f5b..afe61ae8fb 100644 --- a/web/src/test/java/org/springframework/security/web/authentication/www/BasicAuthenticationFilterTests.java +++ b/web/src/test/java/org/springframework/security/web/authentication/www/BasicAuthenticationFilterTests.java @@ -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); diff --git a/web/src/test/java/org/springframework/security/web/context/HttpSessionSecurityContextRepositoryTests.java b/web/src/test/java/org/springframework/security/web/context/HttpSessionSecurityContextRepositoryTests.java index 870372eda7..dd93c46665 100644 --- a/web/src/test/java/org/springframework/security/web/context/HttpSessionSecurityContextRepositoryTests.java +++ b/web/src/test/java/org/springframework/security/web/context/HttpSessionSecurityContextRepositoryTests.java @@ -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; diff --git a/web/src/test/java/org/springframework/security/web/server/authentication/SwitchUserWebFilterTests.java b/web/src/test/java/org/springframework/security/web/server/authentication/SwitchUserWebFilterTests.java index 527d90345d..4e7609f303 100644 --- a/web/src/test/java/org/springframework/security/web/server/authentication/SwitchUserWebFilterTests.java +++ b/web/src/test/java/org/springframework/security/web/server/authentication/SwitchUserWebFilterTests.java @@ -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(() -> {