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

Develop/unilogin lightweight #171

Merged
merged 3 commits into from
Feb 27, 2024
Merged
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
Original file line number Diff line number Diff line change
@@ -1,10 +1,15 @@
package dk.acto.fafnir.api.provider;


import com.hazelcast.security.TokenCredentials;
import dk.acto.fafnir.api.model.AuthenticationResult;
import jakarta.servlet.http.HttpSession;

import java.io.IOException;
import java.security.NoSuchAlgorithmException;

public interface RedirectingAuthenticationProvider<T> extends ProviderInformation {
String authenticate();
String authenticate() throws NoSuchAlgorithmException;

AuthenticationResult callback(T data);
AuthenticationResult callback(T data) throws IOException;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
package dk.acto.fafnir.api.provider;

import dk.acto.fafnir.api.model.AuthenticationResult;
import jakarta.servlet.http.HttpSession;

import java.io.IOException;
import java.security.NoSuchAlgorithmException;


public interface RedirectingUnilogAuthenticationProvider<T> extends ProviderInformation {

String authenticate(HttpSession session) throws NoSuchAlgorithmException;

AuthenticationResult callback(T data, HttpSession session) throws IOException;
}
Empty file modified sso/bootstrap.sh
100755 → 100644
Empty file.
4 changes: 2 additions & 2 deletions sso/src/main/java/dk/acto/fafnir/sso/conf/BeanConf.java
Original file line number Diff line number Diff line change
Expand Up @@ -136,7 +136,7 @@ public UniLoginProvider uniLoginProvider(


@Bean
@ConditionalOnProperty(name = {"UL_CLIENT_ID", "UL_SECRET"})
@ConditionalOnProperty(name = {"UL_CLIENT_ID", "UL_SECRET", "FAFNIR_URL"})
public UniLoginLightweightProvider uniLoginLightweightProvider(
@Value("${UL_CLIENT_ID}") final String appId,
@Value("${UL_SECRET}") final String secret,
Expand All @@ -150,7 +150,7 @@ public UniLoginLightweightProvider uniLoginLightweightProvider(
.callback(fafnirConf.getUrl() + "/unilogin-lightweight/callback")
.defaultScope("openid")
.build(new UniLoginApi()))
.map(oAuth20Service -> new UniLoginLightweightProvider(oAuth20Service, tokenFactory, providerConf))
.map(oAuth20Service -> new UniLoginLightweightProvider(tokenFactory, providerConf))
.toJavaOptional()
.orElseThrow(UniloginLightweightConfigurationBroken::new);
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,51 +1,93 @@
package dk.acto.fafnir.sso.provider;

import com.auth0.jwt.JWT;
import com.auth0.jwt.interfaces.Claim;
import com.github.scribejava.core.oauth.OAuth20Service;
import com.fasterxml.jackson.databind.ObjectMapper;
import dk.acto.fafnir.api.exception.ProviderAttributeMissing;
import dk.acto.fafnir.api.model.*;
import dk.acto.fafnir.api.provider.RedirectingAuthenticationProvider;
import dk.acto.fafnir.api.provider.RedirectingUnilogAuthenticationProvider;
import dk.acto.fafnir.api.provider.metadata.MetadataProvider;
import dk.acto.fafnir.sso.model.conf.ProviderConf;
import dk.acto.fafnir.sso.provider.credentials.TokenCredentials;
import dk.acto.fafnir.sso.provider.unilogin.AccessToken;
import dk.acto.fafnir.sso.provider.unilogin.IntrospectionToken;
import dk.acto.fafnir.sso.provider.unilogin.UniloginTokenCredentials;
import dk.acto.fafnir.sso.util.PkceUtil;
import dk.acto.fafnir.sso.util.TokenFactory;
import io.vavr.control.Try;
import jakarta.servlet.http.HttpSession;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;

import java.util.Map;
import java.io.IOException;
import java.net.URI;
import java.net.URLEncoder;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

@Slf4j
@AllArgsConstructor
public class UniLoginLightweightProvider implements RedirectingAuthenticationProvider<TokenCredentials> {
private final OAuth20Service uniloginOauth;
public class UniLoginLightweightProvider implements RedirectingUnilogAuthenticationProvider<UniloginTokenCredentials> {
private final TokenFactory tokenFactory;
private final ProviderConf providerConf;

@Override
public String authenticate() {
return uniloginOauth.getAuthorizationUrl(Map.of("response_mode", "form_post"));
public String authenticate(HttpSession session) throws NoSuchAlgorithmException {
var codeVerifier = PkceUtil.generateCodeVerifier();
session.setAttribute("codeVerifier", codeVerifier);

var responseType = "response_type=" + URLEncoder.encode("code");
var client = "&client_id=" + URLEncoder.encode(System.getenv("UL_CLIENT_ID"));
var redirect = "&redirect_uri=" + URLEncoder.encode(System.getenv("FAFNIR_URL") + "/unilogin-lightweight/callback");
var codeChallengeMethod = "&code_challenge_method=" + URLEncoder.encode("S256");
var codeChallenge = "&code_challenge=" + URLEncoder.encode(PkceUtil.generateCodeChallenge(codeVerifier));
var nonce = "&nonce=" + URLEncoder.encode(new SecureRandom().ints(16, 0, 256)
.mapToObj(i -> String.format("%02x", i))
.collect(Collectors.joining()));
var state = "&state=" + URLEncoder.encode(new SecureRandom().ints(16, 0, 256)
.mapToObj(i -> String.format("%02x", i))
.collect(Collectors.joining()));
var scope = "&scope=" + URLEncoder.encode("openid");
var responseMode = "&response_mode=" + URLEncoder.encode("form_post");
return "https://et-broker.unilogin.dk/auth/realms/broker/protocol/openid-connect" + "/auth?" + responseType + client + redirect + codeChallengeMethod + codeChallenge + nonce + state + scope + responseMode;
}

@Override
public AuthenticationResult callback(TokenCredentials data) {
var token = Try.of(() -> JWT.decode(data.getCode()))
.onFailure(x -> log.error("Authentication failed", x))
.getOrNull();
public AuthenticationResult callback(UniloginTokenCredentials data, HttpSession session) throws IOException {
var UL_CLIENT_ID = System.getenv("UL_CLIENT_ID");
var UL_SECRET = System.getenv("UL_SECRET");
var UL_REDIRECT_URL = System.getenv("FAFNIR_URL") + "/unilogin-lightweight/callback";
var OID_BASE_URL = "https://et-broker.unilogin.dk/auth/realms/broker/protocol/openid-connect/";

var CODE_VERIFIER = (String) session.getAttribute("codeVerifier");


var accessCode = data.getCode();
AccessToken accessToken;

accessToken = getAccessToken(accessCode, UL_CLIENT_ID, UL_SECRET, UL_REDIRECT_URL, CODE_VERIFIER, OID_BASE_URL);

if (token == null) {
IntrospectionToken intro;

intro = getIntrospectToken(accessToken.getAccess_token(), UL_CLIENT_ID, UL_SECRET, OID_BASE_URL);


if (intro == null) {
return AuthenticationResult.failure(FailureReason.AUTHENTICATION_FAILED);
}

var subject = Optional.ofNullable(token.getClaim("sub"))
.map(Claim::asString)
var subject = Optional.ofNullable(intro.getSub())
.map(providerConf::applySubjectRules)
.orElseThrow(ProviderAttributeMissing::new);

var displayName = Optional.ofNullable(token.getClaim("customDisplayNameClaim"))
.map(Claim::asString)
var displayName = Optional.of("")
.orElseThrow(ProviderAttributeMissing::new);

var subjectActual = UserData.builder()
Expand All @@ -60,6 +102,42 @@ public AuthenticationResult callback(TokenCredentials data) {
return AuthenticationResult.success(jwt);
}

private AccessToken getAccessToken(String code, String clientId, String clientSecret, String redirectUri, String codeVerifier, String oidcBaseUrl) throws IOException {
List<NameValuePair> nvps = new ArrayList<>();
nvps.add(new BasicNameValuePair("grant_type", "authorization_code"));
nvps.add(new BasicNameValuePair("code", code));
nvps.add(new BasicNameValuePair("client_id", clientId));
nvps.add(new BasicNameValuePair("client_secret", clientSecret));
nvps.add(new BasicNameValuePair("redirect_uri", redirectUri));
nvps.add(new BasicNameValuePair("code_verifier", codeVerifier));
HttpResponse response = httpPostRequest(oidcBaseUrl + "/token", nvps);

return getObjectMapper().readValue(response.getEntity().getContent(), AccessToken.class);
}

private IntrospectionToken getIntrospectToken(String accesstoken, String clientId, String clientSecret, String oidcBaseUrl) throws IOException {
List<NameValuePair> nvps = new ArrayList<>();
nvps.add(new BasicNameValuePair("token", accesstoken));
nvps.add(new BasicNameValuePair("client_id", clientId));
nvps.add(new BasicNameValuePair("client_secret", clientSecret));
HttpResponse response = httpPostRequest(oidcBaseUrl + "/token/introspect", nvps);

return getObjectMapper().readValue(response.getEntity().getContent(), IntrospectionToken.class);
}

private HttpResponse httpPostRequest(String uri, List<NameValuePair> nvps) throws IOException {
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost();
httpPost.setURI(URI.create(uri));
httpPost.setEntity(new UrlEncodedFormEntity(nvps));
HttpResponse response = httpClient.execute(httpPost);
return response;
}

ObjectMapper getObjectMapper() {
return new ObjectMapper();
}

@Override
public ProviderMetaData getMetaData() {
return MetadataProvider.UNILOGIN;
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
package dk.acto.fafnir.sso.provider.unilogin;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import lombok.Builder;
import lombok.Value;

@Value
@Builder
@JsonIgnoreProperties(ignoreUnknown = true)
public class AccessToken {
String access_token;
int expires_in;
int refresh_expires_in;
String refresh_token;
String token_type;
String id_token;
String nonce;
String session_state;
String scope;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
package dk.acto.fafnir.sso.provider.unilogin;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import lombok.Builder;
import lombok.Value;

@Value
@Builder
@JsonIgnoreProperties(ignoreUnknown = true)
public class IntrospectionToken {
int exp;
int iat;
int auth_time;
String jti;
String iss;
String sub;
String typ;
String azp;
String session_state;
String nonce;
String acr;
String scope;
String spec_ver;
String unilogin_loa;
String aktoer_gruppe;
String loa;
String uniid;
String client_id;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
package dk.acto.fafnir.sso.provider.unilogin;

import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Value;

@Value
@Builder
@AllArgsConstructor
public class UniloginTokenCredentials {
String code;
}
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;

import java.security.NoSuchAlgorithmException;
import java.util.Set;

@AllArgsConstructor
Expand All @@ -18,28 +19,34 @@ public class SsoProviderService implements ProviderService {
@Override
public String[] getAcceptedProviders() {
return providerInformationSet.stream()
.map(ProviderInformation::getMetaData)
.map(ProviderMetaData::getProviderId)
.toArray(String[]::new);
.map(ProviderInformation::getMetaData)
.map(ProviderMetaData::getProviderId)
.toArray(String[]::new);
}

@Override
public ProviderMetaData getProviderMetaData(String providerId) {
return providerInformationSet.stream()
.map(ProviderInformation::getMetaData)
.filter(metaData -> metaData.getProviderId().equals(providerId))
.findAny()
.orElseThrow(NoSuchProvider::new);
.map(ProviderInformation::getMetaData)
.filter(metaData -> metaData.getProviderId().equals(providerId))
.findAny()
.orElseThrow(NoSuchProvider::new);
}

@Override
public String getAuthenticationUrlForProvider(String providerId) {
return providerInformationSet.stream()
.filter(pi -> pi.getMetaData().getProviderId().equals(providerId))
.filter(RedirectingAuthenticationProvider.class::isInstance)
.map(RedirectingAuthenticationProvider.class::cast)
.map(RedirectingAuthenticationProvider::authenticate)
.findFirst()
.orElseThrow(NoSuchProvider::new);
.filter(pi -> pi.getMetaData().getProviderId().equals(providerId))
.filter(RedirectingAuthenticationProvider.class::isInstance)
.map(RedirectingAuthenticationProvider.class::cast)
.map(provider -> {
try {
return provider.authenticate();
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException("Failed to generate authentication URL due to missing algorithm.", e);
}
})
.findFirst()
.orElseThrow(NoSuchProvider::new);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,9 @@

import dk.acto.fafnir.api.model.conf.FafnirConf;
import dk.acto.fafnir.sso.provider.UniLoginLightweightProvider;
import dk.acto.fafnir.sso.provider.credentials.TokenCredentials;
import dk.acto.fafnir.sso.provider.unilogin.UniloginTokenCredentials;
import jakarta.annotation.PostConstruct;
import jakarta.servlet.http.HttpSession;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
Expand All @@ -14,29 +15,32 @@
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.view.RedirectView;

import java.io.IOException;
import java.security.NoSuchAlgorithmException;

@Controller
@Slf4j
@AllArgsConstructor
@RequestMapping("unilogin-lightweight")
@ConditionalOnProperty(name = {"UL_CLIENT_ID", "UL_SECRET"})
@ConditionalOnProperty(name = {"UL_CLIENT_ID", "UL_SECRET", "FAFNIR_URL"})
public class UniLoginLightweightController {
private final UniLoginLightweightProvider provider;
private final FafnirConf uniloginConf;

@GetMapping
public RedirectView authenticate() {
return new RedirectView(provider.authenticate());
public RedirectView authenticate(HttpSession session) throws NoSuchAlgorithmException {
return new RedirectView(provider.authenticate(session));
}

@PostMapping("callback")
public RedirectView callback(@RequestParam("id_token") String code) {
return new RedirectView(provider.callback(TokenCredentials.builder()
public RedirectView callback(@RequestParam("code") String code, HttpSession session) throws IOException {
return new RedirectView(provider.callback(UniloginTokenCredentials.builder()
.code(code)
.build()).getUrl(uniloginConf));
.build(), session).getUrl(uniloginConf));
}

@PostConstruct
private void postConstruct() {
log.info("Exposing Unilogin OIDC Lightweight Endpoint...");
log.info("Exposing Unilogin lightweight OIDC Endpoint...");
}
}
Loading
Loading