ACS-9416 Backport ACS-9414 Enhance the Identity Provider configuration (#3263) (#3341)

This commit is contained in:
Damian Ujma
2025-05-14 14:00:09 +02:00
committed by Gerard Olenski
parent be2860ffdd
commit 7be9ce394d
28 changed files with 3595 additions and 2826 deletions

View File

@@ -145,7 +145,7 @@ jobs:
- uses: Alfresco/alfresco-build-tools/.github/actions/get-build-info@v8.16.0 - uses: Alfresco/alfresco-build-tools/.github/actions/get-build-info@v8.16.0
- uses: Alfresco/alfresco-build-tools/.github/actions/free-hosted-runner-disk-space@v8.16.0 - uses: Alfresco/alfresco-build-tools/.github/actions/free-hosted-runner-disk-space@v8.16.0
- uses: Alfresco/alfresco-build-tools/.github/actions/setup-java-build@v8.16.0 - uses: Alfresco/alfresco-build-tools/.github/actions/setup-java-build@v8.16.0
- uses: Alfresco/ya-pmd-scan@v4.1.0 - uses: Alfresco/ya-pmd-scan@v4.3.0
with: with:
classpath-build-command: "mvn test-compile -ntp -Pags -pl \"-:alfresco-community-repo-docker\"" classpath-build-command: "mvn test-compile -ntp -Pags -pl \"-:alfresco-community-repo-docker\""

View File

@@ -1627,7 +1627,7 @@
"filename": "repository/src/test/java/org/alfresco/repo/security/authentication/identityservice/SpringBasedIdentityServiceFacadeUnitTest.java", "filename": "repository/src/test/java/org/alfresco/repo/security/authentication/identityservice/SpringBasedIdentityServiceFacadeUnitTest.java",
"hashed_secret": "5baa61e4c9b93f3f0682250b6cf8331b7ee68fd8", "hashed_secret": "5baa61e4c9b93f3f0682250b6cf8331b7ee68fd8",
"is_verified": false, "is_verified": false,
"line_number": 46, "line_number": 48,
"is_secret": false "is_secret": false
} }
], ],
@@ -1888,5 +1888,5 @@
} }
] ]
}, },
"generated_at": "2024-10-09T09:32:52Z" "generated_at": "2025-05-13T10:16:00Z"
} }

View File

@@ -25,22 +25,20 @@
*/ */
package org.alfresco.repo.security.authentication.identityservice; package org.alfresco.repo.security.authentication.identityservice;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.alfresco.repo.management.subsystems.ActivateableBean; import org.alfresco.repo.management.subsystems.ActivateableBean;
import org.alfresco.repo.security.authentication.AbstractAuthenticationComponent; import org.alfresco.repo.security.authentication.AbstractAuthenticationComponent;
import org.alfresco.repo.security.authentication.AuthenticationException; import org.alfresco.repo.security.authentication.AuthenticationException;
import org.alfresco.repo.security.authentication.identityservice.IdentityServiceFacade.AuthorizationGrant; import org.alfresco.repo.security.authentication.identityservice.IdentityServiceFacade.AuthorizationGrant;
import org.alfresco.repo.security.authentication.identityservice.IdentityServiceFacade.IdentityServiceFacadeException; import org.alfresco.repo.security.authentication.identityservice.IdentityServiceFacade.IdentityServiceFacadeException;
import org.apache.commons.logging.Log; import org.alfresco.repo.security.authentication.identityservice.user.OIDCUserInfo;
import org.apache.commons.logging.LogFactory;
/** /**
* *
* Authenticates a user against Identity Service (Keycloak/Authorization Server). * Authenticates a user against Identity Service (Keycloak/Authorization Server). {@link IdentityServiceFacade} is used to verify provided user credentials. User is set as the current user if the user credentials are valid. <br>
* {@link IdentityServiceFacade} is used to verify provided user credentials. User is set as the current user if the * The {@link IdentityServiceAuthenticationComponent#identityServiceFacade} can be null in which case this authenticator will just fall through to the next one in the chain.
* user credentials are valid.
* <br>
* The {@link IdentityServiceAuthenticationComponent#identityServiceFacade} can be null in which case this authenticator
* will just fall through to the next one in the chain.
* *
*/ */
public class IdentityServiceAuthenticationComponent extends AbstractAuthenticationComponent implements ActivateableBean public class IdentityServiceAuthenticationComponent extends AbstractAuthenticationComponent implements ActivateableBean
@@ -48,7 +46,7 @@ public class IdentityServiceAuthenticationComponent extends AbstractAuthenticati
private final Log LOGGER = LogFactory.getLog(IdentityServiceAuthenticationComponent.class); private final Log LOGGER = LogFactory.getLog(IdentityServiceAuthenticationComponent.class);
/** client used to authenticate user credentials against Authorization Server **/ /** client used to authenticate user credentials against Authorization Server **/
private IdentityServiceFacade identityServiceFacade; private IdentityServiceFacade identityServiceFacade;
/** enabled flag for the identity service subsystem**/ /** enabled flag for the identity service subsystem **/
private boolean active; private boolean active;
private IdentityServiceJITProvisioningHandler jitProvisioningHandler; private IdentityServiceJITProvisioningHandler jitProvisioningHandler;

View File

@@ -2,7 +2,7 @@
* #%L * #%L
* Alfresco Repository * Alfresco Repository
* %% * %%
* Copyright (C) 2005 - 2024 Alfresco Software Limited * Copyright (C) 2005 - 2025 Alfresco Software Limited
* %% * %%
* This file is part of the Alfresco software. * This file is part of the Alfresco software.
* If the software was purchased under a paid Alfresco license, the terms of * If the software was purchased under a paid Alfresco license, the terms of
@@ -69,6 +69,13 @@ public class IdentityServiceConfig
private boolean clientIdValidationDisabled; private boolean clientIdValidationDisabled;
private String adminConsoleRedirectPath; private String adminConsoleRedirectPath;
private String signatureAlgorithms; private String signatureAlgorithms;
private String adminConsoleScopes;
private String passwordGrantScopes;
private String issuerAttribute;
private String firstNameAttribute;
private String lastNameAttribute;
private String emailAttribute;
private long jwtClockSkewMs;
/** /**
* *
@@ -81,7 +88,8 @@ public class IdentityServiceConfig
/** /**
* *
* @param clientConnectionTimeout Client connection timeout in milliseconds. * @param clientConnectionTimeout
* Client connection timeout in milliseconds.
*/ */
public void setClientConnectionTimeout(int clientConnectionTimeout) public void setClientConnectionTimeout(int clientConnectionTimeout)
{ {
@@ -99,7 +107,8 @@ public class IdentityServiceConfig
/** /**
* *
* @param clientSocketTimeout Client socket timeout in milliseconds. * @param clientSocketTimeout
* Client socket timeout in milliseconds.
*/ */
public void setClientSocketTimeout(int clientSocketTimeout) public void setClientSocketTimeout(int clientSocketTimeout)
{ {
@@ -327,4 +336,78 @@ public class IdentityServiceConfig
{ {
this.signatureAlgorithms = signatureAlgorithms; this.signatureAlgorithms = signatureAlgorithms;
} }
public String getIssuerAttribute()
{
return issuerAttribute;
}
public void setIssuerAttribute(String issuerAttribute)
{
this.issuerAttribute = issuerAttribute;
}
public Set<String> getAdminConsoleScopes()
{
return Stream.of(adminConsoleScopes.split(","))
.map(String::trim)
.collect(Collectors.toUnmodifiableSet());
}
public void setAdminConsoleScopes(String adminConsoleScopes)
{
this.adminConsoleScopes = adminConsoleScopes;
}
public Set<String> getPasswordGrantScopes()
{
return Stream.of(passwordGrantScopes.split(","))
.map(String::trim)
.collect(Collectors.toUnmodifiableSet());
}
public void setPasswordGrantScopes(String passwordGrantScopes)
{
this.passwordGrantScopes = passwordGrantScopes;
}
public void setFirstNameAttribute(String firstNameAttribute)
{
this.firstNameAttribute = firstNameAttribute;
}
public void setLastNameAttribute(String lastNameAttribute)
{
this.lastNameAttribute = lastNameAttribute;
}
public void setEmailAttribute(String emailAttribute)
{
this.emailAttribute = emailAttribute;
}
public void setJwtClockSkewMs(long jwtClockSkewMs)
{
this.jwtClockSkewMs = jwtClockSkewMs;
}
public String getFirstNameAttribute()
{
return firstNameAttribute;
}
public String getLastNameAttribute()
{
return lastNameAttribute;
}
public String getEmailAttribute()
{
return emailAttribute;
}
public long getJwtClockSkewMs()
{
return jwtClockSkewMs;
}
} }

View File

@@ -2,7 +2,7 @@
* #%L * #%L
* Alfresco Repository * Alfresco Repository
* %% * %%
* Copyright (C) 2005 - 2024 Alfresco Software Limited * Copyright (C) 2005 - 2025 Alfresco Software Limited
* %% * %%
* This file is part of the Alfresco software. * This file is part of the Alfresco software.
* If the software was purchased under a paid Alfresco license, the terms of * If the software was purchased under a paid Alfresco license, the terms of
@@ -34,6 +34,9 @@ import java.util.Optional;
import org.springframework.security.oauth2.client.registration.ClientRegistration; import org.springframework.security.oauth2.client.registration.ClientRegistration;
import org.alfresco.repo.security.authentication.identityservice.user.DecodedTokenUser;
import org.alfresco.repo.security.authentication.identityservice.user.UserInfoAttrMapping;
/** /**
* Allows to interact with the Identity Service * Allows to interact with the Identity Service
*/ */
@@ -41,28 +44,36 @@ public interface IdentityServiceFacade
{ {
/** /**
* Returns {@link AccessToken} based authorization for provided {@link AuthorizationGrant}. * Returns {@link AccessToken} based authorization for provided {@link AuthorizationGrant}.
* @param grant the OAuth2 grant provided by the Resource Owner. *
* @param grant
* the OAuth2 grant provided by the Resource Owner.
* @return {@link AccessTokenAuthorization} containing access token and optional refresh token. * @return {@link AccessTokenAuthorization} containing access token and optional refresh token.
* @throws {@link AuthorizationException} when provided grant cannot be exchanged for the access token. * @throws {@link
* AuthorizationException} when provided grant cannot be exchanged for the access token.
*/ */
AccessTokenAuthorization authorize(AuthorizationGrant grant) throws AuthorizationException; AccessTokenAuthorization authorize(AuthorizationGrant grant) throws AuthorizationException;
/** /**
* Decodes the access token into the {@link DecodedAccessToken} which contains claims connected with a given token. * Decodes the access token into the {@link DecodedAccessToken} which contains claims connected with a given token.
* @param token {@link String} with encoded access token value. *
* @param token
* {@link String} with encoded access token value.
* @return {@link DecodedAccessToken} containing decoded claims. * @return {@link DecodedAccessToken} containing decoded claims.
* @throws {@link TokenDecodingException} when token decoding failed. * @throws {@link
* TokenDecodingException} when token decoding failed.
*/ */
DecodedAccessToken decodeToken(String token) throws TokenDecodingException; DecodedAccessToken decodeToken(String token) throws TokenDecodingException;
/** /**
* Gets claims about the authenticated user, * Gets claims about the authenticated user, such as name and email address, via the UserInfo endpoint of the OpenID provider.
* such as name and email address, via the UserInfo endpoint of the OpenID provider. *
* @param token {@link String} with encoded access token value. * @param token
* @param principalAttribute {@link String} the attribute name used to access the user's name from the user info response. * {@link String} with encoded access token value.
* @return {@link OIDCUserInfo} containing user claims. * @param userInfoAttrMapping
* {@link UserInfoAttrMapping} containing the mapping of claims.
* @return {@link DecodedTokenUser} containing user claims or {@link Optional#empty()} if the token does not contain a username claim.
*/ */
Optional<OIDCUserInfo> getUserInfo(String token, String principalAttribute); Optional<DecodedTokenUser> getUserInfo(String token, UserInfoAttrMapping userInfoAttrMapping);
/** /**
* Gets a client registration * Gets a client registration
@@ -129,19 +140,23 @@ public interface IdentityServiceFacade
{ {
/** /**
* Required {@link AccessToken} * Required {@link AccessToken}
*
* @return {@link AccessToken} * @return {@link AccessToken}
*/ */
AccessToken getAccessToken(); AccessToken getAccessToken();
/** /**
* Optional refresh token. * Optional refresh token.
*
* @return Refresh token or {@code null} * @return Refresh token or {@code null}
*/ */
String getRefreshTokenValue(); String getRefreshTokenValue();
} }
interface AccessToken { interface AccessToken
{
String getTokenValue(); String getTokenValue();
Instant getExpiresAt(); Instant getExpiresAt();
} }
@@ -150,7 +165,8 @@ public interface IdentityServiceFacade
Object getClaim(String claim); Object getClaim(String claim);
} }
class AuthorizationGrant { class AuthorizationGrant
{
private final String username; private final String username;
private final String password; private final String password;
private final String refreshToken; private final String refreshToken;

View File

@@ -2,7 +2,7 @@
* #%L * #%L
* Alfresco Repository * Alfresco Repository
* %% * %%
* Copyright (C) 2005 - 2024 Alfresco Software Limited * Copyright (C) 2005 - 2025 Alfresco Software Limited
* %% * %%
* This file is part of the Alfresco software. * This file is part of the Alfresco software.
* If the software was purchased under a paid Alfresco license, the terms of * If the software was purchased under a paid Alfresco license, the terms of
@@ -72,9 +72,8 @@ import com.nimbusds.jwt.proc.ConfigurableJWTProcessor;
import com.nimbusds.oauth2.sdk.Scope; import com.nimbusds.oauth2.sdk.Scope;
import com.nimbusds.oauth2.sdk.id.Identifier; import com.nimbusds.oauth2.sdk.id.Identifier;
import com.nimbusds.oauth2.sdk.id.Issuer; import com.nimbusds.oauth2.sdk.id.Issuer;
import com.nimbusds.openid.connect.sdk.claims.PersonClaims;
import com.nimbusds.openid.connect.sdk.op.OIDCProviderMetadata; import com.nimbusds.openid.connect.sdk.op.OIDCProviderMetadata;
import org.alfresco.repo.security.authentication.identityservice.IdentityServiceFacade.IdentityServiceFacadeException;
import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log; import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
@@ -98,6 +97,7 @@ import org.springframework.http.client.ClientHttpRequest;
import org.springframework.http.client.ClientHttpRequestFactory; import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory; import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.http.converter.FormHttpMessageConverter; import org.springframework.http.converter.FormHttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.security.converter.RsaKeyConverters; import org.springframework.security.converter.RsaKeyConverters;
import org.springframework.security.oauth2.client.http.OAuth2ErrorResponseErrorHandler; import org.springframework.security.oauth2.client.http.OAuth2ErrorResponseErrorHandler;
import org.springframework.security.oauth2.client.oidc.authentication.OidcIdTokenDecoderFactory; import org.springframework.security.oauth2.client.oidc.authentication.OidcIdTokenDecoderFactory;
@@ -125,6 +125,10 @@ import org.springframework.web.client.RestOperations;
import org.springframework.web.client.RestTemplate; import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder; import org.springframework.web.util.UriComponentsBuilder;
import org.alfresco.repo.security.authentication.identityservice.IdentityServiceFacade.IdentityServiceFacadeException;
import org.alfresco.repo.security.authentication.identityservice.user.DecodedTokenUser;
import org.alfresco.repo.security.authentication.identityservice.user.UserInfoAttrMapping;
/** /**
* Creates an instance of {@link IdentityServiceFacade}. <br> * Creates an instance of {@link IdentityServiceFacade}. <br>
* This factory can return a null if it is disabled. * This factory can return a null if it is disabled.
@@ -134,6 +138,7 @@ public class IdentityServiceFacadeFactoryBean implements FactoryBean<IdentitySer
private static final Log LOGGER = LogFactory.getLog(IdentityServiceFacadeFactoryBean.class); private static final Log LOGGER = LogFactory.getLog(IdentityServiceFacadeFactoryBean.class);
private static final JOSEObjectType AT_JWT = new JOSEObjectType("at+jwt"); private static final JOSEObjectType AT_JWT = new JOSEObjectType("at+jwt");
private static final String DEFAULT_ISSUER_ATTR = "issuer";
private boolean enabled; private boolean enabled;
private SpringBasedIdentityServiceFacadeFactory factory; private SpringBasedIdentityServiceFacadeFactory factory;
@@ -148,8 +153,7 @@ public class IdentityServiceFacadeFactoryBean implements FactoryBean<IdentitySer
factory = new SpringBasedIdentityServiceFacadeFactory( factory = new SpringBasedIdentityServiceFacadeFactory(
new HttpClientProvider(identityServiceConfig)::createHttpClient, new HttpClientProvider(identityServiceConfig)::createHttpClient,
new ClientRegistrationProvider(identityServiceConfig)::createClientRegistration, new ClientRegistrationProvider(identityServiceConfig)::createClientRegistration,
new JwtDecoderProvider(identityServiceConfig)::createJwtDecoder new JwtDecoderProvider(identityServiceConfig)::createJwtDecoder);
);
} }
@Override @Override
@@ -207,9 +211,9 @@ public class IdentityServiceFacadeFactoryBean implements FactoryBean<IdentitySer
} }
@Override @Override
public Optional<OIDCUserInfo> getUserInfo(String token, String principalAttribute) public Optional<DecodedTokenUser> getUserInfo(String token, UserInfoAttrMapping userInfoAttrMapping)
{ {
return getTargetFacade().getUserInfo(token, principalAttribute); return getTargetFacade().getUserInfo(token, userInfoAttrMapping);
} }
@Override @Override
@@ -221,8 +225,7 @@ public class IdentityServiceFacadeFactoryBean implements FactoryBean<IdentitySer
private IdentityServiceFacade getTargetFacade() private IdentityServiceFacade getTargetFacade()
{ {
return ofNullable(targetFacade.get()) return ofNullable(targetFacade.get())
.orElseGet(() -> targetFacade.updateAndGet(prev -> .orElseGet(() -> targetFacade.updateAndGet(prev -> ofNullable(prev).orElseGet(this::createTargetFacade)));
ofNullable(prev).orElseGet(this::createTargetFacade)));
} }
private IdentityServiceFacade createTargetFacade() private IdentityServiceFacade createTargetFacade()
@@ -261,7 +264,7 @@ public class IdentityServiceFacadeFactoryBean implements FactoryBean<IdentitySer
private IdentityServiceFacade createIdentityServiceFacade() private IdentityServiceFacade createIdentityServiceFacade()
{ {
//Here we preserve the behaviour of previously used Keycloak Adapter // Here we preserve the behaviour of previously used Keycloak Adapter
// * Client is authenticating itself using basic auth // * Client is authenticating itself using basic auth
// * Resource Owner Password Credentials Flow is used to authenticate Resource Owner // * Resource Owner Password Credentials Flow is used to authenticate Resource Owner
@@ -279,7 +282,7 @@ public class IdentityServiceFacadeFactoryBean implements FactoryBean<IdentitySer
private RestTemplate createOAuth2RestTemplate(ClientHttpRequestFactory requestFactory) private RestTemplate createOAuth2RestTemplate(ClientHttpRequestFactory requestFactory)
{ {
final RestTemplate restTemplate = new RestTemplate( final RestTemplate restTemplate = new RestTemplate(
Arrays.asList(new FormHttpMessageConverter(), new OAuth2AccessTokenResponseHttpMessageConverter())); Arrays.asList(new FormHttpMessageConverter(), new OAuth2AccessTokenResponseHttpMessageConverter(), new MappingJackson2HttpMessageConverter()));
restTemplate.setRequestFactory(requestFactory); restTemplate.setRequestFactory(requestFactory);
restTemplate.setErrorHandler(new OAuth2ErrorResponseErrorHandler()); restTemplate.setErrorHandler(new OAuth2ErrorResponseErrorHandler());
@@ -387,8 +390,6 @@ public class IdentityServiceFacadeFactoryBean implements FactoryBean<IdentitySer
{ {
private final IdentityServiceConfig config; private final IdentityServiceConfig config;
private static final Set<String> SCOPES = Set.of("openid", "profile", "email");
ClientRegistrationProvider(IdentityServiceConfig config) ClientRegistrationProvider(IdentityServiceConfig config)
{ {
this.config = requireNonNull(config); this.config = requireNonNull(config);
@@ -458,12 +459,11 @@ public class IdentityServiceFacadeFactoryBean implements FactoryBean<IdentitySer
.map(URI::toASCIIString) .map(URI::toASCIIString)
.orElse(null); .orElse(null);
final String issuerUri = Optional.of(metadata) Optional<String> metadataIssuer = getMetadataIssuer(metadata, config);
.map(OIDCProviderMetadata::getIssuer) final String issuerUri = metadataIssuer
.map(Issuer::getValue) .orElseGet(() -> (StringUtils.isNotBlank(config.getRealm()) && StringUtils.isBlank(config.getIssuerUrl())) ? config.getAuthServerUrl() : config.getIssuerUrl());
.orElseGet(() -> (StringUtils.isNotBlank(config.getRealm()) && StringUtils.isBlank(config.getIssuerUrl())) ?
config.getAuthServerUrl() : final String usernameAttribute = StringUtils.isNotBlank(config.getPrincipalAttribute()) ? config.getPrincipalAttribute() : PersonClaims.PREFERRED_USERNAME_CLAIM_NAME;
config.getIssuerUrl());
return ClientRegistration return ClientRegistration
.withRegistrationId("ids") .withRegistrationId("ids")
@@ -472,6 +472,7 @@ public class IdentityServiceFacadeFactoryBean implements FactoryBean<IdentitySer
.jwkSetUri(metadata.getJWKSetURI().toASCIIString()) .jwkSetUri(metadata.getJWKSetURI().toASCIIString())
.issuerUri(issuerUri) .issuerUri(issuerUri)
.userInfoUri(metadata.getUserInfoEndpointURI().toASCIIString()) .userInfoUri(metadata.getUserInfoEndpointURI().toASCIIString())
.userNameAttributeName(usernameAttribute)
.scope(getSupportedScopes(metadata.getScopes())) .scope(getSupportedScopes(metadata.getScopes()))
.providerConfigurationMetadata(createMetadata(metadata)) .providerConfigurationMetadata(createMetadata(metadata))
.authorizationGrantType(AuthorizationGrantType.PASSWORD); .authorizationGrantType(AuthorizationGrantType.PASSWORD);
@@ -480,11 +481,11 @@ public class IdentityServiceFacadeFactoryBean implements FactoryBean<IdentitySer
private Map<String, Object> createMetadata(OIDCProviderMetadata metadata) private Map<String, Object> createMetadata(OIDCProviderMetadata metadata)
{ {
Map<String, Object> configurationMetadata = new LinkedHashMap<>(); Map<String, Object> configurationMetadata = new LinkedHashMap<>();
if(metadata.getScopes() != null) if (metadata.getScopes() != null)
{ {
configurationMetadata.put(SCOPES_SUPPORTED.getValue(), metadata.getScopes()); configurationMetadata.put(SCOPES_SUPPORTED.getValue(), metadata.getScopes());
} }
if(StringUtils.isNotBlank(config.getAudience())) if (StringUtils.isNotBlank(config.getAudience()))
{ {
configurationMetadata.put(AUDIENCE.getValue(), config.getAudience()); configurationMetadata.put(AUDIENCE.getValue(), config.getAudience());
} }
@@ -505,11 +506,17 @@ public class IdentityServiceFacadeFactoryBean implements FactoryBean<IdentitySer
private Set<String> getSupportedScopes(Scope scopes) private Set<String> getSupportedScopes(Scope scopes)
{ {
return scopes.stream().filter(scope -> SCOPES.contains(scope.getValue())) return scopes.stream()
.filter(this::hasPasswordGrantScope)
.map(Identifier::getValue) .map(Identifier::getValue)
.collect(Collectors.toSet()); .collect(Collectors.toSet());
} }
private boolean hasPasswordGrantScope(Scope.Value scope)
{
return config.getPasswordGrantScopes().contains(scope.getValue());
}
private Optional<OIDCProviderMetadata> extractMetadata(RestOperations rest, URI metadataUri) private Optional<OIDCProviderMetadata> extractMetadata(RestOperations rest, URI metadataUri)
{ {
final String response; final String response;
@@ -548,9 +555,7 @@ public class IdentityServiceFacadeFactoryBean implements FactoryBean<IdentitySer
"Failed to create ClientRegistration. The values of issuer url and auth server url cannot both be empty."); "Failed to create ClientRegistration. The values of issuer url and auth server url cannot both be empty.");
} }
String baseUrl = StringUtils.isNotBlank(config.getAuthServerUrl()) ? String baseUrl = StringUtils.isNotBlank(config.getAuthServerUrl()) ? config.getAuthServerUrl() : config.getIssuerUrl();
config.getAuthServerUrl() :
config.getIssuerUrl();
return List.of(UriComponentsBuilder.fromUriString(baseUrl) return List.of(UriComponentsBuilder.fromUriString(baseUrl)
.pathSegment(".well-known", "openid-configuration") .pathSegment(".well-known", "openid-configuration")
@@ -558,6 +563,18 @@ public class IdentityServiceFacadeFactoryBean implements FactoryBean<IdentitySer
} }
} }
private static Optional<String> getMetadataIssuer(OIDCProviderMetadata metadata, IdentityServiceConfig config)
{
return DEFAULT_ISSUER_ATTR.equals(config.getIssuerAttribute()) ? Optional.of(metadata)
.map(OIDCProviderMetadata::getIssuer)
.map(Issuer::getValue)
: Optional.of(metadata)
.map(OIDCProviderMetadata::getCustomParameters)
.map(map -> map.get(config.getIssuerAttribute()))
.filter(String.class::isInstance)
.map(String.class::cast);
}
static class JwtDecoderProvider static class JwtDecoderProvider
{ {
private static final SignatureAlgorithm DEFAULT_SIGNATURE_ALGORITHM = SignatureAlgorithm.RS256; private static final SignatureAlgorithm DEFAULT_SIGNATURE_ALGORITHM = SignatureAlgorithm.RS256;
@@ -657,7 +674,7 @@ public class IdentityServiceFacadeFactoryBean implements FactoryBean<IdentitySer
private OAuth2TokenValidator<Jwt> createJwtTokenValidator(ProviderDetails providerDetails) private OAuth2TokenValidator<Jwt> createJwtTokenValidator(ProviderDetails providerDetails)
{ {
List<OAuth2TokenValidator<Jwt>> validators = new ArrayList<>(); List<OAuth2TokenValidator<Jwt>> validators = new ArrayList<>();
validators.add(new JwtTimestampValidator(Duration.of(0, ChronoUnit.MILLIS))); validators.add(new JwtTimestampValidator(Duration.of(config.getJwtClockSkewMs(), ChronoUnit.MILLIS)));
validators.add(new JwtIssuerValidator(providerDetails.getIssuerUri())); validators.add(new JwtIssuerValidator(providerDetails.getIssuerUri()));
if (!config.isClientIdValidationDisabled()) if (!config.isClientIdValidationDisabled())
{ {
@@ -680,7 +697,7 @@ public class IdentityServiceFacadeFactoryBean implements FactoryBean<IdentitySer
{ {
if (isPemFormatException(e)) if (isPemFormatException(e))
{ {
//For backward compatibility with Keycloak adapter // For backward compatibility with Keycloak adapter
return tryToParsePublicKey("-----BEGIN PUBLIC KEY-----\n" + pem + "\n-----END PUBLIC KEY-----"); return tryToParsePublicKey("-----BEGIN PUBLIC KEY-----\n" + pem + "\n-----END PUBLIC KEY-----");
} }
throw e; throw e;
@@ -758,11 +775,11 @@ public class IdentityServiceFacadeFactoryBean implements FactoryBean<IdentitySer
final Object audience = token.getClaim(JwtClaimNames.AUD); final Object audience = token.getClaim(JwtClaimNames.AUD);
if (audience != null) if (audience != null)
{ {
if(audience instanceof List && ((List<String>) audience).contains(configuredAudience)) if (audience instanceof List && ((List<String>) audience).contains(configuredAudience))
{ {
return OAuth2TokenValidatorResult.success(); return OAuth2TokenValidatorResult.success();
} }
if(audience instanceof String && audience.equals(configuredAudience)) if (audience instanceof String && audience.equals(configuredAudience))
{ {
return OAuth2TokenValidatorResult.success(); return OAuth2TokenValidatorResult.success();
} }
@@ -786,10 +803,7 @@ public class IdentityServiceFacadeFactoryBean implements FactoryBean<IdentitySer
@Override @Override
public ClientHttpRequest createRequest(URI uri, HttpMethod httpMethod) throws IOException public ClientHttpRequest createRequest(URI uri, HttpMethod httpMethod) throws IOException
{ {
/* /* This is to avoid the Brotli content encoding that is not well-supported by the combination of the Apache Http Client and the Spring RestTemplate */
* This is to avoid the Brotli content encoding that is not well-supported by the combination of
* the Apache Http Client and the Spring RestTemplate
*/
ClientHttpRequest request = super.createRequest(uri, httpMethod); ClientHttpRequest request = super.createRequest(uri, httpMethod);
request.getHeaders() request.getHeaders()
.add("Accept-Encoding", "gzip, deflate"); .add("Accept-Encoding", "gzip, deflate");

View File

@@ -2,7 +2,7 @@
* #%L * #%L
* Alfresco Repository * Alfresco Repository
* %% * %%
* Copyright (C) 2005 - 2024 Alfresco Software Limited * Copyright (C) 2005 - 2025 Alfresco Software Limited
* %% * %%
* This file is part of the Alfresco software. * This file is part of the Alfresco software.
* If the software was purchased under a paid Alfresco license, the terms of * If the software was purchased under a paid Alfresco license, the terms of
@@ -30,54 +30,33 @@ import java.io.Serializable;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
import java.util.Optional; import java.util.Optional;
import java.util.function.BiFunction;
import java.util.function.Predicate; import java.util.function.Predicate;
import com.nimbusds.openid.connect.sdk.claims.PersonClaims; import org.apache.commons.lang3.StringUtils;
import com.nimbusds.openid.connect.sdk.claims.UserInfo;
import org.alfresco.model.ContentModel; import org.alfresco.model.ContentModel;
import org.alfresco.repo.security.authentication.AuthenticationUtil; import org.alfresco.repo.security.authentication.AuthenticationUtil;
import org.alfresco.repo.security.authentication.identityservice.IdentityServiceFacade.DecodedAccessToken; import org.alfresco.repo.security.authentication.identityservice.user.AccessTokenToDecodedTokenUserMapper;
import org.alfresco.repo.security.authentication.identityservice.user.DecodedTokenUser;
import org.alfresco.repo.security.authentication.identityservice.user.OIDCUserInfo;
import org.alfresco.repo.security.authentication.identityservice.user.TokenUserToOIDCUserMapper;
import org.alfresco.repo.security.authentication.identityservice.user.UserInfoAttrMapping;
import org.alfresco.service.cmr.security.PersonService; import org.alfresco.service.cmr.security.PersonService;
import org.alfresco.service.namespace.QName; import org.alfresco.service.namespace.QName;
import org.alfresco.service.transaction.TransactionService; import org.alfresco.service.transaction.TransactionService;
import org.apache.commons.lang3.StringUtils;
/** /**
* This class handles Just in Time user provisioning. It extracts {@link OIDCUserInfo} * This class handles Just in Time user provisioning. It extracts {@link OIDCUserInfo} from the given bearer token and creates a new user if it does not exist in the repository.
* from {@link IdentityServiceFacade.DecodedAccessToken} or {@link UserInfo}
* and creates a new user if it does not exist in the repository.
*/ */
public class IdentityServiceJITProvisioningHandler public class IdentityServiceJITProvisioningHandler
{ {
private final IdentityServiceConfig identityServiceConfig;
private final IdentityServiceFacade identityServiceFacade; private final IdentityServiceFacade identityServiceFacade;
private final PersonService personService; private final PersonService personService;
private final TransactionService transactionService; private final TransactionService transactionService;
private final IdentityServiceConfig identityServiceConfig;
private final BiFunction<DecodedAccessToken, String, Optional<? extends OIDCUserInfo>> mapTokenToUserInfoResponse = (token, usernameMappingClaim) -> { private UserInfoAttrMapping userInfoAttrMapping;
Optional<String> firstName = Optional.ofNullable(token) private TokenUserToOIDCUserMapper tokenUserToOIDCUserMapper;
.map(jwtToken -> jwtToken.getClaim(PersonClaims.GIVEN_NAME_CLAIM_NAME)) private AccessTokenToDecodedTokenUserMapper tokenToDecodedTokenUserMapper;
.filter(String.class::isInstance)
.map(String.class::cast);
Optional<String> lastName = Optional.ofNullable(token)
.map(jwtToken -> jwtToken.getClaim(PersonClaims.FAMILY_NAME_CLAIM_NAME))
.filter(String.class::isInstance)
.map(String.class::cast);
Optional<String> email = Optional.ofNullable(token)
.map(jwtToken -> jwtToken.getClaim(PersonClaims.EMAIL_CLAIM_NAME))
.filter(String.class::isInstance)
.map(String.class::cast);
return Optional.ofNullable(token.getClaim(Optional.ofNullable(usernameMappingClaim)
.filter(StringUtils::isNotBlank)
.orElse(PersonClaims.PREFERRED_USERNAME_CLAIM_NAME)))
.filter(String.class::isInstance)
.map(String.class::cast)
.map(this::normalizeUserId)
.map(username -> new OIDCUserInfo(username, firstName.orElse(""), lastName.orElse(""), email.orElse("")));
};
public IdentityServiceJITProvisioningHandler(IdentityServiceFacade identityServiceFacade, public IdentityServiceJITProvisioningHandler(IdentityServiceFacade identityServiceFacade,
PersonService personService, PersonService personService,
@@ -90,32 +69,77 @@ public class IdentityServiceJITProvisioningHandler
this.identityServiceConfig = identityServiceConfig; this.identityServiceConfig = identityServiceConfig;
} }
/**
* Extracts {@link OIDCUserInfo} from the given bearer token and creates a new user if it does not exist in the repository. Call to the UserInfo endpoint is made only if the token does not contain a username claim or if user needs to be created and some of the {@link OIDCUserInfo} fields are empty.
*/
public Optional<OIDCUserInfo> extractUserInfoAndCreateUserIfNeeded(String bearerToken) public Optional<OIDCUserInfo> extractUserInfoAndCreateUserIfNeeded(String bearerToken)
{ {
Optional<OIDCUserInfo> userInfoResponse = Optional.ofNullable(bearerToken) if (userInfoAttrMapping == null)
.filter(Predicate.not(String::isEmpty))
.flatMap(token -> extractUserInfoResponseFromAccessToken(token)
.filter(userInfo -> StringUtils.isNotEmpty(userInfo.username()))
.or(() -> extractUserInfoResponseFromEndpoint(token)));
if (transactionService.isReadOnly() || userInfoResponse.isEmpty())
{ {
return userInfoResponse; initMappers(identityServiceConfig);
} }
return AuthenticationUtil.runAs(new AuthenticationUtil.RunAsWork<Optional<OIDCUserInfo>>()
Optional<OIDCUserInfo> oidcUserInfo = Optional.ofNullable(bearerToken)
.filter(Predicate.not(String::isEmpty))
.flatMap(token -> extractUserInfoResponseFromAccessToken(token).filter(decodedTokenUser -> StringUtils.isNotEmpty(decodedTokenUser.username()))
.or(() -> extractUserInfoResponseFromEndpoint(token, userInfoAttrMapping)))
.map(tokenUserToOIDCUserMapper::toOIDCUser);
if (transactionService.isReadOnly() || oidcUserInfo.isEmpty())
{ {
return oidcUserInfo;
}
return AuthenticationUtil.runAs(new AuthenticationUtil.RunAsWork<Optional<OIDCUserInfo>>() {
@Override @Override
public Optional<OIDCUserInfo> doWork() throws Exception public Optional<OIDCUserInfo> doWork() throws Exception
{ {
return userInfoResponse.map(userInfo -> { return oidcUserInfo.map(oidcUser -> {
if (userInfo.username() != null && personService.createMissingPeople() if (userDoesNotExistsAndCanBeCreated(oidcUser))
&& !personService.personExists(userInfo.username()))
{ {
if (!userInfo.allFieldsNotEmpty()) if (!oidcUser.allFieldsNotEmpty())
{ {
userInfo = extractUserInfoResponseFromEndpoint(bearerToken).orElse(userInfo); oidcUser = extractUserInfoResponseFromEndpoint(bearerToken, userInfoAttrMapping)
.map(tokenUserToOIDCUserMapper::toOIDCUser)
.orElse(oidcUser);
} }
createPerson(oidcUser);
}
return oidcUser;
});
}
}, AuthenticationUtil.getSystemUserName());
}
private void initMappers(IdentityServiceConfig identityServiceConfig)
{
this.userInfoAttrMapping = initUserInfoAttrMapping(identityServiceConfig);
this.tokenUserToOIDCUserMapper = new TokenUserToOIDCUserMapper(personService);
this.tokenToDecodedTokenUserMapper = new AccessTokenToDecodedTokenUserMapper(userInfoAttrMapping);
}
private boolean userDoesNotExistsAndCanBeCreated(OIDCUserInfo userInfo)
{
return userInfo.username() != null && personService.createMissingPeople()
&& !personService.personExists(userInfo.username());
}
private Optional<DecodedTokenUser> extractUserInfoResponseFromAccessToken(String bearerToken)
{
return Optional.ofNullable(bearerToken)
.map(identityServiceFacade::decodeToken)
.flatMap(tokenToDecodedTokenUserMapper::toDecodedTokenUser);
}
private Optional<DecodedTokenUser> extractUserInfoResponseFromEndpoint(String bearerToken, UserInfoAttrMapping userInfoAttrMapping)
{
return identityServiceFacade.getUserInfo(bearerToken, userInfoAttrMapping)
.filter(userInfo -> userInfo.username() != null && !userInfo.username().isEmpty());
}
private void createPerson(OIDCUserInfo userInfo)
{
Map<QName, Serializable> properties = new HashMap<>(); Map<QName, Serializable> properties = new HashMap<>();
properties.put(ContentModel.PROP_USERNAME, userInfo.username()); properties.put(ContentModel.PROP_USERNAME, userInfo.username());
properties.put(ContentModel.PROP_FIRSTNAME, userInfo.firstName()); properties.put(ContentModel.PROP_FIRSTNAME, userInfo.firstName());
@@ -123,61 +147,17 @@ public class IdentityServiceJITProvisioningHandler
properties.put(ContentModel.PROP_EMAIL, userInfo.email()); properties.put(ContentModel.PROP_EMAIL, userInfo.email());
properties.put(ContentModel.PROP_ORGID, ""); properties.put(ContentModel.PROP_ORGID, "");
properties.put(ContentModel.PROP_HOME_FOLDER_PROVIDER, null); properties.put(ContentModel.PROP_HOME_FOLDER_PROVIDER, null);
properties.put(ContentModel.PROP_SIZE_CURRENT, 0L); properties.put(ContentModel.PROP_SIZE_CURRENT, 0L);
properties.put(ContentModel.PROP_SIZE_QUOTA, -1L); // no quota properties.put(ContentModel.PROP_SIZE_QUOTA, -1L); // no quota
personService.createPerson(properties); personService.createPerson(properties);
} }
return userInfo;
});
}
}, AuthenticationUtil.getSystemUserName());
}
private Optional<OIDCUserInfo> extractUserInfoResponseFromAccessToken(String bearerToken) private UserInfoAttrMapping initUserInfoAttrMapping(IdentityServiceConfig identityServiceConfig)
{ {
return Optional.ofNullable(bearerToken) return new UserInfoAttrMapping(identityServiceFacade.getClientRegistration().getProviderDetails().getUserInfoEndpoint().getUserNameAttributeName(),
.map(identityServiceFacade::decodeToken) identityServiceConfig.getFirstNameAttribute(),
.flatMap(decodedToken -> mapTokenToUserInfoResponse.apply(decodedToken, identityServiceConfig.getLastNameAttribute(),
identityServiceConfig.getPrincipalAttribute())); identityServiceConfig.getEmailAttribute());
} }
private Optional<OIDCUserInfo> extractUserInfoResponseFromEndpoint(String bearerToken)
{
return identityServiceFacade.getUserInfo(bearerToken,
StringUtils.isNotBlank(identityServiceConfig.getPrincipalAttribute()) ?
identityServiceConfig.getPrincipalAttribute() : PersonClaims.PREFERRED_USERNAME_CLAIM_NAME)
.filter(userInfo -> userInfo.username() != null && !userInfo.username().isEmpty())
.map(userInfo -> new OIDCUserInfo(normalizeUserId(userInfo.username()),
Optional.ofNullable(userInfo.firstName()).orElse(""),
Optional.ofNullable(userInfo.lastName()).orElse(""),
Optional.ofNullable(userInfo.email()).orElse("")));
}
/**
* Normalizes a user id, taking into account existing user accounts and case sensitivity settings.
*
* @param userId the user id
* @return the string
*/
private String normalizeUserId(final String userId)
{
if (userId == null)
{
return null;
}
String normalized = AuthenticationUtil.runAs(new AuthenticationUtil.RunAsWork<String>()
{
@Override
public String doWork() throws Exception
{
return personService.getUserIdentifier(userId);
}
}, AuthenticationUtil.getSystemUserName());
return normalized == null ? userId : normalized;
}
} }

View File

@@ -2,7 +2,7 @@
* #%L * #%L
* Alfresco Repository * Alfresco Repository
* %% * %%
* Copyright (C) 2005 - 2023 Alfresco Software Limited * Copyright (C) 2005 - 2025 Alfresco Software Limited
* %% * %%
* This file is part of the Alfresco software. * This file is part of the Alfresco software.
* If the software was purchased under a paid Alfresco license, the terms of * If the software was purchased under a paid Alfresco license, the terms of
@@ -25,23 +25,23 @@
*/ */
package org.alfresco.repo.security.authentication.identityservice; package org.alfresco.repo.security.authentication.identityservice;
import java.util.Optional;
import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletRequest;
import java.util.Optional; import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.security.oauth2.core.OAuth2AuthenticationException;
import org.springframework.security.oauth2.server.resource.web.BearerTokenResolver;
import org.alfresco.repo.management.subsystems.ActivateableBean; import org.alfresco.repo.management.subsystems.ActivateableBean;
import org.alfresco.repo.security.authentication.AuthenticationException; import org.alfresco.repo.security.authentication.AuthenticationException;
import org.alfresco.repo.security.authentication.AuthenticationUtil; import org.alfresco.repo.security.authentication.AuthenticationUtil;
import org.alfresco.repo.security.authentication.external.RemoteUserMapper; import org.alfresco.repo.security.authentication.external.RemoteUserMapper;
import org.alfresco.repo.security.authentication.identityservice.IdentityServiceFacade.IdentityServiceFacadeException; import org.alfresco.repo.security.authentication.identityservice.IdentityServiceFacade.IdentityServiceFacadeException;
import org.apache.commons.logging.Log; import org.alfresco.repo.security.authentication.identityservice.user.OIDCUserInfo;
import org.apache.commons.logging.LogFactory;
import org.springframework.security.oauth2.core.OAuth2AuthenticationException;
import org.springframework.security.oauth2.server.resource.web.BearerTokenResolver;
/** /**
* A {@link RemoteUserMapper} implementation that detects and validates JWTs * A {@link RemoteUserMapper} implementation that detects and validates JWTs issued by the Alfresco Identity Service.
* issued by the Alfresco Identity Service.
* *
* @author Gavin Cornwell * @author Gavin Cornwell
*/ */
@@ -62,7 +62,8 @@ public class IdentityServiceRemoteUserMapper implements RemoteUserMapper, Activa
/** /**
* Sets the active flag * Sets the active flag
* *
* @param isEnabled true to enable the subsystem * @param isEnabled
* true to enable the subsystem
*/ */
public void setActive(boolean isEnabled) public void setActive(boolean isEnabled)
{ {
@@ -72,7 +73,8 @@ public class IdentityServiceRemoteUserMapper implements RemoteUserMapper, Activa
/** /**
* Determines whether token validation failures are silent * Determines whether token validation failures are silent
* *
* @param silent true to silently fail, false to throw an exception * @param silent
* true to silently fail, false to throw an exception
*/ */
public void setValidationFailureSilent(boolean silent) public void setValidationFailureSilent(boolean silent)
{ {
@@ -89,10 +91,9 @@ public class IdentityServiceRemoteUserMapper implements RemoteUserMapper, Activa
this.jitProvisioningHandler = jitProvisioningHandler; this.jitProvisioningHandler = jitProvisioningHandler;
} }
/* /* (non-Javadoc)
* (non-Javadoc) *
* @see org.alfresco.web.app.servlet.RemoteUserMapper#getRemoteUser(jakarta.servlet.http.HttpServletRequest) * @see org.alfresco.web.app.servlet.RemoteUserMapper#getRemoteUser(jakarta.servlet.http.HttpServletRequest) */
*/
@Override @Override
public String getRemoteUser(HttpServletRequest request) public String getRemoteUser(HttpServletRequest request)
{ {
@@ -107,7 +108,6 @@ public class IdentityServiceRemoteUserMapper implements RemoteUserMapper, Activa
{ {
String normalizedUserId = extractUserFromHeader(request); String normalizedUserId = extractUserFromHeader(request);
if (normalizedUserId != null) if (normalizedUserId != null)
{ {
// Normalize the user ID taking into account case sensitivity settings // Normalize the user ID taking into account case sensitivity settings
@@ -131,10 +131,9 @@ public class IdentityServiceRemoteUserMapper implements RemoteUserMapper, Activa
return null; return null;
} }
/* /* (non-Javadoc)
* (non-Javadoc) *
* @see org.alfresco.repo.management.subsystems.ActivateableBean#isActive() * @see org.alfresco.repo.management.subsystems.ActivateableBean#isActive() */
*/
public boolean isActive() public boolean isActive()
{ {
return this.isEnabled; return this.isEnabled;
@@ -143,7 +142,8 @@ public class IdentityServiceRemoteUserMapper implements RemoteUserMapper, Activa
/** /**
* Extracts the user name from the JWT in the given request. * Extracts the user name from the JWT in the given request.
* *
* @param request The request containing the JWT * @param request
* The request containing the JWT
* @return The username or null if it can not be determined * @return The username or null if it can not be determined
*/ */
private String extractUserFromHeader(HttpServletRequest request) private String extractUserFromHeader(HttpServletRequest request)

View File

@@ -2,7 +2,7 @@
* #%L * #%L
* Alfresco Repository * Alfresco Repository
* %% * %%
* Copyright (C) 2005 - 2024 Alfresco Software Limited * Copyright (C) 2005 - 2025 Alfresco Software Limited
* %% * %%
* This file is part of the Alfresco software. * This file is part of the Alfresco software.
* If the software was purchased under a paid Alfresco license, the terms of * If the software was purchased under a paid Alfresco license, the terms of
@@ -30,20 +30,12 @@ import static java.util.Objects.requireNonNull;
import static org.alfresco.repo.security.authentication.identityservice.IdentityServiceMetadataKey.AUDIENCE; import static org.alfresco.repo.security.authentication.identityservice.IdentityServiceMetadataKey.AUDIENCE;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.time.Instant; import java.time.Instant;
import java.util.Map; import java.util.Map;
import java.util.Optional; import java.util.Optional;
import java.util.function.Predicate;
import com.nimbusds.oauth2.sdk.ParseException;
import com.nimbusds.oauth2.sdk.token.BearerAccessToken;
import com.nimbusds.openid.connect.sdk.UserInfoRequest;
import com.nimbusds.openid.connect.sdk.UserInfoResponse;
import com.nimbusds.openid.connect.sdk.UserInfoSuccessResponse;
import com.nimbusds.openid.connect.sdk.claims.PersonClaims;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log; import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
import org.springframework.core.convert.converter.Converter; import org.springframework.core.convert.converter.Converter;
@@ -58,27 +50,35 @@ import org.springframework.security.oauth2.client.endpoint.OAuth2PasswordGrantRe
import org.springframework.security.oauth2.client.endpoint.OAuth2RefreshTokenGrantRequest; import org.springframework.security.oauth2.client.endpoint.OAuth2RefreshTokenGrantRequest;
import org.springframework.security.oauth2.client.registration.ClientRegistration; import org.springframework.security.oauth2.client.registration.ClientRegistration;
import org.springframework.security.oauth2.client.registration.ClientRegistration.ProviderDetails; import org.springframework.security.oauth2.client.registration.ClientRegistration.ProviderDetails;
import org.springframework.security.oauth2.client.userinfo.DefaultOAuth2UserService;
import org.springframework.security.oauth2.client.userinfo.OAuth2UserRequest;
import org.springframework.security.oauth2.core.AbstractOAuth2Token; import org.springframework.security.oauth2.core.AbstractOAuth2Token;
import org.springframework.security.oauth2.core.AuthorizationGrantType; import org.springframework.security.oauth2.core.AuthorizationGrantType;
import org.springframework.security.oauth2.core.OAuth2AccessToken; import org.springframework.security.oauth2.core.OAuth2AccessToken;
import org.springframework.security.oauth2.core.OAuth2AccessToken.TokenType; import org.springframework.security.oauth2.core.OAuth2AccessToken.TokenType;
import org.springframework.security.oauth2.core.OAuth2AuthenticationException;
import org.springframework.security.oauth2.core.OAuth2AuthorizationException; import org.springframework.security.oauth2.core.OAuth2AuthorizationException;
import org.springframework.security.oauth2.core.OAuth2RefreshToken; import org.springframework.security.oauth2.core.OAuth2RefreshToken;
import org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse; import org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse;
import org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationExchange; import org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationExchange;
import org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest; import org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest;
import org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationResponse; import org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationResponse;
import org.springframework.security.oauth2.core.user.OAuth2User;
import org.springframework.security.oauth2.jwt.Jwt; import org.springframework.security.oauth2.jwt.Jwt;
import org.springframework.security.oauth2.jwt.JwtDecoder; import org.springframework.security.oauth2.jwt.JwtDecoder;
import org.springframework.util.LinkedMultiValueMap; import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap; import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestOperations; import org.springframework.web.client.RestOperations;
import org.alfresco.repo.security.authentication.identityservice.user.DecodedTokenUser;
import org.alfresco.repo.security.authentication.identityservice.user.UserInfoAttrMapping;
class SpringBasedIdentityServiceFacade implements IdentityServiceFacade class SpringBasedIdentityServiceFacade implements IdentityServiceFacade
{ {
private static final Log LOGGER = LogFactory.getLog(SpringBasedIdentityServiceFacade.class); private static final Log LOGGER = LogFactory.getLog(SpringBasedIdentityServiceFacade.class);
private static final Instant SOME_INSIGNIFICANT_DATE_IN_THE_PAST = Instant.MIN.plusSeconds(12345); private static final Instant SOME_INSIGNIFICANT_DATE_IN_THE_PAST = Instant.MIN.plusSeconds(12345);
private final Map<AuthorizationGrantType, OAuth2AccessTokenResponseClient> clients; private final Map<AuthorizationGrantType, OAuth2AccessTokenResponseClient> clients;
private final DefaultOAuth2UserService defaultOAuth2UserService;
private final ClientRegistration clientRegistration; private final ClientRegistration clientRegistration;
private final JwtDecoder jwtDecoder; private final JwtDecoder jwtDecoder;
@@ -92,6 +92,7 @@ class SpringBasedIdentityServiceFacade implements IdentityServiceFacade
AuthorizationGrantType.AUTHORIZATION_CODE, createAuthorizationCodeClient(restOperations), AuthorizationGrantType.AUTHORIZATION_CODE, createAuthorizationCodeClient(restOperations),
AuthorizationGrantType.REFRESH_TOKEN, createRefreshTokenClient(restOperations), AuthorizationGrantType.REFRESH_TOKEN, createRefreshTokenClient(restOperations),
AuthorizationGrantType.PASSWORD, createPasswordClient(restOperations, clientRegistration)); AuthorizationGrantType.PASSWORD, createPasswordClient(restOperations, clientRegistration));
this.defaultOAuth2UserService = createOAuth2UserService(restOperations);
} }
@Override @Override
@@ -120,41 +121,18 @@ class SpringBasedIdentityServiceFacade implements IdentityServiceFacade
} }
@Override @Override
public Optional<OIDCUserInfo> getUserInfo(String tokenParameter, String principalAttribute) public Optional<DecodedTokenUser> getUserInfo(String token, UserInfoAttrMapping userInfoAttrMapping)
{ {
return Optional.ofNullable(tokenParameter)
.filter(Predicate.not(String::isEmpty))
.flatMap(token -> Optional.ofNullable(clientRegistration)
.map(ClientRegistration::getProviderDetails)
.map(ClientRegistration.ProviderDetails::getUserInfoEndpoint)
.map(ClientRegistration.ProviderDetails.UserInfoEndpoint::getUri)
.flatMap(uri -> {
try try
{ {
return Optional.of( return Optional.ofNullable(defaultOAuth2UserService.loadUser(new OAuth2UserRequest(clientRegistration, getSpringAccessToken(token))))
new UserInfoRequest(new URI(uri), new BearerAccessToken(token)).toHTTPRequest().send()); .flatMap(oAuth2User -> mapOAuth2UserToDecodedTokenUser(oAuth2User, userInfoAttrMapping));
} }
catch (IOException | URISyntaxException e) catch (OAuth2AuthenticationException exception)
{ {
LOGGER.warn("Failed to get user information. Reason: " + e.getMessage()); LOGGER.warn("User Info Request failed: " + exception.getMessage());
return Optional.empty(); return Optional.empty();
} }
})
.flatMap(httpResponse -> {
try
{
return Optional.of(UserInfoResponse.parse(httpResponse));
}
catch (ParseException e)
{
LOGGER.warn("Failed to parse user info response. Reason: " + e.getMessage());
return Optional.empty();
}
})
.map(UserInfoResponse::toSuccessResponse)
.map(UserInfoSuccessResponse::getUserInfo))
.map(userInfo -> new OIDCUserInfo(userInfo.getStringClaim(principalAttribute), userInfo.getGivenName(),
userInfo.getFamilyName(), userInfo.getEmailAddress()));
} }
@Override @Override
@@ -191,11 +169,7 @@ class SpringBasedIdentityServiceFacade implements IdentityServiceFacade
if (grant.isRefreshToken()) if (grant.isRefreshToken())
{ {
final OAuth2AccessToken expiredAccessToken = new OAuth2AccessToken( final OAuth2AccessToken expiredAccessToken = getSpringAccessToken("JUST_FOR_FULFILLING_THE_SPRING_API");
TokenType.BEARER,
"JUST_FOR_FULFILLING_THE_SPRING_API",
SOME_INSIGNIFICANT_DATE_IN_THE_PAST,
SOME_INSIGNIFICANT_DATE_IN_THE_PAST.plusSeconds(1));
final OAuth2RefreshToken refreshToken = new OAuth2RefreshToken(grant.getRefreshToken(), null); final OAuth2RefreshToken refreshToken = new OAuth2RefreshToken(grant.getRefreshToken(), null);
return new OAuth2RefreshTokenGrantRequest(clientRegistration, expiredAccessToken, refreshToken, return new OAuth2RefreshTokenGrantRequest(clientRegistration, expiredAccessToken, refreshToken,
@@ -213,8 +187,7 @@ class SpringBasedIdentityServiceFacade implements IdentityServiceFacade
.build(), .build(),
OAuth2AuthorizationResponse.success(grant.getAuthorizationCode()) OAuth2AuthorizationResponse.success(grant.getAuthorizationCode())
.redirectUri(grant.getRedirectUri()) .redirectUri(grant.getRedirectUri())
.build() .build());
);
return new OAuth2AuthorizationCodeGrantRequest(clientRegistration, authzExchange); return new OAuth2AuthorizationCodeGrantRequest(clientRegistration, authzExchange);
} }
@@ -248,6 +221,26 @@ class SpringBasedIdentityServiceFacade implements IdentityServiceFacade
return client; return client;
} }
private static DefaultOAuth2UserService createOAuth2UserService(RestOperations rest)
{
final DefaultOAuth2UserService userService = new DefaultOAuth2UserService();
userService.setRestOperations(rest);
return userService;
}
private Optional<DecodedTokenUser> mapOAuth2UserToDecodedTokenUser(OAuth2User oAuth2User, UserInfoAttrMapping userInfoAttrMapping)
{
Optional<String> preferredUsername = Optional.ofNullable(oAuth2User.getAttribute(PersonClaims.PREFERRED_USERNAME_CLAIM_NAME))
.filter(String.class::isInstance)
.map(String.class::cast)
.filter(StringUtils::isNotEmpty);
Optional<String> userName = Optional.ofNullable(oAuth2User.getName()).filter(username -> !username.isEmpty()).or(() -> preferredUsername);
return userName.map(name -> DecodedTokenUser.validateAndCreate(name,
oAuth2User.getAttribute(userInfoAttrMapping.firstNameClaim()),
oAuth2User.getAttribute(userInfoAttrMapping.lastNameClaim()),
oAuth2User.getAttribute(userInfoAttrMapping.emailClaim())));
}
private static OAuth2AccessTokenResponseClient<OAuth2PasswordGrantRequest> createPasswordClient(RestOperations rest, private static OAuth2AccessTokenResponseClient<OAuth2PasswordGrantRequest> createPasswordClient(RestOperations rest,
ClientRegistration clientRegistration) ClientRegistration clientRegistration)
{ {
@@ -278,6 +271,16 @@ class SpringBasedIdentityServiceFacade implements IdentityServiceFacade
}; };
} }
private static OAuth2AccessToken getSpringAccessToken(String token)
{
// Just for fulfilling the Spring API
return new OAuth2AccessToken(
TokenType.BEARER,
token,
SOME_INSIGNIFICANT_DATE_IN_THE_PAST,
SOME_INSIGNIFICANT_DATE_IN_THE_PAST.plusSeconds(1));
}
private static class SpringAccessTokenAuthorization implements AccessTokenAuthorization private static class SpringAccessTokenAuthorization implements AccessTokenAuthorization
{ {
private final OAuth2AccessTokenResponse tokenResponse; private final OAuth2AccessTokenResponse tokenResponse;

View File

@@ -2,7 +2,7 @@
* #%L * #%L
* Alfresco Repository * Alfresco Repository
* %% * %%
* Copyright (C) 2005 - 2024 Alfresco Software Limited * Copyright (C) 2005 - 2025 Alfresco Software Limited
* %% * %%
* This file is part of the Alfresco software. * This file is part of the Alfresco software.
* If the software was purchased under a paid Alfresco license, the terms of * If the software was purchased under a paid Alfresco license, the terms of
@@ -37,13 +37,19 @@ import java.util.Map;
import java.util.Optional; import java.util.Optional;
import java.util.Set; import java.util.Set;
import java.util.stream.Collectors; import java.util.stream.Collectors;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import com.nimbusds.oauth2.sdk.Scope; import com.nimbusds.oauth2.sdk.Scope;
import com.nimbusds.oauth2.sdk.id.Identifier; import com.nimbusds.oauth2.sdk.id.Identifier;
import com.nimbusds.oauth2.sdk.id.State; import com.nimbusds.oauth2.sdk.id.State;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.oauth2.client.registration.ClientRegistration;
import org.springframework.security.oauth2.client.registration.ClientRegistration.ProviderDetails;
import org.springframework.web.util.UriComponentsBuilder;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.alfresco.repo.management.subsystems.ActivateableBean; import org.alfresco.repo.management.subsystems.ActivateableBean;
import org.alfresco.repo.security.authentication.AuthenticationException; import org.alfresco.repo.security.authentication.AuthenticationException;
import org.alfresco.repo.security.authentication.external.AdminConsoleAuthenticator; import org.alfresco.repo.security.authentication.external.AdminConsoleAuthenticator;
@@ -53,16 +59,9 @@ import org.alfresco.repo.security.authentication.identityservice.IdentityService
import org.alfresco.repo.security.authentication.identityservice.IdentityServiceFacade.AccessTokenAuthorization; import org.alfresco.repo.security.authentication.identityservice.IdentityServiceFacade.AccessTokenAuthorization;
import org.alfresco.repo.security.authentication.identityservice.IdentityServiceFacade.AuthorizationException; import org.alfresco.repo.security.authentication.identityservice.IdentityServiceFacade.AuthorizationException;
import org.alfresco.repo.security.authentication.identityservice.IdentityServiceFacade.AuthorizationGrant; import org.alfresco.repo.security.authentication.identityservice.IdentityServiceFacade.AuthorizationGrant;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.oauth2.client.registration.ClientRegistration;
import org.springframework.security.oauth2.client.registration.ClientRegistration.ProviderDetails;
import org.springframework.web.util.UriComponentsBuilder;
/** /**
* An {@link AdminConsoleAuthenticator} implementation to extract an externally authenticated user ID * An {@link AdminConsoleAuthenticator} implementation to extract an externally authenticated user ID or to initiate the OIDC authorization code flow.
* or to initiate the OIDC authorization code flow.
*/ */
public class IdentityServiceAdminConsoleAuthenticator implements AdminConsoleAuthenticator, ActivateableBean public class IdentityServiceAdminConsoleAuthenticator implements AdminConsoleAuthenticator, ActivateableBean
{ {
@@ -71,7 +70,6 @@ public class IdentityServiceAdminConsoleAuthenticator implements AdminConsoleAut
private static final String ALFRESCO_ACCESS_TOKEN = "ALFRESCO_ACCESS_TOKEN"; private static final String ALFRESCO_ACCESS_TOKEN = "ALFRESCO_ACCESS_TOKEN";
private static final String ALFRESCO_REFRESH_TOKEN = "ALFRESCO_REFRESH_TOKEN"; private static final String ALFRESCO_REFRESH_TOKEN = "ALFRESCO_REFRESH_TOKEN";
private static final String ALFRESCO_TOKEN_EXPIRATION = "ALFRESCO_TOKEN_EXPIRATION"; private static final String ALFRESCO_TOKEN_EXPIRATION = "ALFRESCO_TOKEN_EXPIRATION";
private static final Set<String> SCOPES = Set.of("openid", "profile", "email", "offline_access");
private IdentityServiceConfig identityServiceConfig; private IdentityServiceConfig identityServiceConfig;
private IdentityServiceFacade identityServiceFacade; private IdentityServiceFacade identityServiceFacade;
@@ -204,7 +202,7 @@ public class IdentityServiceAdminConsoleAuthenticator implements AdminConsoleAut
.queryParam("scope", String.join("+", getScopes(clientRegistration))) .queryParam("scope", String.join("+", getScopes(clientRegistration)))
.queryParam("state", state.toString()); .queryParam("state", state.toString());
if(StringUtils.isNotBlank(identityServiceConfig.getAudience())) if (StringUtils.isNotBlank(identityServiceConfig.getAudience()))
{ {
authRequestBuilder.queryParam("audience", identityServiceConfig.getAudience()); authRequestBuilder.queryParam("audience", identityServiceConfig.getAudience());
} }
@@ -226,11 +224,16 @@ public class IdentityServiceAdminConsoleAuthenticator implements AdminConsoleAut
private Set<String> getSupportedScopes(Scope scopes) private Set<String> getSupportedScopes(Scope scopes)
{ {
return scopes.stream() return scopes.stream()
.filter(scope -> SCOPES.contains(scope.getValue())) .filter(this::hasAdminConsoleScope)
.map(Identifier::getValue) .map(Identifier::getValue)
.collect(Collectors.toSet()); .collect(Collectors.toSet());
} }
private boolean hasAdminConsoleScope(Scope.Value scope)
{
return identityServiceConfig.getAdminConsoleScopes().contains(scope.getValue());
}
private String getRedirectUri(String requestURL) private String getRedirectUri(String requestURL)
{ {
try try

View File

@@ -0,0 +1,66 @@
/*
* #%L
* Alfresco Repository
* %%
* Copyright (C) 2005 - 2025 Alfresco Software Limited
* %%
* This file is part of the Alfresco software.
* If the software was purchased under a paid Alfresco license, the terms of
* the paid license agreement will prevail. Otherwise, the software is
* provided under the following open source license terms:
*
* Alfresco is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Alfresco is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
* #L%
*/
package org.alfresco.repo.security.authentication.identityservice.user;
import java.util.Optional;
import com.nimbusds.openid.connect.sdk.claims.PersonClaims;
import org.apache.commons.lang3.StringUtils;
import org.alfresco.repo.security.authentication.identityservice.IdentityServiceFacade;
public class AccessTokenToDecodedTokenUserMapper
{
private static final String DEFAULT_USERNAME_CLAIM = PersonClaims.PREFERRED_USERNAME_CLAIM_NAME;
private final UserInfoAttrMapping userInfoAttrMapping;
public AccessTokenToDecodedTokenUserMapper(UserInfoAttrMapping userInfoAttrMapping)
{
this.userInfoAttrMapping = userInfoAttrMapping;
}
/**
* Maps the given {@link IdentityServiceFacade.DecodedAccessToken} to a {@link DecodedTokenUser}.
*
* @param token
* the token to map
* @return the mapped {@link DecodedTokenUser} or {@link Optional#empty()} if the token does not contain a username claim
*/
public Optional<DecodedTokenUser> toDecodedTokenUser(IdentityServiceFacade.DecodedAccessToken token)
{
Object firstName = token.getClaim(userInfoAttrMapping.firstNameClaim());
Object lastName = token.getClaim(userInfoAttrMapping.lastNameClaim());
Object email = token.getClaim(userInfoAttrMapping.emailClaim());
return Optional.ofNullable(token.getClaim(Optional.ofNullable(userInfoAttrMapping.usernameClaim())
.filter(StringUtils::isNotBlank)
.orElse(DEFAULT_USERNAME_CLAIM)))
.filter(String.class::isInstance)
.map(String.class::cast)
.map(username -> DecodedTokenUser.validateAndCreate(username, firstName, lastName, email));
}
}

View File

@@ -0,0 +1,109 @@
/*
* #%L
* Alfresco Repository
* %%
* Copyright (C) 2005 - 2025 Alfresco Software Limited
* %%
* This file is part of the Alfresco software.
* If the software was purchased under a paid Alfresco license, the terms of
* the paid license agreement will prevail. Otherwise, the software is
* provided under the following open source license terms:
*
* Alfresco is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Alfresco is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
* #L%
*/
package org.alfresco.repo.security.authentication.identityservice.user;
import java.util.Objects;
import java.util.Optional;
public final class DecodedTokenUser
{
private static final String EMPTY_STRING = "";
private final String username;
private final String firstName;
private final String lastName;
private final String email;
public DecodedTokenUser(String username, String firstName, String lastName, String email)
{
this.username = username;
this.firstName = firstName;
this.lastName = lastName;
this.email = email;
}
public static DecodedTokenUser validateAndCreate(String username, Object firstName, Object lastName, Object email)
{
return new DecodedTokenUser(username, getStringVal(firstName), getStringVal(lastName), getStringVal(email));
}
private static String getStringVal(Object firstName)
{
return Optional.ofNullable(firstName).filter(String.class::isInstance).map(String.class::cast).orElse(EMPTY_STRING);
}
public String username()
{
return username;
}
public String firstName()
{
return firstName;
}
public String lastName()
{
return lastName;
}
public String email()
{
return email;
}
@Override
public boolean equals(Object object)
{
if (this == object)
{
return true;
}
if (object == null || getClass() != object.getClass())
{
return false;
}
DecodedTokenUser that = (DecodedTokenUser) object;
return Objects.equals(username, that.username) && Objects.equals(firstName, that.firstName) && Objects.equals(lastName, that.lastName) && Objects.equals(email, that.email);
}
@Override
public int hashCode()
{
return Objects.hash(username, firstName, lastName, email);
}
@Override
public String toString()
{
return "DecodedTokenUser{" +
"username='" + username + '\'' +
", firstName='" + firstName + '\'' +
", lastName='" + lastName + '\'' +
", email='" + email + '\'' +
'}';
}
}

View File

@@ -23,7 +23,7 @@
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>. * along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
* #L% * #L%
*/ */
package org.alfresco.repo.security.authentication.identityservice; package org.alfresco.repo.security.authentication.identityservice.user;
import java.util.stream.Stream; import java.util.stream.Stream;

View File

@@ -0,0 +1,76 @@
/*
* #%L
* Alfresco Repository
* %%
* Copyright (C) 2005 - 2025 Alfresco Software Limited
* %%
* This file is part of the Alfresco software.
* If the software was purchased under a paid Alfresco license, the terms of
* the paid license agreement will prevail. Otherwise, the software is
* provided under the following open source license terms:
*
* Alfresco is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Alfresco is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
* #L%
*/
package org.alfresco.repo.security.authentication.identityservice.user;
import org.alfresco.repo.security.authentication.AuthenticationUtil;
import org.alfresco.service.cmr.security.PersonService;
public class TokenUserToOIDCUserMapper
{
private final PersonService personService;
public TokenUserToOIDCUserMapper(PersonService personService)
{
this.personService = personService;
}
/**
* Maps a decoded token user to an OIDC user where the user id (username) is normalized.
*
* @param decodedTokenUser
* the decoded token user
* @return the OIDC user
*/
public OIDCUserInfo toOIDCUser(DecodedTokenUser decodedTokenUser)
{
return new OIDCUserInfo(usernameToUserId(decodedTokenUser.username()), decodedTokenUser.firstName(), decodedTokenUser.lastName(), decodedTokenUser.email());
}
/**
* Normalizes a username, taking into account existing user accounts and case sensitivity settings.
*
* @param caseSensitiveUserName
* the case-sensitive username
* @return the string
*/
private String usernameToUserId(final String caseSensitiveUserName)
{
if (caseSensitiveUserName == null)
{
return null;
}
String normalized = AuthenticationUtil.runAs(new AuthenticationUtil.RunAsWork<String>() {
@Override
public String doWork() throws Exception
{
return personService.getUserIdentifier(caseSensitiveUserName);
}
}, AuthenticationUtil.getSystemUserName());
return normalized == null ? caseSensitiveUserName : normalized;
}
}

View File

@@ -0,0 +1,108 @@
/*
* #%L
* Alfresco Repository
* %%
* Copyright (C) 2005 - 2025 Alfresco Software Limited
* %%
* This file is part of the Alfresco software.
* If the software was purchased under a paid Alfresco license, the terms of
* the paid license agreement will prevail. Otherwise, the software is
* provided under the following open source license terms:
*
* Alfresco is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Alfresco is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
* #L%
*/
package org.alfresco.repo.security.authentication.identityservice.user;
import java.util.Objects;
public final class UserInfoAttrMapping
{
private final String usernameClaim;
private final String firstNameClaim;
private final String lastNameClaim;
private final String emailClaim;
/**
* The UserInfoAttrMapping class represents the mapping of claims fetched from the UserInfo endpoint to create an Alfresco user.
*
* @param usernameClaim
* the claim that represents the username
* @param firstNameClaim
* the claim that represents the first name
* @param lastNameClaim
* the claim that represents the last name
* @param emailClaim
* the claim that represents the email
*/
public UserInfoAttrMapping(String usernameClaim, String firstNameClaim, String lastNameClaim, String emailClaim)
{
this.usernameClaim = usernameClaim;
this.firstNameClaim = firstNameClaim;
this.lastNameClaim = lastNameClaim;
this.emailClaim = emailClaim;
}
public String usernameClaim()
{
return usernameClaim;
}
public String firstNameClaim()
{
return firstNameClaim;
}
public String lastNameClaim()
{
return lastNameClaim;
}
public String emailClaim()
{
return emailClaim;
}
@Override
public boolean equals(Object object)
{
if (this == object)
{
return true;
}
if (object == null || getClass() != object.getClass())
{
return false;
}
UserInfoAttrMapping that = (UserInfoAttrMapping) object;
return Objects.equals(usernameClaim, that.usernameClaim) && Objects.equals(firstNameClaim, that.firstNameClaim) && Objects.equals(lastNameClaim, that.lastNameClaim) && Objects.equals(emailClaim, that.emailClaim);
}
@Override
public int hashCode()
{
return Objects.hash(usernameClaim, firstNameClaim, lastNameClaim, emailClaim);
}
@Override
public String toString()
{
return "UserInfoAttrMapping{" +
"usernameClaim='" + usernameClaim + '\'' +
", firstNameClaim='" + firstNameClaim + '\'' +
", lastNameClaim='" + lastNameClaim + '\'' +
", emailClaim='" + emailClaim + '\'' +
'}';
}
}

View File

@@ -149,6 +149,15 @@
<property name="principalAttribute"> <property name="principalAttribute">
<value>${identity-service.principal-attribute:preferred_username}</value> <value>${identity-service.principal-attribute:preferred_username}</value>
</property> </property>
<property name="firstNameAttribute">
<value>${identity-service.first-name-attribute:given_name}</value>
</property>
<property name="lastNameAttribute">
<value>${identity-service.last-name-attribute:family_name}</value>
</property>
<property name="emailAttribute">
<value>${identity-service.email-attribute:email}</value>
</property>
<property name="clientIdValidationDisabled"> <property name="clientIdValidationDisabled">
<value>${identity-service.client-id.validation.disabled:true}</value> <value>${identity-service.client-id.validation.disabled:true}</value>
</property> </property>
@@ -158,6 +167,18 @@
<property name="signatureAlgorithms"> <property name="signatureAlgorithms">
<value>${identity-service.signature-algorithms:RS256,PS256}</value> <value>${identity-service.signature-algorithms:RS256,PS256}</value>
</property> </property>
<property name="adminConsoleScopes">
<value>${identity-service.admin-console.scopes:openid,profile,email,offline_access}</value>
</property>
<property name="passwordGrantScopes">
<value>${identity-service.password-grant.scopes:openid,profile,email}</value>
</property>
<property name="issuerAttribute">
<value>${identity-service.issuer-attribute:issuer}</value>
</property>
<property name="jwtClockSkewMs">
<value>${identity-service.jwt-clock-skew-ms:0}</value>
</property>
</bean> </bean>
<!-- Enable control over mapping between request and user ID --> <!-- Enable control over mapping between request and user ID -->

View File

@@ -13,3 +13,10 @@ identity-service.credentials.secret=
identity-service.public-client=true identity-service.public-client=true
identity-service.admin-console.redirect-path=/alfresco/s/admin/admin-communitysummary identity-service.admin-console.redirect-path=/alfresco/s/admin/admin-communitysummary
identity-service.signature-algorithms=RS256,PS256 identity-service.signature-algorithms=RS256,PS256
identity-service.first-name-attribute=given_name
identity-service.last-name-attribute=family_name
identity-service.email-attribute=email
identity-service.admin-console.scopes=openid,profile,email,offline_access
identity-service.password-grant.scopes=openid,profile,email
identity-service.issuer-attribute=issuer
identity-service.jwt-clock-skew-ms=0

View File

@@ -2,7 +2,7 @@
* #%L * #%L
* Alfresco Repository * Alfresco Repository
* %% * %%
* Copyright (C) 2005 - 2024 Alfresco Software Limited * Copyright (C) 2005 - 2025 Alfresco Software Limited
* %% * %%
* This file is part of the Alfresco software. * This file is part of the Alfresco software.
* If the software was purchased under a paid Alfresco license, the terms of * If the software was purchased under a paid Alfresco license, the terms of
@@ -25,6 +25,10 @@
*/ */
package org.alfresco; package org.alfresco;
import org.junit.experimental.categories.Categories;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
import org.alfresco.repo.security.authentication.identityservice.ClientRegistrationProviderUnitTest; import org.alfresco.repo.security.authentication.identityservice.ClientRegistrationProviderUnitTest;
import org.alfresco.repo.security.authentication.identityservice.IdentityServiceFacadeFactoryBeanTest; import org.alfresco.repo.security.authentication.identityservice.IdentityServiceFacadeFactoryBeanTest;
import org.alfresco.repo.security.authentication.identityservice.IdentityServiceJITProvisioningHandlerUnitTest; import org.alfresco.repo.security.authentication.identityservice.IdentityServiceJITProvisioningHandlerUnitTest;
@@ -33,15 +37,13 @@ import org.alfresco.repo.security.authentication.identityservice.SpringBasedIden
import org.alfresco.repo.security.authentication.identityservice.admin.AdminConsoleAuthenticationCookiesServiceUnitTest; import org.alfresco.repo.security.authentication.identityservice.admin.AdminConsoleAuthenticationCookiesServiceUnitTest;
import org.alfresco.repo.security.authentication.identityservice.admin.AdminConsoleHttpServletRequestWrapperUnitTest; import org.alfresco.repo.security.authentication.identityservice.admin.AdminConsoleHttpServletRequestWrapperUnitTest;
import org.alfresco.repo.security.authentication.identityservice.admin.IdentityServiceAdminConsoleAuthenticatorUnitTest; import org.alfresco.repo.security.authentication.identityservice.admin.IdentityServiceAdminConsoleAuthenticatorUnitTest;
import org.alfresco.repo.security.authentication.identityservice.user.AccessTokenToDecodedTokenUserMapperUnitTest;
import org.alfresco.repo.security.authentication.identityservice.user.TokenUserToOIDCUserMapperUnitTest;
import org.alfresco.util.testing.category.DBTests; import org.alfresco.util.testing.category.DBTests;
import org.alfresco.util.testing.category.NonBuildTests; import org.alfresco.util.testing.category.NonBuildTests;
import org.junit.experimental.categories.Categories;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
/** /**
* All Repository project UNIT test classes (no application context) should be added to this test suite. * All Repository project UNIT test classes (no application context) should be added to this test suite. Tests marked as DBTests are automatically excluded and are run as part of {@link AllDBTestsTestSuite}.
* Tests marked as DBTests are automatically excluded and are run as part of {@link AllDBTestsTestSuite}.
*/ */
@RunWith(Categories.class) @RunWith(Categories.class)
@Categories.ExcludeCategory({DBTests.class, NonBuildTests.class}) @Categories.ExcludeCategory({DBTests.class, NonBuildTests.class})
@@ -149,6 +151,8 @@ import org.junit.runners.Suite;
LazyInstantiatingIdentityServiceFacadeUnitTest.class, LazyInstantiatingIdentityServiceFacadeUnitTest.class,
SpringBasedIdentityServiceFacadeUnitTest.class, SpringBasedIdentityServiceFacadeUnitTest.class,
IdentityServiceJITProvisioningHandlerUnitTest.class, IdentityServiceJITProvisioningHandlerUnitTest.class,
AccessTokenToDecodedTokenUserMapperUnitTest.class,
TokenUserToOIDCUserMapperUnitTest.class,
AdminConsoleAuthenticationCookiesServiceUnitTest.class, AdminConsoleAuthenticationCookiesServiceUnitTest.class,
AdminConsoleHttpServletRequestWrapperUnitTest.class, AdminConsoleHttpServletRequestWrapperUnitTest.class,
IdentityServiceAdminConsoleAuthenticatorUnitTest.class, IdentityServiceAdminConsoleAuthenticatorUnitTest.class,
@@ -265,5 +269,4 @@ import org.junit.runners.Suite;
org.alfresco.repo.serviceaccount.ServiceAccountRegistryImplTest.class org.alfresco.repo.serviceaccount.ServiceAccountRegistryImplTest.class
}) })
public class AllUnitTestsSuite public class AllUnitTestsSuite
{ {}
}

View File

@@ -2,7 +2,7 @@
* #%L * #%L
* Alfresco Repository * Alfresco Repository
* %% * %%
* Copyright (C) 2005 - 2024 Alfresco Software Limited * Copyright (C) 2005 - 2025 Alfresco Software Limited
* %% * %%
* This file is part of the Alfresco software. * This file is part of the Alfresco software.
* If the software was purchased under a paid Alfresco license, the terms of * If the software was purchased under a paid Alfresco license, the terms of
@@ -38,8 +38,7 @@ import java.util.Set;
import com.nimbusds.oauth2.sdk.ParseException; import com.nimbusds.oauth2.sdk.ParseException;
import com.nimbusds.oauth2.sdk.Scope; import com.nimbusds.oauth2.sdk.Scope;
import com.nimbusds.openid.connect.sdk.op.OIDCProviderMetadata; import com.nimbusds.openid.connect.sdk.op.OIDCProviderMetadata;
import net.minidev.json.JSONObject;
import org.alfresco.repo.security.authentication.identityservice.IdentityServiceFacadeFactoryBean.ClientRegistrationProvider;
import org.junit.Before; import org.junit.Before;
import org.junit.Test; import org.junit.Test;
import org.mockito.ArgumentCaptor; import org.mockito.ArgumentCaptor;
@@ -51,12 +50,17 @@ import org.springframework.http.ResponseEntity;
import org.springframework.security.oauth2.client.registration.ClientRegistration; import org.springframework.security.oauth2.client.registration.ClientRegistration;
import org.springframework.web.client.RestTemplate; import org.springframework.web.client.RestTemplate;
import org.alfresco.repo.security.authentication.identityservice.IdentityServiceFacadeFactoryBean.ClientRegistrationProvider;
public class ClientRegistrationProviderUnitTest public class ClientRegistrationProviderUnitTest
{ {
private static final String CLIENT_ID = "alfresco"; private static final String CLIENT_ID = "alfresco";
private static final String OPENID_CONFIGURATION = "{\"token_endpoint\":\"https://login.serviceonline.alfresco/common/oauth2/v2.0/token\",\"token_endpoint_auth_methods_supported\":[\"client_secret_post\",\"private_key_jwt\",\"client_secret_basic\"],\"jwks_uri\":\"https://login.serviceonline.alfresco/common/discovery/v2.0/keys\",\"response_modes_supported\":[\"query\",\"fragment\",\"form_post\"],\"subject_types_supported\":[\"pairwise\"],\"id_token_signing_alg_values_supported\":[\"RS256\"],\"response_types_supported\":[\"code\",\"id_token\",\"code id_token\",\"id_token token\"],\"scopes_supported\":[\"openid\",\"profile\",\"email\",\"offline_access\"],\"issuer\":\"https://login.serviceonline.alfresco/alfresco/v2.0\",\"request_uri_parameter_supported\":false,\"userinfo_endpoint\":\"https://graph.service.alfresco/oidc/userinfo\",\"authorization_endpoint\":\"https://login.serviceonline.alfresco/common/oauth2/v2.0/authorize\",\"device_authorization_endpoint\":\"https://login.serviceonline.alfresco/common/oauth2/v2.0/devicecode\",\"http_logout_supported\":true,\"frontchannel_logout_supported\":true,\"end_session_endpoint\":\"https://login.serviceonline.alfresco/common/oauth2/v2.0/logout\",\"claims_supported\":[\"sub\",\"iss\",\"cloud_instance_name\",\"cloud_instance_host_name\",\"cloud_graph_host_name\",\"msgraph_host\",\"aud\",\"exp\",\"iat\",\"auth_time\",\"acr\",\"nonce\",\"preferred_username\",\"name\",\"tid\",\"ver\",\"at_hash\",\"c_hash\",\"email\"],\"kerberos_endpoint\":\"https://login.serviceonline.alfresco/common/kerberos\",\"tenant_region_scope\":null,\"cloud_instance_name\":\"serviceonline.alfresco\",\"cloud_graph_host_name\":\"graph.oidc.net\",\"msgraph_host\":\"graph.service.alfresco\",\"rbac_url\":\"https://pas.oidc.alfresco\"}"; private static final String OPENID_CONFIGURATION = "{\"token_endpoint\":\"https://login.serviceonline.alfresco/common/oauth2/v2.0/token\",\"token_endpoint_auth_methods_supported\":[\"client_secret_post\",\"private_key_jwt\",\"client_secret_basic\"],\"jwks_uri\":\"https://login.serviceonline.alfresco/common/discovery/v2.0/keys\",\"response_modes_supported\":[\"query\",\"fragment\",\"form_post\"],\"subject_types_supported\":[\"pairwise\"],\"id_token_signing_alg_values_supported\":[\"RS256\"],\"response_types_supported\":[\"code\",\"id_token\",\"code id_token\",\"id_token token\"],\"scopes_supported\":[\"openid\",\"profile\",\"email\",\"offline_access\"],\"issuer\":\"https://login.serviceonline.alfresco/alfresco/v2.0\",\"request_uri_parameter_supported\":false,\"userinfo_endpoint\":\"https://graph.service.alfresco/oidc/userinfo\",\"authorization_endpoint\":\"https://login.serviceonline.alfresco/common/oauth2/v2.0/authorize\",\"device_authorization_endpoint\":\"https://login.serviceonline.alfresco/common/oauth2/v2.0/devicecode\",\"http_logout_supported\":true,\"frontchannel_logout_supported\":true,\"end_session_endpoint\":\"https://login.serviceonline.alfresco/common/oauth2/v2.0/logout\",\"claims_supported\":[\"sub\",\"iss\",\"cloud_instance_name\",\"cloud_instance_host_name\",\"cloud_graph_host_name\",\"msgraph_host\",\"aud\",\"exp\",\"iat\",\"auth_time\",\"acr\",\"nonce\",\"preferred_username\",\"name\",\"tid\",\"ver\",\"at_hash\",\"c_hash\",\"email\"],\"kerberos_endpoint\":\"https://login.serviceonline.alfresco/common/kerberos\",\"tenant_region_scope\":null,\"cloud_instance_name\":\"serviceonline.alfresco\",\"cloud_graph_host_name\":\"graph.oidc.net\",\"msgraph_host\":\"graph.service.alfresco\",\"rbac_url\":\"https://pas.oidc.alfresco\"}";
private static final String DISCOVERY_PATH_SEGMENTS = "/.well-known/openid-configuration"; private static final String DISCOVERY_PATH_SEGMENTS = "/.well-known/openid-configuration";
private static final String AUTH_SERVER = "https://login.serviceonline.alfresco"; private static final String AUTH_SERVER = "https://login.serviceonline.alfresco";
private static final String ADMIN_CONSOLE_SCOPES = "openid,email,profile,offline_access";
private static final String PSSWD_GRANT_SCOPES = "openid,email,profile";
private static final String ISSUER_ATRR = "issuer";
private IdentityServiceConfig config; private IdentityServiceConfig config;
private RestTemplate restTemplate; private RestTemplate restTemplate;
@@ -70,6 +74,9 @@ public class ClientRegistrationProviderUnitTest
config = new IdentityServiceConfig(); config = new IdentityServiceConfig();
config.setAuthServerUrl(AUTH_SERVER); config.setAuthServerUrl(AUTH_SERVER);
config.setResource(CLIENT_ID); config.setResource(CLIENT_ID);
config.setAdminConsoleScopes(ADMIN_CONSOLE_SCOPES);
config.setPasswordGrantScopes(PSSWD_GRANT_SCOPES);
config.setIssuerAttribute(ISSUER_ATRR);
restTemplate = mock(RestTemplate.class); restTemplate = mock(RestTemplate.class);
ResponseEntity responseEntity = mock(ResponseEntity.class); ResponseEntity responseEntity = mock(ResponseEntity.class);
@@ -263,4 +270,42 @@ public class ClientRegistrationProviderUnitTest
"https://login.serviceonline.alfresco/alfresco/v2.0" + DISCOVERY_PATH_SEGMENTS); "https://login.serviceonline.alfresco/alfresco/v2.0" + DISCOVERY_PATH_SEGMENTS);
} }
} }
@Test
public void shouldUseDefaultIssuerAttribute()
{
config.setIssuerUrl(null);
try (MockedStatic<OIDCProviderMetadata> providerMetadata = Mockito.mockStatic(OIDCProviderMetadata.class))
{
providerMetadata.when(() -> OIDCProviderMetadata.parse(any(String.class))).thenReturn(oidcResponse);
ClientRegistration clientRegistration = new ClientRegistrationProvider(config).createClientRegistration(
restTemplate);
assertThat(clientRegistration.getProviderDetails().getIssuerUri()).isEqualTo("https://login.serviceonline.alfresco/alfresco/v2.0");
}
}
@Test
public void shouldUseCustomIssuerAttribute()
{
try (MockedStatic<OIDCProviderMetadata> providerMetadata = Mockito.mockStatic(OIDCProviderMetadata.class))
{
config.setIssuerAttribute("access_token_issuer");
when(oidcResponse.getCustomParameters()).thenReturn(createJSONObject("access_token_issuer", "https://login.serviceonline.alfresco/alfresco/v2.0/at_trust"));
providerMetadata.when(() -> OIDCProviderMetadata.parse(any(String.class))).thenReturn(oidcResponse);
ClientRegistration clientRegistration = new ClientRegistrationProvider(config).createClientRegistration(
restTemplate);
assertThat(clientRegistration.getProviderDetails().getIssuerUri()).isEqualTo("https://login.serviceonline.alfresco/alfresco/v2.0/at_trust");
}
}
private static JSONObject createJSONObject(String fieldName, String fieldValue)
{
JSONObject jsonObject = new JSONObject();
jsonObject.appendField(fieldName, fieldValue);
return jsonObject;
}
} }

View File

@@ -2,7 +2,7 @@
* #%L * #%L
* Alfresco Repository * Alfresco Repository
* %% * %%
* Copyright (C) 2005 - 2023 Alfresco Software Limited * Copyright (C) 2005 - 2025 Alfresco Software Limited
* %% * %%
* This file is part of the Alfresco software. * This file is part of the Alfresco software.
* If the software was purchased under a paid Alfresco license, the terms of * If the software was purchased under a paid Alfresco license, the terms of
@@ -32,21 +32,23 @@ import static org.mockito.Mockito.when;
import java.net.ConnectException; import java.net.ConnectException;
import java.util.Optional; import java.util.Optional;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.alfresco.error.ExceptionStackUtil; import org.alfresco.error.ExceptionStackUtil;
import org.alfresco.repo.security.authentication.AuthenticationContext; import org.alfresco.repo.security.authentication.AuthenticationContext;
import org.alfresco.repo.security.authentication.AuthenticationException; import org.alfresco.repo.security.authentication.AuthenticationException;
import org.alfresco.repo.security.authentication.identityservice.IdentityServiceFacade.AccessTokenAuthorization; import org.alfresco.repo.security.authentication.identityservice.IdentityServiceFacade.AccessTokenAuthorization;
import org.alfresco.repo.security.authentication.identityservice.IdentityServiceFacade.AuthorizationException; import org.alfresco.repo.security.authentication.identityservice.IdentityServiceFacade.AuthorizationException;
import org.alfresco.repo.security.authentication.identityservice.IdentityServiceFacade.AuthorizationGrant; import org.alfresco.repo.security.authentication.identityservice.IdentityServiceFacade.AuthorizationGrant;
import org.alfresco.repo.security.authentication.identityservice.user.OIDCUserInfo;
import org.alfresco.repo.security.sync.UserRegistrySynchronizer; import org.alfresco.repo.security.sync.UserRegistrySynchronizer;
import org.alfresco.service.cmr.repository.NodeService; import org.alfresco.service.cmr.repository.NodeService;
import org.alfresco.service.cmr.security.PersonService; import org.alfresco.service.cmr.security.PersonService;
import org.alfresco.service.transaction.TransactionService; import org.alfresco.service.transaction.TransactionService;
import org.alfresco.util.BaseSpringTest; import org.alfresco.util.BaseSpringTest;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
public class IdentityServiceAuthenticationComponentTest extends BaseSpringTest public class IdentityServiceAuthenticationComponentTest extends BaseSpringTest
{ {
@@ -67,7 +69,6 @@ public class IdentityServiceAuthenticationComponentTest extends BaseSpringTest
@Autowired @Autowired
private PersonService personService; private PersonService personService;
private IdentityServiceJITProvisioningHandler jitProvisioning; private IdentityServiceJITProvisioningHandler jitProvisioning;
private IdentityServiceFacade mockIdentityServiceFacade; private IdentityServiceFacade mockIdentityServiceFacade;
@@ -92,7 +93,7 @@ public class IdentityServiceAuthenticationComponentTest extends BaseSpringTest
authenticationContext.clearCurrentSecurityContext(); authenticationContext.clearCurrentSecurityContext();
} }
@Test (expected=AuthenticationException.class) @Test(expected = AuthenticationException.class)
public void testAuthenticationFail() public void testAuthenticationFail()
{ {
final AuthorizationGrant grant = AuthorizationGrant.password("username", "password"); final AuthorizationGrant grant = AuthorizationGrant.password("username", "password");
@@ -122,7 +123,7 @@ public class IdentityServiceAuthenticationComponentTest extends BaseSpringTest
} }
} }
@Test (expected=AuthenticationException.class) @Test(expected = AuthenticationException.class)
public void testAuthenticationFail_otherException() public void testAuthenticationFail_otherException()
{ {
final AuthorizationGrant grant = AuthorizationGrant.password("username", "password"); final AuthorizationGrant grant = AuthorizationGrant.password("username", "password");
@@ -150,10 +151,10 @@ public class IdentityServiceAuthenticationComponentTest extends BaseSpringTest
authComponent.authenticateImpl("username", "password".toCharArray()); authComponent.authenticateImpl("username", "password".toCharArray());
// Check that the authenticated user has been set // Check that the authenticated user has been set
assertEquals("User has not been set as expected.","username", authenticationContext.getCurrentUserName()); assertEquals("User has not been set as expected.", "username", authenticationContext.getCurrentUserName());
} }
@Test (expected= AuthenticationException.class) @Test(expected = AuthenticationException.class)
public void testFallthroughWhenIdentityServiceFacadeIsNull() public void testFallthroughWhenIdentityServiceFacadeIsNull()
{ {
authComponent.setIdentityServiceFacade(null); authComponent.setIdentityServiceFacade(null);

View File

@@ -2,7 +2,7 @@
* #%L * #%L
* Alfresco Repository * Alfresco Repository
* %% * %%
* Copyright (C) 2005 - 2024 Alfresco Software Limited * Copyright (C) 2005 - 2025 Alfresco Software Limited
* %% * %%
* This file is part of the Alfresco software. * This file is part of the Alfresco software.
* If the software was purchased under a paid Alfresco license, the terms of * If the software was purchased under a paid Alfresco license, the terms of
@@ -25,29 +25,29 @@
*/ */
package org.alfresco.repo.security.authentication.identityservice; package org.alfresco.repo.security.authentication.identityservice;
import static org.mockito.Mockito.atLeast; import static org.mockito.Mockito.*;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import java.lang.reflect.Field; import java.lang.reflect.Field;
import java.util.Optional; import java.util.Optional;
import com.nimbusds.openid.connect.sdk.claims.PersonClaims; import com.nimbusds.openid.connect.sdk.claims.PersonClaims;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.springframework.security.oauth2.client.registration.ClientRegistration;
import org.alfresco.model.ContentModel; import org.alfresco.model.ContentModel;
import org.alfresco.repo.management.subsystems.ChildApplicationContextFactory; import org.alfresco.repo.management.subsystems.ChildApplicationContextFactory;
import org.alfresco.repo.management.subsystems.DefaultChildApplicationContextManager; import org.alfresco.repo.management.subsystems.DefaultChildApplicationContextManager;
import org.alfresco.repo.security.authentication.AuthenticationUtil; import org.alfresco.repo.security.authentication.AuthenticationUtil;
import org.alfresco.repo.security.authentication.identityservice.user.OIDCUserInfo;
import org.alfresco.repo.security.authentication.identityservice.user.UserInfoAttrMapping;
import org.alfresco.repo.transaction.RetryingTransactionHelper.RetryingTransactionCallback; import org.alfresco.repo.transaction.RetryingTransactionHelper.RetryingTransactionCallback;
import org.alfresco.service.cmr.repository.NodeRef; import org.alfresco.service.cmr.repository.NodeRef;
import org.alfresco.service.cmr.repository.NodeService; import org.alfresco.service.cmr.repository.NodeService;
import org.alfresco.service.cmr.security.PersonService; import org.alfresco.service.cmr.security.PersonService;
import org.alfresco.service.transaction.TransactionService; import org.alfresco.service.transaction.TransactionService;
import org.alfresco.util.BaseSpringTest; import org.alfresco.util.BaseSpringTest;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
@SuppressWarnings("PMD.AvoidAccessibilityAlteration") @SuppressWarnings("PMD.AvoidAccessibilityAlteration")
public class IdentityServiceJITProvisioningHandlerTest extends BaseSpringTest public class IdentityServiceJITProvisioningHandlerTest extends BaseSpringTest
@@ -95,8 +95,7 @@ public class IdentityServiceJITProvisioningHandlerTest extends BaseSpringTest
{ {
assertFalse(personService.personExists(IDS_USERNAME)); assertFalse(personService.personExists(IDS_USERNAME));
IdentityServiceFacade.AccessTokenAuthorization accessTokenAuthorization = IdentityServiceFacade.AccessTokenAuthorization accessTokenAuthorization = identityServiceFacade.authorize(
identityServiceFacade.authorize(
IdentityServiceFacade.AuthorizationGrant.password(IDS_USERNAME, userPassword)); IdentityServiceFacade.AuthorizationGrant.password(IDS_USERNAME, userPassword));
Optional<OIDCUserInfo> userInfoOptional = jitProvisioningHandler.extractUserInfoAndCreateUserIfNeeded( Optional<OIDCUserInfo> userInfoOptional = jitProvisioningHandler.extractUserInfoAndCreateUserIfNeeded(
@@ -125,14 +124,17 @@ public class IdentityServiceJITProvisioningHandlerTest extends BaseSpringTest
assertFalse(personService.personExists(IDS_USERNAME)); assertFalse(personService.personExists(IDS_USERNAME));
String principalAttribute = isAuth0Enabled ? PersonClaims.NICKNAME_CLAIM_NAME : PersonClaims.PREFERRED_USERNAME_CLAIM_NAME; String principalAttribute = isAuth0Enabled ? PersonClaims.NICKNAME_CLAIM_NAME : PersonClaims.PREFERRED_USERNAME_CLAIM_NAME;
IdentityServiceFacade.AccessTokenAuthorization accessTokenAuthorization = IdentityServiceFacade.AccessTokenAuthorization accessTokenAuthorization = identityServiceFacade.authorize(
identityServiceFacade.authorize(
IdentityServiceFacade.AuthorizationGrant.password(IDS_USERNAME, userPassword)); IdentityServiceFacade.AuthorizationGrant.password(IDS_USERNAME, userPassword));
UserInfoAttrMapping userInfoAttrMapping = new UserInfoAttrMapping(principalAttribute, "given_name", "family_name", "email");
String accessToken = accessTokenAuthorization.getAccessToken().getTokenValue(); String accessToken = accessTokenAuthorization.getAccessToken().getTokenValue();
ClientRegistration clientRegistration = mock(ClientRegistration.class, RETURNS_DEEP_STUBS);
when(clientRegistration.getProviderDetails().getUserInfoEndpoint().getUserNameAttributeName()).thenReturn(principalAttribute);
IdentityServiceFacade idsServiceFacadeMock = mock(IdentityServiceFacade.class); IdentityServiceFacade idsServiceFacadeMock = mock(IdentityServiceFacade.class);
when(idsServiceFacadeMock.decodeToken(accessToken)).thenReturn(null); when(idsServiceFacadeMock.decodeToken(accessToken)).thenReturn(null);
when(idsServiceFacadeMock.getUserInfo(accessToken, principalAttribute)).thenReturn(identityServiceFacade.getUserInfo(accessToken, principalAttribute)); when(idsServiceFacadeMock.getUserInfo(accessToken, userInfoAttrMapping)).thenReturn(identityServiceFacade.getUserInfo(accessToken, userInfoAttrMapping));
when(idsServiceFacadeMock.getClientRegistration()).thenReturn(clientRegistration);
// Replace the original facade with a mocked one to prevent user information from being extracted from the access token. // Replace the original facade with a mocked one to prevent user information from being extracted from the access token.
Field declaredField = jitProvisioningHandler.getClass() Field declaredField = jitProvisioningHandler.getClass()
@@ -153,7 +155,7 @@ public class IdentityServiceJITProvisioningHandlerTest extends BaseSpringTest
assertEquals("johndoe123@alfresco.com", userInfoOptional.get().email()); assertEquals("johndoe123@alfresco.com", userInfoOptional.get().email());
assertEquals("johndoe123@alfresco.com", nodeService.getProperty(person, ContentModel.PROP_EMAIL)); assertEquals("johndoe123@alfresco.com", nodeService.getProperty(person, ContentModel.PROP_EMAIL));
verify(idsServiceFacadeMock).decodeToken(accessToken); verify(idsServiceFacadeMock).decodeToken(accessToken);
verify(idsServiceFacadeMock, atLeast(1)).getUserInfo(accessToken, principalAttribute); verify(idsServiceFacadeMock, atLeast(1)).getUserInfo(accessToken, userInfoAttrMapping);
if (!isAuth0Enabled) if (!isAuth0Enabled)
{ {
assertEquals("John", userInfoOptional.get().firstName()); assertEquals("John", userInfoOptional.get().firstName());
@@ -166,8 +168,7 @@ public class IdentityServiceJITProvisioningHandlerTest extends BaseSpringTest
@After @After
public void tearDown() public void tearDown()
{ {
AuthenticationUtil.runAsSystem(new AuthenticationUtil.RunAsWork<Void>() AuthenticationUtil.runAsSystem(new AuthenticationUtil.RunAsWork<Void>() {
{
@Override @Override
public Void doWork() throws Exception public Void doWork() throws Exception
{ {

View File

@@ -2,7 +2,7 @@
* #%L * #%L
* Alfresco Repository * Alfresco Repository
* %% * %%
* Copyright (C) 2005 - 2024 Alfresco Software Limited * Copyright (C) 2005 - 2025 Alfresco Software Limited
* %% * %%
* This file is part of the Alfresco software. * This file is part of the Alfresco software.
* If the software was purchased under a paid Alfresco license, the terms of * If the software was purchased under a paid Alfresco license, the terms of
@@ -38,12 +38,17 @@ import static org.mockito.MockitoAnnotations.initMocks;
import java.util.Optional; import java.util.Optional;
import com.nimbusds.openid.connect.sdk.claims.PersonClaims; import com.nimbusds.openid.connect.sdk.claims.PersonClaims;
import org.alfresco.service.cmr.security.PersonService;
import org.alfresco.service.transaction.TransactionService;
import org.junit.Before; import org.junit.Before;
import org.junit.Test; import org.junit.Test;
import org.mockito.Answers;
import org.mockito.Mock; import org.mockito.Mock;
import org.springframework.security.oauth2.client.registration.ClientRegistration;
import org.alfresco.repo.security.authentication.identityservice.user.DecodedTokenUser;
import org.alfresco.repo.security.authentication.identityservice.user.OIDCUserInfo;
import org.alfresco.repo.security.authentication.identityservice.user.UserInfoAttrMapping;
import org.alfresco.service.cmr.security.PersonService;
import org.alfresco.service.transaction.TransactionService;
public class IdentityServiceJITProvisioningHandlerUnitTest public class IdentityServiceJITProvisioningHandlerUnitTest
{ {
@@ -51,6 +56,9 @@ public class IdentityServiceJITProvisioningHandlerUnitTest
@Mock @Mock
private IdentityServiceFacade identityServiceFacade; private IdentityServiceFacade identityServiceFacade;
@Mock(answer = Answers.RETURNS_DEEP_STUBS)
private ClientRegistration clientRegistration;
@Mock @Mock
private PersonService personService; private PersonService personService;
@@ -64,11 +72,22 @@ public class IdentityServiceJITProvisioningHandlerUnitTest
private IdentityServiceConfig identityServiceConfig; private IdentityServiceConfig identityServiceConfig;
@Mock @Mock
private OIDCUserInfo userInfo; private DecodedTokenUser decodedTokenUser;
private IdentityServiceJITProvisioningHandler jitProvisioningHandler; private IdentityServiceJITProvisioningHandler jitProvisioningHandler;
private UserInfoAttrMapping expectedMapping;
private static final String JWT_TOKEN = "myToken"; private static final String JWT_TOKEN = "myToken";
private static final String USERNAME = "johny123";
private static final String FIRST_NAME = "John";
private static final String LAST_NAME = "Doe";
private static final String EMAIL = "johny123@email.com";
public static final String USERNAME_CLAIM = "nickname";
public static final String EMAIL_CLAIM = "email";
public static final String FIRST_NAME_CLAIM = "given_name";
public static final String LAST_NAME_CLAIM = "family_name";
@Before @Before
public void setup() public void setup()
@@ -78,149 +97,147 @@ public class IdentityServiceJITProvisioningHandlerUnitTest
when(transactionService.isReadOnly()).thenReturn(false); when(transactionService.isReadOnly()).thenReturn(false);
when(identityServiceFacade.decodeToken(JWT_TOKEN)).thenReturn(decodedAccessToken); when(identityServiceFacade.decodeToken(JWT_TOKEN)).thenReturn(decodedAccessToken);
when(personService.createMissingPeople()).thenReturn(true); when(personService.createMissingPeople()).thenReturn(true);
jitProvisioningHandler = new IdentityServiceJITProvisioningHandler(identityServiceFacade, when(identityServiceFacade.getClientRegistration()).thenReturn(clientRegistration);
personService, transactionService, identityServiceConfig); when(clientRegistration.getProviderDetails().getUserInfoEndpoint().getUserNameAttributeName()).thenReturn(USERNAME_CLAIM);
when(identityServiceConfig.getEmailAttribute()).thenReturn(EMAIL_CLAIM);
when(identityServiceConfig.getFirstNameAttribute()).thenReturn(FIRST_NAME_CLAIM);
when(identityServiceConfig.getLastNameAttribute()).thenReturn(LAST_NAME_CLAIM);
expectedMapping = new UserInfoAttrMapping(USERNAME_CLAIM, FIRST_NAME_CLAIM, LAST_NAME_CLAIM, EMAIL_CLAIM);
jitProvisioningHandler = new IdentityServiceJITProvisioningHandler(identityServiceFacade, personService, transactionService, identityServiceConfig);
} }
@Test @Test
public void shouldExtractUserInfoForExistingUser() public void shouldExtractUserInfoForExistingUser()
{ {
when(personService.personExists("johny123")).thenReturn(true); when(clientRegistration.getProviderDetails().getUserInfoEndpoint().getUserNameAttributeName()).thenReturn(PersonClaims.PREFERRED_USERNAME_CLAIM_NAME);
when(decodedAccessToken.getClaim(PersonClaims.PREFERRED_USERNAME_CLAIM_NAME)).thenReturn("johny123"); when(personService.personExists(USERNAME)).thenReturn(true);
when(decodedAccessToken.getClaim(PersonClaims.PREFERRED_USERNAME_CLAIM_NAME)).thenReturn(USERNAME);
jitProvisioningHandler = new IdentityServiceJITProvisioningHandler(identityServiceFacade, personService, transactionService, identityServiceConfig);
Optional<OIDCUserInfo> result = jitProvisioningHandler.extractUserInfoAndCreateUserIfNeeded( Optional<OIDCUserInfo> result = jitProvisioningHandler.extractUserInfoAndCreateUserIfNeeded(
JWT_TOKEN); JWT_TOKEN);
assertTrue(result.isPresent()); assertTrue(result.isPresent());
assertEquals("johny123", result.get().username()); assertEquals(USERNAME, result.get().username());
assertFalse(result.get().allFieldsNotEmpty()); assertFalse(result.get().allFieldsNotEmpty());
verify(identityServiceFacade, never()).getUserInfo(JWT_TOKEN, PersonClaims.PREFERRED_USERNAME_CLAIM_NAME); verify(identityServiceFacade, never()).getUserInfo(JWT_TOKEN, expectedMapping);
} }
@Test @Test
public void shouldExtractUserInfoForExistingUserWithProviderPrincipalAttribute() public void shouldExtractUserInfoForExistingUserWithProviderPrincipalAttribute()
{ {
when(identityServiceConfig.getPrincipalAttribute()).thenReturn("nickname"); when(identityServiceConfig.getPrincipalAttribute()).thenReturn(USERNAME_CLAIM);
when(personService.personExists("johny123")).thenReturn(true); when(personService.personExists(USERNAME)).thenReturn(true);
when(decodedAccessToken.getClaim("nickname")).thenReturn("johny123"); when(decodedAccessToken.getClaim(USERNAME_CLAIM)).thenReturn(USERNAME);
Optional<OIDCUserInfo> result = jitProvisioningHandler.extractUserInfoAndCreateUserIfNeeded( Optional<OIDCUserInfo> result = jitProvisioningHandler.extractUserInfoAndCreateUserIfNeeded(
JWT_TOKEN); JWT_TOKEN);
assertTrue(result.isPresent()); assertTrue(result.isPresent());
assertEquals("johny123", result.get().username()); assertEquals(USERNAME, result.get().username());
assertFalse(result.get().allFieldsNotEmpty()); assertFalse(result.get().allFieldsNotEmpty());
verify(identityServiceFacade, never()).getUserInfo(JWT_TOKEN, "nickname"); verify(identityServiceFacade, never()).getUserInfo(JWT_TOKEN, expectedMapping);
} }
@Test @Test
public void shouldExtractUserInfoFromAccessTokenAndCreateUser() public void shouldExtractUserInfoFromAccessTokenAndCreateUser()
{ {
when(personService.personExists("johny123")).thenReturn(false); when(clientRegistration.getProviderDetails().getUserInfoEndpoint().getUserNameAttributeName()).thenReturn(PersonClaims.PREFERRED_USERNAME_CLAIM_NAME);
when(personService.personExists(USERNAME)).thenReturn(false);
when(decodedAccessToken.getClaim(PersonClaims.PREFERRED_USERNAME_CLAIM_NAME)).thenReturn("johny123"); when(decodedAccessToken.getClaim(PersonClaims.PREFERRED_USERNAME_CLAIM_NAME)).thenReturn(USERNAME);
when(decodedAccessToken.getClaim(PersonClaims.GIVEN_NAME_CLAIM_NAME)).thenReturn("John"); when(decodedAccessToken.getClaim(PersonClaims.GIVEN_NAME_CLAIM_NAME)).thenReturn(FIRST_NAME);
when(decodedAccessToken.getClaim(PersonClaims.FAMILY_NAME_CLAIM_NAME)).thenReturn("Doe"); when(decodedAccessToken.getClaim(PersonClaims.FAMILY_NAME_CLAIM_NAME)).thenReturn(LAST_NAME);
when(decodedAccessToken.getClaim(PersonClaims.EMAIL_CLAIM_NAME)).thenReturn("johny123@email.com"); when(decodedAccessToken.getClaim(PersonClaims.EMAIL_CLAIM_NAME)).thenReturn(EMAIL);
jitProvisioningHandler = new IdentityServiceJITProvisioningHandler(identityServiceFacade, personService, transactionService, identityServiceConfig);
Optional<OIDCUserInfo> result = jitProvisioningHandler.extractUserInfoAndCreateUserIfNeeded( Optional<OIDCUserInfo> result = jitProvisioningHandler.extractUserInfoAndCreateUserIfNeeded(
JWT_TOKEN); JWT_TOKEN);
assertTrue(result.isPresent()); assertTrue(result.isPresent());
assertEquals("johny123", result.get().username()); assertEquals(USERNAME, result.get().username());
assertEquals("John", result.get().firstName()); assertEquals(FIRST_NAME, result.get().firstName());
assertEquals("Doe", result.get().lastName()); assertEquals(LAST_NAME, result.get().lastName());
assertEquals("johny123@email.com", result.get().email()); assertEquals(EMAIL, result.get().email());
assertTrue(result.get().allFieldsNotEmpty()); assertTrue(result.get().allFieldsNotEmpty());
verify(personService).createPerson(any()); verify(personService).createPerson(any());
verify(identityServiceFacade, never()).getUserInfo(JWT_TOKEN, PersonClaims.PREFERRED_USERNAME_CLAIM_NAME); verify(identityServiceFacade, never()).getUserInfo(JWT_TOKEN, expectedMapping);
} }
@Test @Test
public void shouldExtractUserInfoFromUserInfoEndpointAndCreateUser() public void shouldExtractUserInfoFromUserInfoEndpointAndCreateUser()
{ {
when(userInfo.username()).thenReturn("johny123"); when(decodedTokenUser.username()).thenReturn(USERNAME);
when(userInfo.firstName()).thenReturn("John"); when(decodedTokenUser.firstName()).thenReturn(FIRST_NAME);
when(userInfo.lastName()).thenReturn("Doe"); when(decodedTokenUser.lastName()).thenReturn(LAST_NAME);
when(userInfo.email()).thenReturn("johny123@email.com"); when(decodedTokenUser.email()).thenReturn(EMAIL);
when(personService.personExists(USERNAME)).thenReturn(false);
when(personService.personExists("johny123")).thenReturn(false); when(decodedAccessToken.getClaim(PersonClaims.PREFERRED_USERNAME_CLAIM_NAME)).thenReturn(USERNAME);
when(identityServiceFacade.getUserInfo(JWT_TOKEN, expectedMapping)).thenReturn(Optional.of(decodedTokenUser));
when(decodedAccessToken.getClaim(PersonClaims.PREFERRED_USERNAME_CLAIM_NAME)).thenReturn("johny123");
when(identityServiceFacade.getUserInfo(JWT_TOKEN, PersonClaims.PREFERRED_USERNAME_CLAIM_NAME)).thenReturn(Optional.of(userInfo));
Optional<OIDCUserInfo> result = jitProvisioningHandler.extractUserInfoAndCreateUserIfNeeded( Optional<OIDCUserInfo> result = jitProvisioningHandler.extractUserInfoAndCreateUserIfNeeded(
JWT_TOKEN); JWT_TOKEN);
assertTrue(result.isPresent()); assertTrue(result.isPresent());
assertEquals("johny123", result.get().username()); assertEquals(USERNAME, result.get().username());
assertEquals("John", result.get().firstName()); assertEquals(FIRST_NAME, result.get().firstName());
assertEquals("Doe", result.get().lastName()); assertEquals(LAST_NAME, result.get().lastName());
assertEquals("johny123@email.com", result.get().email()); assertEquals(EMAIL, result.get().email());
assertTrue(result.get().allFieldsNotEmpty()); assertTrue(result.get().allFieldsNotEmpty());
verify(personService).createPerson(any()); verify(personService).createPerson(any());
verify(identityServiceFacade).getUserInfo(JWT_TOKEN, PersonClaims.PREFERRED_USERNAME_CLAIM_NAME); verify(identityServiceFacade).getUserInfo(JWT_TOKEN, expectedMapping);
} }
@Test @Test
public void shouldReturnEmptyOptionalIfUsernameNotExtracted() public void shouldReturnEmptyOptionalIfUsernameNotExtracted()
{ {
when(identityServiceFacade.getUserInfo(JWT_TOKEN, expectedMapping)).thenReturn(Optional.of(decodedTokenUser));
when(identityServiceFacade.getUserInfo(JWT_TOKEN, PersonClaims.PREFERRED_USERNAME_CLAIM_NAME)).thenReturn(Optional.of(userInfo));
Optional<OIDCUserInfo> result = jitProvisioningHandler.extractUserInfoAndCreateUserIfNeeded( Optional<OIDCUserInfo> result = jitProvisioningHandler.extractUserInfoAndCreateUserIfNeeded(
JWT_TOKEN); JWT_TOKEN);
assertFalse(result.isPresent()); assertFalse(result.isPresent());
verify(personService, never()).createPerson(any()); verify(personService, never()).createPerson(any());
verify(identityServiceFacade).getUserInfo(JWT_TOKEN, PersonClaims.PREFERRED_USERNAME_CLAIM_NAME); verify(identityServiceFacade).getUserInfo(JWT_TOKEN, expectedMapping);
} }
@Test @Test
public void shouldCallUserInfoEndpointToGetUsername() public void shouldCallUserInfoEndpointToGetUsername()
{ {
when(personService.personExists("johny123")).thenReturn(true); when(personService.personExists(USERNAME)).thenReturn(true);
when(decodedAccessToken.getClaim(PersonClaims.PREFERRED_USERNAME_CLAIM_NAME)).thenReturn(""); when(decodedAccessToken.getClaim(PersonClaims.PREFERRED_USERNAME_CLAIM_NAME)).thenReturn("");
when(identityServiceFacade.getUserInfo(JWT_TOKEN, expectedMapping)).thenReturn(Optional.of(DecodedTokenUser.validateAndCreate(USERNAME, null, null, null)));
when(userInfo.username()).thenReturn("johny123");
when(identityServiceFacade.getUserInfo(JWT_TOKEN, PersonClaims.PREFERRED_USERNAME_CLAIM_NAME)).thenReturn(Optional.of(userInfo));
Optional<OIDCUserInfo> result = jitProvisioningHandler.extractUserInfoAndCreateUserIfNeeded( Optional<OIDCUserInfo> result = jitProvisioningHandler.extractUserInfoAndCreateUserIfNeeded(
JWT_TOKEN); JWT_TOKEN);
assertTrue(result.isPresent()); assertTrue(result.isPresent());
assertEquals("johny123", result.get().username()); assertEquals(USERNAME, result.get().username());
assertEquals("", result.get().firstName()); assertEquals("", result.get().firstName());
assertEquals("", result.get().lastName()); assertEquals("", result.get().lastName());
assertEquals("", result.get().email()); assertEquals("", result.get().email());
assertFalse(result.get().allFieldsNotEmpty()); assertFalse(result.get().allFieldsNotEmpty());
verify(personService, never()).createPerson(any()); verify(personService, never()).createPerson(any());
verify(identityServiceFacade).getUserInfo(JWT_TOKEN, PersonClaims.PREFERRED_USERNAME_CLAIM_NAME); verify(identityServiceFacade).getUserInfo(JWT_TOKEN, expectedMapping);
} }
@Test @Test
public void shouldCallUserInfoEndpointToGetUsernameWithProvidedPrincipalAttribute() public void shouldCallUserInfoEndpointToGetUsernameWithProvidedPrincipalAttribute()
{ {
when(identityServiceConfig.getPrincipalAttribute()).thenReturn("nickname"); when(identityServiceConfig.getPrincipalAttribute()).thenReturn(USERNAME_CLAIM);
when(personService.personExists("johny123")).thenReturn(true); when(personService.personExists(USERNAME)).thenReturn(true);
when(decodedAccessToken.getClaim(USERNAME_CLAIM)).thenReturn("");
when(decodedAccessToken.getClaim("nickname")).thenReturn(""); when(identityServiceFacade.getUserInfo(JWT_TOKEN, expectedMapping)).thenReturn(Optional.of(DecodedTokenUser.validateAndCreate(USERNAME, null, null, null)));
when(userInfo.username()).thenReturn("johny123");
when(identityServiceFacade.getUserInfo(JWT_TOKEN, "nickname")).thenReturn(Optional.of(userInfo));
Optional<OIDCUserInfo> result = jitProvisioningHandler.extractUserInfoAndCreateUserIfNeeded( Optional<OIDCUserInfo> result = jitProvisioningHandler.extractUserInfoAndCreateUserIfNeeded(
JWT_TOKEN); JWT_TOKEN);
assertTrue(result.isPresent()); assertTrue(result.isPresent());
assertEquals("johny123", result.get().username()); assertEquals(USERNAME, result.get().username());
assertEquals("", result.get().firstName()); assertEquals("", result.get().firstName());
assertEquals("", result.get().lastName()); assertEquals("", result.get().lastName());
assertEquals("", result.get().email()); assertEquals("", result.get().email());
assertFalse(result.get().allFieldsNotEmpty()); assertFalse(result.get().allFieldsNotEmpty());
verify(personService, never()).createPerson(any()); verify(personService, never()).createPerson(any());
verify(identityServiceFacade).getUserInfo(JWT_TOKEN, "nickname"); verify(identityServiceFacade).getUserInfo(JWT_TOKEN, expectedMapping);
} }
@Test @Test
@@ -232,8 +249,8 @@ public class IdentityServiceJITProvisioningHandlerUnitTest
verify(personService, never()).createPerson(any()); verify(personService, never()).createPerson(any());
verify(identityServiceFacade, never()).decodeToken(null); verify(identityServiceFacade, never()).decodeToken(null);
verify(identityServiceFacade, never()).decodeToken(""); verify(identityServiceFacade, never()).decodeToken("");
verify(identityServiceFacade, never()).getUserInfo(null, PersonClaims.PREFERRED_USERNAME_CLAIM_NAME); verify(identityServiceFacade, never()).getUserInfo(null, expectedMapping);
verify(identityServiceFacade, never()).getUserInfo("", PersonClaims.PREFERRED_USERNAME_CLAIM_NAME); verify(identityServiceFacade, never()).getUserInfo(null, expectedMapping);
} }
} }

View File

@@ -2,7 +2,7 @@
* #%L * #%L
* Alfresco Repository * Alfresco Repository
* %% * %%
* Copyright (C) 2005 - 2024 Alfresco Software Limited * Copyright (C) 2005 - 2025 Alfresco Software Limited
* %% * %%
* This file is part of the Alfresco software. * This file is part of the Alfresco software.
* If the software was purchased under a paid Alfresco license, the terms of * If the software was purchased under a paid Alfresco license, the terms of
@@ -34,17 +34,18 @@ import java.time.Instant;
import java.util.Map; import java.util.Map;
import java.util.Vector; import java.util.Vector;
import java.util.function.Supplier; import java.util.function.Supplier;
import jakarta.servlet.http.HttpServletRequest;
import com.nimbusds.openid.connect.sdk.claims.PersonClaims; import com.nimbusds.openid.connect.sdk.claims.PersonClaims;
import jakarta.servlet.http.HttpServletRequest;
import junit.framework.TestCase; import junit.framework.TestCase;
import org.mockito.Mockito;
import org.springframework.security.oauth2.server.resource.web.DefaultBearerTokenResolver;
import org.alfresco.repo.security.authentication.AuthenticationException; import org.alfresco.repo.security.authentication.AuthenticationException;
import org.alfresco.repo.security.authentication.identityservice.IdentityServiceFacade.DecodedAccessToken; import org.alfresco.repo.security.authentication.identityservice.IdentityServiceFacade.DecodedAccessToken;
import org.alfresco.repo.security.authentication.identityservice.IdentityServiceFacade.TokenDecodingException; import org.alfresco.repo.security.authentication.identityservice.IdentityServiceFacade.TokenDecodingException;
import org.alfresco.service.cmr.security.PersonService; import org.alfresco.service.cmr.security.PersonService;
import org.alfresco.service.transaction.TransactionService; import org.alfresco.service.transaction.TransactionService;
import org.springframework.security.oauth2.server.resource.web.DefaultBearerTokenResolver;
/** /**
* Tests the Identity Service based authentication subsystem. * Tests the Identity Service based authentication subsystem.
@@ -68,7 +69,9 @@ public class IdentityServiceRemoteUserMapperTest extends TestCase
public void testWrongTokenWithSilentValidation() public void testWrongTokenWithSilentValidation()
{ {
final IdentityServiceRemoteUserMapper mapper = givenMapper(Map.of("WrOnG-ToKeN", () -> {throw new TokenDecodingException("Expected ");})); final IdentityServiceRemoteUserMapper mapper = givenMapper(Map.of("WrOnG-ToKeN", () -> {
throw new TokenDecodingException("Expected ");
}));
mapper.setValidationFailureSilent(true); mapper.setValidationFailureSilent(true);
HttpServletRequest mockRequest = createMockTokenRequest("WrOnG-ToKeN"); HttpServletRequest mockRequest = createMockTokenRequest("WrOnG-ToKeN");
@@ -79,7 +82,9 @@ public class IdentityServiceRemoteUserMapperTest extends TestCase
public void testWrongTokenWithoutSilentValidation() public void testWrongTokenWithoutSilentValidation()
{ {
final IdentityServiceRemoteUserMapper mapper = givenMapper(Map.of("WrOnG-ToKeN", () -> {throw new TokenDecodingException("Expected");})); final IdentityServiceRemoteUserMapper mapper = givenMapper(Map.of("WrOnG-ToKeN", () -> {
throw new TokenDecodingException("Expected");
}));
mapper.setValidationFailureSilent(false); mapper.setValidationFailureSilent(false);
HttpServletRequest mockRequest = createMockTokenRequest("WrOnG-ToKeN"); HttpServletRequest mockRequest = createMockTokenRequest("WrOnG-ToKeN");
@@ -92,12 +97,14 @@ public class IdentityServiceRemoteUserMapperTest extends TestCase
private IdentityServiceRemoteUserMapper givenMapper(Map<String, Supplier<String>> tokenToUser) private IdentityServiceRemoteUserMapper givenMapper(Map<String, Supplier<String>> tokenToUser)
{ {
final TransactionService transactionService = mock(TransactionService.class); final TransactionService transactionService = mock(TransactionService.class);
final IdentityServiceFacade facade = mock(IdentityServiceFacade.class); final IdentityServiceFacade facade = mock(IdentityServiceFacade.class, Mockito.RETURNS_DEEP_STUBS);
final PersonService personService = mock(PersonService.class); final PersonService personService = mock(PersonService.class);
final IdentityServiceConfig identityServiceConfig = mock(IdentityServiceConfig.class); final IdentityServiceConfig identityServiceConfig = mock(IdentityServiceConfig.class);
when(transactionService.isReadOnly()).thenReturn(true); when(transactionService.isReadOnly()).thenReturn(true);
when(facade.decodeToken(anyString())) when(facade.decodeToken(anyString()))
.thenAnswer(i -> new TestDecodedToken(tokenToUser.get(i.getArgument(0, String.class)))); .thenAnswer(i -> new TestDecodedToken(tokenToUser.get(i.getArgument(0, String.class))));
when(facade.getClientRegistration().getProviderDetails().getUserInfoEndpoint().getUserNameAttributeName())
.thenReturn(PersonClaims.PREFERRED_USERNAME_CLAIM_NAME);
when(personService.getUserIdentifier(anyString())).thenAnswer(i -> i.getArgument(0, String.class)); when(personService.getUserIdentifier(anyString())).thenAnswer(i -> i.getArgument(0, String.class));
@@ -108,14 +115,14 @@ public class IdentityServiceRemoteUserMapperTest extends TestCase
mapper.setActive(true); mapper.setActive(true);
mapper.setBearerTokenResolver(new DefaultBearerTokenResolver()); mapper.setBearerTokenResolver(new DefaultBearerTokenResolver());
return mapper; return mapper;
} }
/** /**
* Utility method for creating a mocked Servlet request with a token. * Utility method for creating a mocked Servlet request with a token.
* *
* @param token The token to add to the Authorization header * @param token
* The token to add to the Authorization header
* @return The mocked request object * @return The mocked request object
*/ */
private HttpServletRequest createMockTokenRequest(String token) private HttpServletRequest createMockTokenRequest(String token)

View File

@@ -2,7 +2,7 @@
* #%L * #%L
* Alfresco Repository * Alfresco Repository
* %% * %%
* Copyright (C) 2005 - 2024 Alfresco Software Limited * Copyright (C) 2005 - 2025 Alfresco Software Limited
* %% * %%
* This file is part of the Alfresco software. * This file is part of the Alfresco software.
* If the software was purchased under a paid Alfresco license, the terms of * If the software was purchased under a paid Alfresco license, the terms of
@@ -31,20 +31,23 @@ import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when; import static org.mockito.Mockito.when;
import org.alfresco.repo.security.authentication.identityservice.IdentityServiceFacade.AuthorizationException;
import org.alfresco.repo.security.authentication.identityservice.IdentityServiceFacade.AuthorizationGrant;
import org.alfresco.repo.security.authentication.identityservice.IdentityServiceFacade.TokenDecodingException;
import org.junit.Test; import org.junit.Test;
import org.springframework.security.oauth2.client.registration.ClientRegistration; import org.springframework.security.oauth2.client.registration.ClientRegistration;
import org.springframework.security.oauth2.core.AuthorizationGrantType; import org.springframework.security.oauth2.core.AuthorizationGrantType;
import org.springframework.security.oauth2.jwt.JwtDecoder; import org.springframework.security.oauth2.jwt.JwtDecoder;
import org.springframework.web.client.RestOperations; import org.springframework.web.client.RestOperations;
import org.alfresco.repo.security.authentication.identityservice.IdentityServiceFacade.AuthorizationException;
import org.alfresco.repo.security.authentication.identityservice.IdentityServiceFacade.AuthorizationGrant;
import org.alfresco.repo.security.authentication.identityservice.IdentityServiceFacade.TokenDecodingException;
import org.alfresco.repo.security.authentication.identityservice.user.UserInfoAttrMapping;
public class SpringBasedIdentityServiceFacadeUnitTest public class SpringBasedIdentityServiceFacadeUnitTest
{ {
private static final String USER_NAME = "user"; private static final String USER_NAME = "user";
private static final String PASSWORD = "password"; private static final String PASSWORD = "password";
private static final String TOKEN = "tEsT-tOkEn"; private static final String TOKEN = "tEsT-tOkEn";
private static final UserInfoAttrMapping USER_INFO_ATTR_MAPPING = new UserInfoAttrMapping("preferred_username", "given_name", "family_name", "email");
@Test @Test
public void shouldThrowVerificationExceptionOnFailure() public void shouldThrowVerificationExceptionOnFailure()
@@ -74,7 +77,6 @@ public class SpringBasedIdentityServiceFacadeUnitTest
.havingCause().withNoCause().withMessage("Expected"); .havingCause().withNoCause().withMessage("Expected");
} }
@Test @Test
public void shouldReturnEmptyOptionalOnFailure() public void shouldReturnEmptyOptionalOnFailure()
{ {
@@ -82,8 +84,7 @@ public class SpringBasedIdentityServiceFacadeUnitTest
final JwtDecoder jwtDecoder = mock(JwtDecoder.class); final JwtDecoder jwtDecoder = mock(JwtDecoder.class);
final SpringBasedIdentityServiceFacade facade = new SpringBasedIdentityServiceFacade(restOperations, testRegistration(), jwtDecoder); final SpringBasedIdentityServiceFacade facade = new SpringBasedIdentityServiceFacade(restOperations, testRegistration(), jwtDecoder);
assertThat(facade.getUserInfo(TOKEN, USER_INFO_ATTR_MAPPING).isEmpty()).isTrue();
assertThat(facade.getUserInfo(TOKEN, "preferred_username").isEmpty()).isTrue();
} }
private ClientRegistration testRegistration() private ClientRegistration testRegistration()

View File

@@ -2,7 +2,7 @@
* #%L * #%L
* Alfresco Repository * Alfresco Repository
* %% * %%
* Copyright (C) 2005 - 2024 Alfresco Software Limited * Copyright (C) 2005 - 2025 Alfresco Software Limited
* %% * %%
* This file is part of the Alfresco software. * This file is part of the Alfresco software.
* If the software was purchased under a paid Alfresco license, the terms of * If the software was purchased under a paid Alfresco license, the terms of
@@ -38,18 +38,11 @@ import java.io.IOException;
import java.time.Instant; import java.time.Instant;
import java.util.Arrays; import java.util.Arrays;
import java.util.Map; import java.util.Map;
import java.util.Set;
import com.nimbusds.oauth2.sdk.Scope;
import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse; import jakarta.servlet.http.HttpServletResponse;
import org.alfresco.repo.security.authentication.external.RemoteUserMapper;
import org.alfresco.repo.security.authentication.identityservice.IdentityServiceConfig; import com.nimbusds.oauth2.sdk.Scope;
import org.alfresco.repo.security.authentication.identityservice.IdentityServiceFacade;
import org.alfresco.repo.security.authentication.identityservice.IdentityServiceFacade.AccessToken;
import org.alfresco.repo.security.authentication.identityservice.IdentityServiceFacade.AccessTokenAuthorization;
import org.alfresco.repo.security.authentication.identityservice.IdentityServiceFacade.AuthorizationException;
import org.alfresco.repo.security.authentication.identityservice.IdentityServiceFacade.AuthorizationGrant;
import org.junit.Before; import org.junit.Before;
import org.junit.Test; import org.junit.Test;
import org.mockito.ArgumentCaptor; import org.mockito.ArgumentCaptor;
@@ -58,6 +51,14 @@ import org.mockito.Mock;
import org.springframework.security.oauth2.client.registration.ClientRegistration; import org.springframework.security.oauth2.client.registration.ClientRegistration;
import org.springframework.security.oauth2.client.registration.ClientRegistration.ProviderDetails; import org.springframework.security.oauth2.client.registration.ClientRegistration.ProviderDetails;
import org.alfresco.repo.security.authentication.external.RemoteUserMapper;
import org.alfresco.repo.security.authentication.identityservice.IdentityServiceConfig;
import org.alfresco.repo.security.authentication.identityservice.IdentityServiceFacade;
import org.alfresco.repo.security.authentication.identityservice.IdentityServiceFacade.AccessToken;
import org.alfresco.repo.security.authentication.identityservice.IdentityServiceFacade.AccessTokenAuthorization;
import org.alfresco.repo.security.authentication.identityservice.IdentityServiceFacade.AuthorizationException;
import org.alfresco.repo.security.authentication.identityservice.IdentityServiceFacade.AuthorizationGrant;
@SuppressWarnings("PMD.AvoidStringBufferField") @SuppressWarnings("PMD.AvoidStringBufferField")
public class IdentityServiceAdminConsoleAuthenticatorUnitTest public class IdentityServiceAdminConsoleAuthenticatorUnitTest
{ {
@@ -155,6 +156,7 @@ public class IdentityServiceAdminConsoleAuthenticatorUnitTest
{ {
String redirectPath = "/alfresco/s/admin/admin-communitysummary"; String redirectPath = "/alfresco/s/admin/admin-communitysummary";
when(identityServiceConfig.getAdminConsoleScopes()).thenReturn(Set.of("openid", "email", "profile", "offline_access"));
when(identityServiceConfig.getAdminConsoleRedirectPath()).thenReturn("/alfresco/s/admin/admin-communitysummary"); when(identityServiceConfig.getAdminConsoleRedirectPath()).thenReturn("/alfresco/s/admin/admin-communitysummary");
ArgumentCaptor<String> authenticationRequest = ArgumentCaptor.forClass(String.class); ArgumentCaptor<String> authenticationRequest = ArgumentCaptor.forClass(String.class);
String expectedUri = "http://localhost:8999/auth?client_id=alfresco&redirect_uri=%s%s&response_type=code&scope=" String expectedUri = "http://localhost:8999/auth?client_id=alfresco&redirect_uri=%s%s&response_type=code&scope="
@@ -178,6 +180,7 @@ public class IdentityServiceAdminConsoleAuthenticatorUnitTest
String redirectPath = "/alfresco/s/admin/admin-communitysummary"; String redirectPath = "/alfresco/s/admin/admin-communitysummary";
when(identityServiceConfig.getAudience()).thenReturn(audience); when(identityServiceConfig.getAudience()).thenReturn(audience);
when(identityServiceConfig.getAdminConsoleRedirectPath()).thenReturn(redirectPath); when(identityServiceConfig.getAdminConsoleRedirectPath()).thenReturn(redirectPath);
when(identityServiceConfig.getAdminConsoleScopes()).thenReturn(Set.of("openid", "email", "profile", "offline_access"));
ArgumentCaptor<String> authenticationRequest = ArgumentCaptor.forClass(String.class); ArgumentCaptor<String> authenticationRequest = ArgumentCaptor.forClass(String.class);
String expectedUri = "http://localhost:8999/auth?client_id=alfresco&redirect_uri=%s%s&response_type=code&scope=" String expectedUri = "http://localhost:8999/auth?client_id=alfresco&redirect_uri=%s%s&response_type=code&scope="
.formatted("http://localhost:8080", redirectPath); .formatted("http://localhost:8080", redirectPath);

View File

@@ -0,0 +1,109 @@
/*
* #%L
* Alfresco Repository
* %%
* Copyright (C) 2005 - 2025 Alfresco Software Limited
* %%
* This file is part of the Alfresco software.
* If the software was purchased under a paid Alfresco license, the terms of
* the paid license agreement will prevail. Otherwise, the software is
* provided under the following open source license terms:
*
* Alfresco is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Alfresco is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
* #L%
*/
package org.alfresco.repo.security.authentication.identityservice.user;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.when;
import static org.mockito.MockitoAnnotations.initMocks;
import java.util.Optional;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.alfresco.repo.security.authentication.identityservice.IdentityServiceFacade;
public class AccessTokenToDecodedTokenUserMapperUnitTest
{
@Mock
private IdentityServiceFacade.DecodedAccessToken decodedAccessToken;
private AccessTokenToDecodedTokenUserMapper tokenToDecodedTokenUserMapper;
public static final String USERNAME_CLAIM = "nickname";
public static final String EMAIL_CLAIM = "email";
public static final String FIRST_NAME_CLAIM = "given_name";
public static final String LAST_NAME_CLAIM = "family_name";
@Before
public void setup()
{
initMocks(this);
UserInfoAttrMapping userInfoAttrMapping = new UserInfoAttrMapping(USERNAME_CLAIM, FIRST_NAME_CLAIM, LAST_NAME_CLAIM, EMAIL_CLAIM);
tokenToDecodedTokenUserMapper = new AccessTokenToDecodedTokenUserMapper(userInfoAttrMapping);
}
@Test
public void shouldMapToDecodedTokenUserWithAllFieldsPopulated()
{
when(decodedAccessToken.getClaim(USERNAME_CLAIM)).thenReturn("johny123");
when(decodedAccessToken.getClaim(FIRST_NAME_CLAIM)).thenReturn("John");
when(decodedAccessToken.getClaim(LAST_NAME_CLAIM)).thenReturn("Doe");
when(decodedAccessToken.getClaim(EMAIL_CLAIM)).thenReturn("johny123@email.com");
Optional<DecodedTokenUser> result = tokenToDecodedTokenUserMapper.toDecodedTokenUser(decodedAccessToken);
assertTrue(result.isPresent());
assertEquals("johny123", result.get().username());
assertEquals("John", result.get().firstName());
assertEquals("Doe", result.get().lastName());
assertEquals("johny123@email.com", result.get().email());
}
@Test
public void shouldMapToDecodedTokenUserWithSomeFieldsEmpty()
{
when(decodedAccessToken.getClaim(USERNAME_CLAIM)).thenReturn("johny123");
when(decodedAccessToken.getClaim(FIRST_NAME_CLAIM)).thenReturn("");
when(decodedAccessToken.getClaim(LAST_NAME_CLAIM)).thenReturn("Doe");
when(decodedAccessToken.getClaim(EMAIL_CLAIM)).thenReturn("");
Optional<DecodedTokenUser> result = tokenToDecodedTokenUserMapper.toDecodedTokenUser(decodedAccessToken);
assertTrue(result.isPresent());
assertEquals("johny123", result.get().username());
assertEquals("", result.get().firstName());
assertEquals("Doe", result.get().lastName());
assertEquals("", result.get().email());
}
@Test
public void shouldReturnEmptyOptionalForNullUsername()
{
when(decodedAccessToken.getClaim(USERNAME_CLAIM)).thenReturn(null);
when(decodedAccessToken.getClaim(FIRST_NAME_CLAIM)).thenReturn("John");
when(decodedAccessToken.getClaim(LAST_NAME_CLAIM)).thenReturn("Doe");
when(decodedAccessToken.getClaim(EMAIL_CLAIM)).thenReturn("johny123@email.com");
Optional<DecodedTokenUser> result = tokenToDecodedTokenUserMapper.toDecodedTokenUser(decodedAccessToken);
assertFalse(result.isPresent());
}
}

View File

@@ -0,0 +1,95 @@
/*
* #%L
* Alfresco Repository
* %%
* Copyright (C) 2005 - 2025 Alfresco Software Limited
* %%
* This file is part of the Alfresco software.
* If the software was purchased under a paid Alfresco license, the terms of
* the paid license agreement will prevail. Otherwise, the software is
* provided under the following open source license terms:
*
* Alfresco is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Alfresco is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
* #L%
*/
package org.alfresco.repo.security.authentication.identityservice.user;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.mockito.Mockito.when;
import static org.mockito.MockitoAnnotations.initMocks;
import org.junit.Before;
import org.junit.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.alfresco.service.cmr.security.PersonService;
public class TokenUserToOIDCUserMapperUnitTest
{
@Mock
private PersonService personService;
@InjectMocks
private TokenUserToOIDCUserMapper tokenUserToOIDCUserMapper;
@Before
public void setup()
{
initMocks(this);
}
@Test
public void shouldMapToOIDCUserWithAllFieldsPopulated()
{
DecodedTokenUser decodedTokenUser = new DecodedTokenUser("JOHNY123", "John", "Doe", "johny123@email.com");
when(personService.getUserIdentifier("JOHNY123")).thenReturn("johny123");
OIDCUserInfo oidcUserInfo = tokenUserToOIDCUserMapper.toOIDCUser(decodedTokenUser);
assertEquals("johny123", oidcUserInfo.username());
assertEquals("John", oidcUserInfo.firstName());
assertEquals("Doe", oidcUserInfo.lastName());
assertEquals("johny123@email.com", oidcUserInfo.email());
}
@Test
public void shouldMapToOIDCUserWithSomeFieldsEmpty()
{
DecodedTokenUser decodedTokenUser = new DecodedTokenUser("johny123", "", "Doe", "");
when(personService.getUserIdentifier("johny123")).thenReturn("johny123");
OIDCUserInfo oidcUserInfo = tokenUserToOIDCUserMapper.toOIDCUser(decodedTokenUser);
assertEquals("johny123", oidcUserInfo.username());
assertEquals("", oidcUserInfo.firstName());
assertEquals("Doe", oidcUserInfo.lastName());
assertEquals("", oidcUserInfo.email());
}
@Test
public void shouldReturnNullForNullUsername()
{
DecodedTokenUser decodedTokenUser = new DecodedTokenUser(null, "John", "Doe", "johny123@email.com");
OIDCUserInfo oidcUserInfo = tokenUserToOIDCUserMapper.toOIDCUser(decodedTokenUser);
assertNull(oidcUserInfo.username());
assertEquals("John", oidcUserInfo.firstName());
assertEquals("Doe", oidcUserInfo.lastName());
assertEquals("johny123@email.com", oidcUserInfo.email());
}
}

View File

@@ -28,6 +28,9 @@ identity-service.register-node-at-startup=true
identity-service.register-node-period=50 identity-service.register-node-period=50
identity-service.token-store=SESSION identity-service.token-store=SESSION
identity-service.principal-attribute=preferred_username identity-service.principal-attribute=preferred_username
identity-service.first-name-attribute=given_name
identity-service.last-name-attribute=family_name
identity-service.email-attribute=email
identity-service.turn-off-change-session-id-on-login=true identity-service.turn-off-change-session-id-on-login=true
identity-service.token-minimum-time-to-live=10 identity-service.token-minimum-time-to-live=10
identity-service.min-time-between-jwks-requests=60 identity-service.min-time-between-jwks-requests=60