or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

aot-native-support.mdauthentication-core.mdauthentication-events.mdauthentication-management.mdauthentication-tokens.mdauthorities.mdauthorization.mdcompromised-password.mdconcurrent-async.mddao-authentication.mdexpression-access-control.mdindex.mdjaas-authentication.mdjackson-serialization.mdmethod-security.mdobservation-metrics.mdone-time-tokens.mdprovisioning.mdsecurity-context.mdsession-management.mduser-details.md
tile.json

authentication-tokens.mddocs/

Authentication Tokens

Concrete implementations of the Authentication interface for various authentication mechanisms including username/password, anonymous, remember-me, testing, JAAS, and one-time token authentication.

Key Information for Agents

Core Capabilities:

  • Multiple token types for different authentication mechanisms
  • Factory methods for creating authenticated vs unauthenticated tokens
  • Key-based validation for anonymous and remember-me tokens
  • Testing support via TestingAuthenticationToken and TestingAuthenticationProvider
  • JAAS integration via JaasAuthenticationToken with LoginContext
  • One-time token support via OneTimeTokenAuthenticationToken and OneTimeTokenAuthentication

Key Interfaces and Classes:

  • UsernamePasswordAuthenticationToken - Standard username/password authentication
  • AnonymousAuthenticationToken - Represents anonymous/unauthenticated users
  • RememberMeAuthenticationToken - Remember-me cookie authentication
  • TestingAuthenticationToken - Simple token for unit/integration tests
  • JaasAuthenticationToken - JAAS authentication with LoginContext
  • OneTimeTokenAuthenticationToken - Unauthenticated token with OTT value
  • OneTimeTokenAuthentication - Authenticated token after OTT validation
  • AbstractAuthenticationToken - Base class for custom tokens

Default Behaviors:

  • Two-arg constructor creates unauthenticated token (for requests)
  • Three-arg constructor with authorities creates authenticated token (for results)
  • Factory methods: unauthenticated() and authenticated() (preferred)
  • Anonymous/Remember-me tokens validated via key hash matching
  • Testing provider accepts all TestingAuthenticationToken instances
  • OTT tokens: getCredentials() and getPrincipal() both return token value

Threading Model:

  • Tokens are immutable after creation (except setAuthenticated() which throws if called incorrectly)
  • Thread-safe: No shared mutable state

Lifecycle:

  • Tokens created by authentication providers or manually
  • Credentials erased after authentication (via eraseCredentials())
  • Tokens stored in SecurityContext after successful authentication

Exceptions:

  • IllegalArgumentException - Thrown by setAuthenticated() if called on already-authenticated token
  • InvalidOneTimeTokenException - Thrown when OTT is invalid, expired, or already used
  • Authentication exceptions from providers (BadCredentialsException, etc.)

Edge Cases:

  • Unauthenticated tokens: isAuthenticated() returns false, used for authentication requests
  • Authenticated tokens: isAuthenticated() returns true, used for successful results
  • Key validation: Anonymous/Remember-me providers validate key hash matches
  • Testing tokens: TestingAuthenticationProvider accepts all instances (no validation)
  • OTT consumption: Token consumed (removed) after successful validation (single-use)
  • Custom tokens: Extend AbstractAuthenticationToken, call super constructor with authorities

Username/Password Authentication

UsernamePasswordAuthenticationToken

Standard 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:

  • Two-argument constructor creates an unauthenticated token (for authentication requests).
  • Three-argument constructor creates an authenticated token (for successful authentication results).

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);
}

Anonymous Authentication

AnonymousAuthenticationToken

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");
}

AnonymousAuthenticationProvider

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);

Remember-Me Authentication

RememberMeAuthenticationToken

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
}

RememberMeAuthenticationProvider

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
);

Testing Authentication

TestingAuthenticationToken

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());

TestingAuthenticationProvider

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());
    }
}

JAAS Authentication

JaasAuthenticationToken

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:

  • Takes a 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();

One-Time Token Authentication

OneTimeTokenAuthenticationToken

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);

OneTimeTokenAuthentication

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());

OneTimeTokenAuthenticationProvider

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:

  • Takes 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);

OneTimeTokenReactiveAuthenticationManager

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:

  • Takes reactive versions of token service and user details service.

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();

Pre-Authenticated Tokens

PreAuthenticatedAuthenticationToken

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:

  • Two-argument constructor creates unauthenticated token.
  • Three-argument constructor creates authenticated token with authorities.

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);

Custom Authentication Tokens

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");