docs
Concrete implementations of the Authentication interface for various authentication mechanisms including username/password, anonymous, remember-me, testing, JAAS, and one-time token authentication.
Core Capabilities:
TestingAuthenticationToken and TestingAuthenticationProviderJaasAuthenticationToken with LoginContextOneTimeTokenAuthenticationToken and OneTimeTokenAuthenticationKey Interfaces and Classes:
UsernamePasswordAuthenticationToken - Standard username/password authenticationAnonymousAuthenticationToken - Represents anonymous/unauthenticated usersRememberMeAuthenticationToken - Remember-me cookie authenticationTestingAuthenticationToken - Simple token for unit/integration testsJaasAuthenticationToken - JAAS authentication with LoginContextOneTimeTokenAuthenticationToken - Unauthenticated token with OTT valueOneTimeTokenAuthentication - Authenticated token after OTT validationAbstractAuthenticationToken - Base class for custom tokensDefault Behaviors:
unauthenticated() and authenticated() (preferred)TestingAuthenticationToken instancesgetCredentials() and getPrincipal() both return token valueThreading Model:
setAuthenticated() which throws if called incorrectly)Lifecycle:
eraseCredentials())SecurityContext after successful authenticationExceptions:
IllegalArgumentException - Thrown by setAuthenticated() if called on already-authenticated tokenInvalidOneTimeTokenException - Thrown when OTT is invalid, expired, or already usedEdge Cases:
isAuthenticated() returns false, used for authentication requestsisAuthenticated() returns true, used for successful resultsTestingAuthenticationProvider accepts all instances (no validation)AbstractAuthenticationToken, call super constructor with authoritiesStandard authentication token for username and password authentication.
package org.springframework.security.authentication;
class UsernamePasswordAuthenticationToken extends AbstractAuthenticationToken {
UsernamePasswordAuthenticationToken(Object principal, Object credentials);
UsernamePasswordAuthenticationToken(Object principal, Object credentials,
Collection<? extends GrantedAuthority> authorities);
static UsernamePasswordAuthenticationToken unauthenticated(
Object principal, Object credentials);
static UsernamePasswordAuthenticationToken authenticated(
Object principal, Object credentials,
Collection<? extends GrantedAuthority> authorities);
Object getCredentials();
Object getPrincipal();
void setAuthenticated(boolean authenticated) throws IllegalArgumentException;
void eraseCredentials();
}Constructor Details:
Static Factory Methods:
unauthenticated(Object, Object) - Creates an authentication request token with isAuthenticated() == false.authenticated(Object, Object, Collection) - Creates a fully authenticated token with authorities.Usage Example:
// Creating an authentication request
UsernamePasswordAuthenticationToken authRequest =
UsernamePasswordAuthenticationToken.unauthenticated("john", "password123");
// Authenticate via manager
Authentication result = authenticationManager.authenticate(authRequest);
// Creating an authenticated token directly (in custom provider)
UsernamePasswordAuthenticationToken authenticated =
UsernamePasswordAuthenticationToken.authenticated(
userDetails,
null, // credentials typically null after authentication
userDetails.getAuthorities()
);
// Check authentication status
if (authenticated.isAuthenticated()) {
SecurityContextHolder.getContext().setAuthentication(authenticated);
}Represents an anonymous user (unauthenticated visitor).
package org.springframework.security.authentication;
class AnonymousAuthenticationToken extends AbstractAuthenticationToken {
AnonymousAuthenticationToken(String key, Object principal,
Collection<? extends GrantedAuthority> authorities);
AnonymousAuthenticationToken(Integer keyHash, Object principal,
Collection<? extends GrantedAuthority> authorities);
int getKeyHash();
Object getCredentials();
Object getPrincipal();
boolean equals(Object obj);
int hashCode();
}Constructor Details:
AnonymousAuthenticationToken(String, Object, Collection) - Creates token with string key (hashed internally).AnonymousAuthenticationToken(Integer, Object, Collection) - Creates token with pre-computed key hash.Method Details:
getKeyHash() - Returns the hash of the key used to identify anonymous authentication provider.Usage Example:
// Creating anonymous authentication
String key = "myAnonymousKey";
Object principal = "anonymousUser";
List<GrantedAuthority> authorities =
AuthorityUtils.createAuthorityList("ROLE_ANONYMOUS");
AnonymousAuthenticationToken anonymous =
new AnonymousAuthenticationToken(key, principal, authorities);
// Check if current authentication is anonymous
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
if (auth instanceof AnonymousAuthenticationToken) {
log.info("Anonymous user detected");
}
// Using trust resolver
AuthenticationTrustResolver trustResolver = new AuthenticationTrustResolverImpl();
if (trustResolver.isAnonymous(auth)) {
log.info("User is anonymous");
}Processes AnonymousAuthenticationToken instances.
package org.springframework.security.authentication;
class AnonymousAuthenticationProvider implements AuthenticationProvider,
MessageSourceAware {
AnonymousAuthenticationProvider(String key);
Authentication authenticate(Authentication authentication)
throws AuthenticationException;
boolean supports(Class<?> authentication);
int getKey();
void setMessageSource(MessageSource messageSource);
}Constructor Details:
AnonymousAuthenticationProvider(String) - Creates provider with the specified key.Method Details:
authenticate(Authentication) - Validates the key hash matches the provider's key.supports(Class) - Returns true for AnonymousAuthenticationToken.getKey() - Returns the hash of the key.Usage Example:
String key = "myAnonymousKey";
AnonymousAuthenticationProvider provider = new AnonymousAuthenticationProvider(key);
// Add to provider manager
List<AuthenticationProvider> providers = Arrays.asList(
daoAuthenticationProvider,
provider
);
ProviderManager authManager = new ProviderManager(providers);Represents authentication via a remember-me cookie.
package org.springframework.security.authentication;
class RememberMeAuthenticationToken extends AbstractAuthenticationToken {
RememberMeAuthenticationToken(String key, Object principal,
Collection<? extends GrantedAuthority> authorities);
int getKeyHash();
Object getCredentials();
Object getPrincipal();
boolean equals(Object obj);
int hashCode();
}Constructor Details:
RememberMeAuthenticationToken(String, Object, Collection) - Creates token with key, principal, and authorities.Method Details:
getKeyHash() - Returns the hash of the key used to identify remember-me provider.Usage Example:
// Creating remember-me authentication
String key = "myRememberMeKey";
UserDetails user = userDetailsService.loadUserByUsername("john");
RememberMeAuthenticationToken rememberMe =
new RememberMeAuthenticationToken(key, user, user.getAuthorities());
// Check if authentication is remember-me
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
AuthenticationTrustResolver trustResolver = new AuthenticationTrustResolverImpl();
if (trustResolver.isRememberMe(auth)) {
log.info("User authenticated via remember-me");
// May require re-authentication for sensitive operations
}Processes RememberMeAuthenticationToken instances.
package org.springframework.security.authentication;
class RememberMeAuthenticationProvider implements AuthenticationProvider,
InitializingBean, MessageSourceAware {
RememberMeAuthenticationProvider(String key);
Authentication authenticate(Authentication authentication)
throws AuthenticationException;
boolean supports(Class<?> authentication);
String getKey();
void setMessageSource(MessageSource messageSource);
void afterPropertiesSet();
}Constructor Details:
RememberMeAuthenticationProvider(String) - Creates provider with the specified key.Method Details:
authenticate(Authentication) - Validates the key matches the provider's key.supports(Class) - Returns true for RememberMeAuthenticationToken.getKey() - Returns the key string.Usage Example:
String key = "myRememberMeKey";
RememberMeAuthenticationProvider provider =
new RememberMeAuthenticationProvider(key);
// Add to provider manager
ProviderManager authManager = new ProviderManager(
daoAuthenticationProvider,
provider,
anonymousAuthenticationProvider
);Simple authentication token for unit and integration tests.
package org.springframework.security.authentication;
class TestingAuthenticationToken extends AbstractAuthenticationToken {
TestingAuthenticationToken(Object principal, Object credentials);
TestingAuthenticationToken(Object principal, Object credentials,
String... authorities);
TestingAuthenticationToken(Object principal, Object credentials,
List<GrantedAuthority> authorities);
Object getCredentials();
Object getPrincipal();
}Constructor Details:
TestingAuthenticationToken(Object, Object) - Creates unauthenticated token.TestingAuthenticationToken(Object, Object, String...) - Creates authenticated token with string authorities.TestingAuthenticationToken(Object, Object, List) - Creates authenticated token with authority objects.Usage Example:
// In unit tests
@Test
public void testSecuredMethod() {
// Create authenticated test token
TestingAuthenticationToken auth = new TestingAuthenticationToken(
"testUser", "password", "ROLE_USER", "ROLE_ADMIN");
// Set in security context
SecurityContextHolder.getContext().setAuthentication(auth);
// Call secured method
String result = securedService.getSecretData();
assertNotNull(result);
}
// Simple unauthenticated token
TestingAuthenticationToken unauth = new TestingAuthenticationToken("user", "pass");
assertFalse(unauth.isAuthenticated());
// Authenticated token with authorities
TestingAuthenticationToken auth = new TestingAuthenticationToken(
"john", "credentials",
AuthorityUtils.createAuthorityList("ROLE_USER", "ROLE_ADMIN"));
assertTrue(auth.isAuthenticated());Simple authentication provider for testing that accepts all TestingAuthenticationToken instances.
package org.springframework.security.authentication;
class TestingAuthenticationProvider implements AuthenticationProvider {
TestingAuthenticationProvider();
Authentication authenticate(Authentication authentication)
throws AuthenticationException;
boolean supports(Class<?> authentication);
}Method Details:
authenticate(Authentication) - Returns the token as-is if it's a TestingAuthenticationToken.supports(Class) - Returns true for TestingAuthenticationToken.Usage Example:
// Configure for integration tests
@TestConfiguration
static class TestSecurityConfig {
@Bean
public AuthenticationManager authenticationManager() {
return new ProviderManager(new TestingAuthenticationProvider());
}
}Authentication token for JAAS (Java Authentication and Authorization Service) integration.
package org.springframework.security.authentication.jaas;
class JaasAuthenticationToken extends UsernamePasswordAuthenticationToken {
JaasAuthenticationToken(Object principal, Object credentials,
LoginContext loginContext);
JaasAuthenticationToken(Object principal, Object credentials,
Collection<? extends GrantedAuthority> authorities,
LoginContext loginContext);
LoginContext getLoginContext();
void setLoginContext(LoginContext loginContext);
}Constructor Details:
javax.security.auth.login.LoginContext in addition to standard authentication parameters.Method Details:
getLoginContext() - Returns the JAAS LoginContext associated with this authentication.setLoginContext(LoginContext) - Sets the login context.Usage Example:
// Created by JAAS authentication provider after successful login
LoginContext loginContext = // ... from JAAS authentication
JaasAuthenticationToken token = new JaasAuthenticationToken(
principal,
credentials,
authorities,
loginContext
);
// Access JAAS subjects
Subject subject = loginContext.getSubject();
Set<Principal> principals = subject.getPrincipals();Unauthenticated token containing a one-time token value for authentication.
package org.springframework.security.authentication.ott;
class OneTimeTokenAuthenticationToken extends AbstractAuthenticationToken {
OneTimeTokenAuthenticationToken(String tokenValue);
String getTokenValue();
Object getCredentials();
Object getPrincipal();
}Constructor Details:
OneTimeTokenAuthenticationToken(String) - Creates unauthenticated token with the OTT value.Method Details:
getTokenValue() - Returns the one-time token value.getCredentials() - Returns the token value.getPrincipal() - Returns the token value.Usage Example:
// User receives OTT via email/SMS
String tokenFromEmail = "abc123xyz789";
// Create authentication request
OneTimeTokenAuthenticationToken authRequest =
new OneTimeTokenAuthenticationToken(tokenFromEmail);
// Authenticate
Authentication result = authenticationManager.authenticate(authRequest);
SecurityContextHolder.getContext().setAuthentication(result);Authenticated token after successful one-time token validation.
package org.springframework.security.authentication.ott;
class OneTimeTokenAuthentication extends AbstractAuthenticationToken {
OneTimeTokenAuthentication(Object principal,
Collection<? extends GrantedAuthority> authorities);
Object getCredentials();
Object getPrincipal();
}Constructor Details:
OneTimeTokenAuthentication(Object, Collection) - Creates authenticated token with principal and authorities.Usage Example:
// Created by OneTimeTokenAuthenticationProvider after successful validation
UserDetails user = userDetailsService.loadUserByUsername(username);
OneTimeTokenAuthentication authenticated =
new OneTimeTokenAuthentication(user, user.getAuthorities());Authentication provider that validates one-time tokens.
package org.springframework.security.authentication.ott;
class OneTimeTokenAuthenticationProvider implements AuthenticationProvider {
OneTimeTokenAuthenticationProvider(OneTimeTokenService oneTimeTokenService,
UserDetailsService userDetailsService);
Authentication authenticate(Authentication authentication)
throws AuthenticationException;
boolean supports(Class<?> authentication);
}Constructor Details:
OneTimeTokenService for consuming tokens and UserDetailsService for loading user details.Method Details:
authenticate(Authentication) - Consumes the OTT and loads user details if valid.supports(Class) - Returns true for OneTimeTokenAuthenticationToken.Usage Example:
// Configure OTT authentication
OneTimeTokenService tokenService = new InMemoryOneTimeTokenService();
UserDetailsService userDetailsService = // ... user details service
OneTimeTokenAuthenticationProvider provider =
new OneTimeTokenAuthenticationProvider(tokenService, userDetailsService);
// Add to authentication manager
ProviderManager authManager = new ProviderManager(
daoAuthenticationProvider,
provider
);
// Generate token for user
GenerateOneTimeTokenRequest request =
new GenerateOneTimeTokenRequest("john@example.com");
OneTimeToken token = tokenService.generate(request);
// Send token to user via email/SMS
emailService.sendToken(token.getUsername(), token.getTokenValue());
// User authenticates with token
OneTimeTokenAuthenticationToken authRequest =
new OneTimeTokenAuthenticationToken(token.getTokenValue());
Authentication result = authManager.authenticate(authRequest);Reactive authentication manager for one-time tokens.
package org.springframework.security.authentication.ott.reactive;
class OneTimeTokenReactiveAuthenticationManager
implements ReactiveAuthenticationManager {
OneTimeTokenReactiveAuthenticationManager(
ReactiveOneTimeTokenService oneTimeTokenService,
ReactiveUserDetailsService userDetailsService);
Mono<Authentication> authenticate(Authentication authentication);
}Constructor Details:
Usage Example:
ReactiveOneTimeTokenService tokenService =
new InMemoryReactiveOneTimeTokenService();
ReactiveUserDetailsService userDetailsService = // ... reactive service
OneTimeTokenReactiveAuthenticationManager authManager =
new OneTimeTokenReactiveAuthenticationManager(tokenService, userDetailsService);
// Reactive authentication
OneTimeTokenAuthenticationToken authRequest =
new OneTimeTokenAuthenticationToken(tokenValue);
authManager.authenticate(authRequest)
.doOnSuccess(auth -> {
log.info("User authenticated: {}", auth.getName());
})
.subscribe();Token for pre-authenticated scenarios where authentication happened in an external system.
package org.springframework.security.web.authentication.preauth;
class PreAuthenticatedAuthenticationToken extends AbstractAuthenticationToken {
PreAuthenticatedAuthenticationToken(Object principal, Object credentials);
PreAuthenticatedAuthenticationToken(Object principal, Object credentials,
Collection<? extends GrantedAuthority> authorities);
Object getCredentials();
Object getPrincipal();
}Constructor Details:
Usage Example:
// External authentication (e.g., SSO, X.509 certificate)
String principal = request.getRemoteUser(); // from container authentication
Object credentials = "N/A"; // not applicable for pre-auth
PreAuthenticatedAuthenticationToken preAuth =
new PreAuthenticatedAuthenticationToken(principal, credentials);
// Authenticate to load authorities
Authentication result = authenticationManager.authenticate(preAuth);
SecurityContextHolder.getContext().setAuthentication(result);To create custom authentication tokens, extend AbstractAuthenticationToken:
// Example: Custom token with additional metadata
public class CustomAuthenticationToken extends AbstractAuthenticationToken {
private final Object principal;
private Object credentials;
private final String customMetadata;
// Unauthenticated constructor
public CustomAuthenticationToken(Object principal, Object credentials,
String customMetadata) {
super(null);
this.principal = principal;
this.credentials = credentials;
this.customMetadata = customMetadata;
setAuthenticated(false);
}
// Authenticated constructor
public CustomAuthenticationToken(Object principal, Object credentials,
Collection<? extends GrantedAuthority> authorities,
String customMetadata) {
super(authorities);
this.principal = principal;
this.credentials = credentials;
this.customMetadata = customMetadata;
super.setAuthenticated(true);
}
@Override
public Object getCredentials() {
return credentials;
}
@Override
public Object getPrincipal() {
return principal;
}
public String getCustomMetadata() {
return customMetadata;
}
@Override
public void eraseCredentials() {
super.eraseCredentials();
credentials = null;
}
// Static factory methods
public static CustomAuthenticationToken unauthenticated(
Object principal, Object credentials, String metadata) {
return new CustomAuthenticationToken(principal, credentials, metadata);
}
public static CustomAuthenticationToken authenticated(
Object principal, Object credentials,
Collection<? extends GrantedAuthority> authorities,
String metadata) {
return new CustomAuthenticationToken(
principal, credentials, authorities, metadata);
}
}
// Usage
CustomAuthenticationToken authRequest =
CustomAuthenticationToken.unauthenticated("user", "pass", "metadata123");
// In custom provider
CustomAuthenticationToken authenticated =
CustomAuthenticationToken.authenticated(
userDetails, null, authorities, "metadata123");