Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add OidcAuthenticationCustomizer service provider interface #755

Draft
wants to merge 4 commits into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions alpine-common/src/main/java/alpine/Config.java
Original file line number Diff line number Diff line change
Expand Up @@ -168,6 +168,7 @@ public enum AlpineKey implements Key {
OIDC_TEAM_SYNCHRONIZATION ("alpine.oidc.team.synchronization", false),
OIDC_TEAMS_CLAIM ("alpine.oidc.teams.claim", "groups"),
OIDC_TEAMS_DEFAULT ("alpine.oidc.teams.default", null),
OIDC_AUTH_CUSTOMIZER ("alpine.oidc.auth.customizer", "alpine.server.auth.DefaultOidcAuthenticationCustomizer"),
HTTP_PROXY_ADDRESS ("alpine.http.proxy.address", null),
HTTP_PROXY_PORT ("alpine.http.proxy.port", null),
HTTP_PROXY_USERNAME ("alpine.http.proxy.username", null),
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
/*
* This file is part of Alpine.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* SPDX-License-Identifier: Apache-2.0
* Copyright (c) Steve Springett. All Rights Reserved.
*/

package alpine.server.auth;

import net.minidev.json.JSONObject;

import alpine.Config;

import com.nimbusds.openid.connect.sdk.claims.ClaimsSet;
import com.nimbusds.openid.connect.sdk.claims.UserInfo;

public class DefaultOidcAuthenticationCustomizer implements OidcAuthenticationCustomizer {

public DefaultOidcAuthenticationCustomizer() {

}

public OidcProfile createProfile(ClaimsSet claimsSet) {
final String teamsClaimName = Config.getInstance().getProperty(Config.AlpineKey.OIDC_TEAMS_CLAIM);
final String usernameClaimName = Config.getInstance().getProperty(Config.AlpineKey.OIDC_USERNAME_CLAIM);
final var profile = new OidcProfile();

profile.setSubject(claimsSet.getStringClaim(UserInfo.SUB_CLAIM_NAME));
profile.setUsername(claimsSet.getStringClaim(usernameClaimName));
profile.setGroups(claimsSet.getStringListClaim(teamsClaimName));
profile.setEmail(claimsSet.getStringClaim(UserInfo.EMAIL_CLAIM_NAME));

JSONObject claimsObj = claimsSet.toJSONObject();
claimsObj.remove(UserInfo.EMAIL_CLAIM_NAME);
claimsObj.remove(UserInfo.SUB_CLAIM_NAME);
claimsObj.remove(teamsClaimName);
claimsObj.remove(usernameClaimName);

profile.setCustomValues(claimsObj);

return profile;
}

public boolean isProfileComplete(final OidcProfile profile, final boolean teamSyncEnabled) {
return profile.getSubject() != null && profile.getUsername() != null
&& (!teamSyncEnabled || (profile.getGroups() != null));
}

public OidcProfile mergeProfiles(final OidcProfile left, final OidcProfile right) {
final var profile = new OidcProfile();

profile.setSubject(selectProfileClaim(left.getSubject(), right.getSubject()));
profile.setUsername(selectProfileClaim(left.getUsername(), right.getUsername()));
profile.setGroups(selectProfileClaim(left.getGroups(), right.getGroups()));
profile.setEmail(selectProfileClaim(left.getEmail(), right.getEmail()));

JSONObject customValues = left.getCustomValues();
customValues.merge(right.getCustomValues());
profile.setCustomValues(customValues);

return profile;
}

public void onAuthenticationSuccess(OidcProfile profile, String idToken, String accessToken) {

}

private <T> T selectProfileClaim(final T left, final T right) {
return (left != null) ? left : right;
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
/*
* This file is part of Alpine.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* SPDX-License-Identifier: Apache-2.0
* Copyright (c) Steve Springett. All Rights Reserved.
*/

package alpine.server.auth;

import com.nimbusds.openid.connect.sdk.claims.ClaimsSet;

public interface OidcAuthenticationCustomizer {

OidcProfile createProfile(ClaimsSet claimsSet);

boolean isProfileComplete(OidcProfile profile, boolean teamSyncEnabled);

OidcProfile mergeProfiles(OidcProfile left, OidcProfile right);

void onAuthenticationSuccess(OidcProfile profile, String idToken, String accessToken);

}
Original file line number Diff line number Diff line change
Expand Up @@ -24,12 +24,12 @@
import alpine.model.OidcUser;
import alpine.persistence.AlpineQueryManager;
import alpine.server.util.OidcUtil;
import com.nimbusds.openid.connect.sdk.claims.UserInfo;

import jakarta.annotation.Nonnull;
import java.security.Principal;
import java.util.List;
import java.util.Objects;
import java.util.ServiceLoader;

/**
* @since 1.8.0
Expand All @@ -44,6 +44,7 @@ public class OidcAuthenticationService implements AuthenticationService {
private final OidcUserInfoAuthenticator userInfoAuthenticator;
private final String idToken;
private final String accessToken;
private final OidcAuthenticationCustomizer customizer;

/**
* @param accessToken The access token acquired by authenticating with an IdP
Expand Down Expand Up @@ -87,6 +88,14 @@ public OidcAuthenticationService(final String idToken, final String accessToken)
this.userInfoAuthenticator = userInfoAuthenticator;
this.idToken = idToken;
this.accessToken = accessToken;

String customizerClassName = Config.getInstance().getProperty(Config.AlpineKey.OIDC_AUTH_CUSTOMIZER);
this.customizer = ServiceLoader.load(OidcAuthenticationCustomizer.class)
.stream()
.filter(provider -> provider.type().getName().equals(customizerClassName))
.map(ServiceLoader.Provider::get)
.findFirst()
.orElseThrow(IllegalStateException::new);
}

@Override
Expand Down Expand Up @@ -127,20 +136,15 @@ public Principal authenticate() throws AlpineAuthenticationException {
}

final OidcProfileCreator profileCreator = claims -> {
final var profile = new OidcProfile();
profile.setSubject(claims.getStringClaim(UserInfo.SUB_CLAIM_NAME));
profile.setUsername(claims.getStringClaim(usernameClaimName));
profile.setGroups(claims.getStringListClaim(teamsClaimName));
profile.setEmail(claims.getStringClaim(UserInfo.EMAIL_CLAIM_NAME));
return profile;
return customizer.createProfile(claims);
};

OidcProfile idTokenProfile = null;
if (idToken != null) {
idTokenProfile = idTokenAuthenticator.authenticate(idToken, profileCreator);
LOGGER.debug("ID token profile: " + idTokenProfile);

if (isProfileComplete(idTokenProfile, teamSyncEnabled)) {
if (customizer.isProfileComplete(idTokenProfile, teamSyncEnabled)) {
LOGGER.debug("ID token profile is complete, proceeding to authenticate");
return authenticateInternal(idTokenProfile);
}
Expand All @@ -151,18 +155,18 @@ public Principal authenticate() throws AlpineAuthenticationException {
userInfoProfile = userInfoAuthenticator.authenticate(accessToken, profileCreator);
LOGGER.debug("UserInfo profile: " + userInfoProfile);

if (isProfileComplete(userInfoProfile, teamSyncEnabled)) {
if (customizer.isProfileComplete(userInfoProfile, teamSyncEnabled)) {
LOGGER.debug("UserInfo profile is complete, proceeding to authenticate");
return authenticateInternal(userInfoProfile);
}
}

OidcProfile mergedProfile = null;
if (idTokenProfile != null && userInfoProfile != null) {
mergedProfile = mergeProfiles(idTokenProfile, userInfoProfile);
mergedProfile = customizer.mergeProfiles(idTokenProfile, userInfoProfile);
LOGGER.debug("Merged profile: " + mergedProfile);

if (isProfileComplete(mergedProfile, teamSyncEnabled)) {
if (customizer.isProfileComplete(mergedProfile, teamSyncEnabled)) {
LOGGER.debug("Merged profile is complete, proceeding to authenticate");
return authenticateInternal(mergedProfile);
}
Expand All @@ -182,7 +186,9 @@ private OidcUser authenticateInternal(final OidcProfile profile) throws AlpineAu
LOGGER.debug("Assigning subject identifier " + profile.getSubject() + " to user " + user.getUsername());
user.setSubjectIdentifier(profile.getSubject());
user.setEmail(profile.getEmail());
return qm.updateOidcUser(user);
user = qm.updateOidcUser(user);
customizer.onAuthenticationSuccess(profile, idToken, accessToken);
return user;
} else if (!user.getSubjectIdentifier().equals(profile.getSubject())) {
LOGGER.error("Refusing to authenticate user " + user.getUsername() + ": subject identifier has changed (" +
user.getSubjectIdentifier() + " to " + profile.getSubject() + ")");
Expand All @@ -194,38 +200,24 @@ private OidcUser authenticateInternal(final OidcProfile profile) throws AlpineAu
user = qm.updateOidcUser(user);
}
if (config.getPropertyAsBoolean(Config.AlpineKey.OIDC_TEAM_SYNCHRONIZATION)) {
return qm.synchronizeTeamMembership(user, profile.getGroups());
user = qm.synchronizeTeamMembership(user, profile.getGroups());
customizer.onAuthenticationSuccess(profile, idToken, accessToken);
return user;
}
customizer.onAuthenticationSuccess(profile, idToken, accessToken);
return user;
} else if (config.getPropertyAsBoolean(Config.AlpineKey.OIDC_USER_PROVISIONING)) {
LOGGER.debug("The user (" + profile.getUsername() + ") authenticated successfully but the account has not been provisioned");
return autoProvision(qm, profile);
user = autoProvision(qm, profile);
customizer.onAuthenticationSuccess(profile, idToken, accessToken);
return user;
} else {
LOGGER.debug("The user (" + profile.getUsername() + ") is unmapped and user provisioning is not enabled");
throw new AlpineAuthenticationException(AlpineAuthenticationException.CauseType.UNMAPPED_ACCOUNT);
}
}
}

private boolean isProfileComplete(final OidcProfile profile, final boolean teamSyncEnabled) {
return profile.getSubject() != null
&& profile.getUsername() != null
&& (!teamSyncEnabled || (profile.getGroups() != null));
}

private OidcProfile mergeProfiles(final OidcProfile left, final OidcProfile right) {
final var profile = new OidcProfile();
profile.setSubject(selectProfileClaim(left.getSubject(), right.getSubject()));
profile.setUsername(selectProfileClaim(left.getUsername(), right.getUsername()));
profile.setGroups(selectProfileClaim(left.getGroups(), right.getGroups()));
profile.setEmail(selectProfileClaim(left.getEmail(), right.getEmail()));
return profile;
}

private <T> T selectProfileClaim(final T left, final T right) {
return (left != null) ? left : right;
}

private OidcUser autoProvision(final AlpineQueryManager qm, final OidcProfile profile) {
var user = new OidcUser();
user.setUsername(profile.getUsername());
Expand All @@ -235,7 +227,9 @@ private OidcUser autoProvision(final AlpineQueryManager qm, final OidcProfile pr

if (config.getPropertyAsBoolean(Config.AlpineKey.OIDC_TEAM_SYNCHRONIZATION)) {
LOGGER.debug("Synchronizing teams for user " + user.getUsername());
return qm.synchronizeTeamMembership(user, profile.getGroups());
user = qm.synchronizeTeamMembership(user, profile.getGroups());
customizer.onAuthenticationSuccess(profile, idToken, accessToken);
return user;
}

final List<String> defaultTeams = config.getPropertyAsList(Config.AlpineKey.OIDC_TEAMS_DEFAULT);
Expand Down
49 changes: 31 additions & 18 deletions alpine-server/src/main/java/alpine/server/auth/OidcProfile.java
Original file line number Diff line number Diff line change
Expand Up @@ -21,56 +21,69 @@

import java.util.List;

import net.minidev.json.JSONObject;

/**
* @since 1.10.0
*/
class OidcProfile {
public class OidcProfile {

private String subject;
private String username;
private String subject, username, email;
private List<String> groups;
private String email;
private JSONObject customValues = new JSONObject();

public Object getCustomValue(final String key) {
return customValues.get(key);
}

public Object putCustomValue(final String key, final Object value) {
return customValues.put(key, value);
}

public JSONObject getCustomValues() {
return customValues;
}

public void setCustomValues(JSONObject customValues) {
this.customValues = customValues;
}

String getSubject() {
public String getSubject() {
return subject;
}

void setSubject(final String subject) {
public void setSubject(final String subject) {
this.subject = subject;
}

String getUsername() {
public String getUsername() {
return username;
}

void setUsername(final String username) {
public void setUsername(final String username) {
this.username = username;
}

List<String> getGroups() {
public List<String> getGroups() {
return groups;
}

void setGroups(final List<String> groups) {
public void setGroups(final List<String> groups) {
this.groups = groups;
}

String getEmail() {
public String getEmail() {
return email;
}

void setEmail(final String email) {
public void setEmail(final String email) {
this.email = email;
}

@Override
public String toString() {
return "OidcProfile{" +
"subject='" + subject + '\'' +
", username='" + username + '\'' +
", groups=" + groups +
", email='" + email + '\'' +
'}';
return "%s{subject='%s', username='%s', groups=%s, email='%s', customValues=%s"
.formatted(getClass().getName(), subject, username, groups, email, customValues);
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
alpine.server.auth.DefaultOidcAuthenticationCustomizer