1
0
mirror of synced 2026-08-04 17:27:13 +00:00

Add Authentication.Builder

This commit adds a new default method to Authentication
for the purposes of creating a Builder based on the current
authentication, allowing other authentications to be
applied to it as a composite.

It also adds Builders for each one of the authentication
result classes.

Issue gh-17861
This commit is contained in:
Josh Cummings
2025-08-22 16:21:26 -06:00
parent eeb4574bb3
commit a201a2b862
27 changed files with 1016 additions and 1 deletions
@@ -21,6 +21,7 @@ import java.util.Collection;
import org.jspecify.annotations.Nullable;
import org.springframework.security.authentication.AbstractAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
/**
@@ -82,4 +83,46 @@ public class PreAuthenticatedAuthenticationToken extends AbstractAuthenticationT
return this.principal;
}
@Override
public Builder toBuilder() {
return new Builder().apply(this);
}
/**
* A builder preserving the concrete {@link Authentication} type
*
* @since 7.0
*/
public static final class Builder
extends AbstractAuthenticationBuilder<PreAuthenticatedAuthenticationToken, Builder> {
private Object principal;
private Object credentials;
private Builder() {
}
public Builder apply(PreAuthenticatedAuthenticationToken token) {
return super.apply(token).principal(token.getPrincipal()).credentials(token.getCredentials());
}
public Builder principal(Object principal) {
this.principal = principal;
return this;
}
public Builder credentials(Object credentials) {
this.credentials = credentials;
return this;
}
@Override
protected PreAuthenticatedAuthenticationToken build(Collection<GrantedAuthority> authorities) {
return new PreAuthenticatedAuthenticationToken(this.principal, this.credentials, authorities);
}
}
}
@@ -18,6 +18,7 @@ package org.springframework.security.web.authentication.preauth;
import java.util.Collection;
import java.util.List;
import java.util.Set;
import org.junit.jupiter.api.Test;
@@ -73,4 +74,17 @@ public class PreAuthenticatedAuthenticationTokenTests {
.isTrue();
}
@Test
public void toBuilderWhenApplyThenCopies() {
PreAuthenticatedAuthenticationToken factorOne = new PreAuthenticatedAuthenticationToken("alice", "pass",
AuthorityUtils.createAuthorityList("FACTOR_ONE"));
PreAuthenticatedAuthenticationToken factorTwo = new PreAuthenticatedAuthenticationToken("bob", "ssap",
AuthorityUtils.createAuthorityList("FACTOR_TWO"));
PreAuthenticatedAuthenticationToken result = factorOne.toBuilder().apply(factorTwo).build();
Set<String> authorities = AuthorityUtils.authorityListToSet(result.getAuthorities());
assertThat(result.getPrincipal()).isSameAs(factorTwo.getPrincipal());
assertThat(result.getCredentials()).isSameAs(factorTwo.getCredentials());
assertThat(authorities).containsExactlyInAnyOrder("FACTOR_ONE", "FACTOR_TWO");
}
}