Search in sources :

Example 11 with Subject

use of com.nimbusds.oauth2.sdk.id.Subject in project nifi by apache.

the class KnoxServiceTest method testRequiredAudience.

@Test
public void testRequiredAudience() throws Exception {
    final String subject = "user-1";
    final Date expiration = new Date(System.currentTimeMillis() + TimeUnit.MILLISECONDS.convert(5, TimeUnit.SECONDS));
    final KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
    final KeyPair pair = keyGen.generateKeyPair();
    final RSAPrivateKey privateKey = (RSAPrivateKey) pair.getPrivate();
    final RSAPublicKey publicKey = (RSAPublicKey) pair.getPublic();
    final JWTAuthenticationClaimsSet claimsSet = getAuthenticationClaimsSet(subject, AUDIENCE, expiration);
    final PrivateKeyJWT privateKeyJWT = new PrivateKeyJWT(claimsSet, JWSAlgorithm.RS256, privateKey, null, null);
    final KnoxConfiguration configuration = getConfiguration(publicKey);
    when(configuration.getAudiences()).thenReturn(null);
    final KnoxService service = new KnoxService(configuration);
    Assert.assertEquals(subject, service.getAuthenticationFromToken(privateKeyJWT.getClientAssertion().serialize()));
}
Also used : KeyPair(java.security.KeyPair) RSAPublicKey(java.security.interfaces.RSAPublicKey) PrivateKeyJWT(com.nimbusds.oauth2.sdk.auth.PrivateKeyJWT) JWTAuthenticationClaimsSet(com.nimbusds.oauth2.sdk.auth.JWTAuthenticationClaimsSet) KeyPairGenerator(java.security.KeyPairGenerator) RSAPrivateKey(java.security.interfaces.RSAPrivateKey) Date(java.util.Date) Test(org.junit.Test)

Example 12 with Subject

use of com.nimbusds.oauth2.sdk.id.Subject in project nifi by apache.

the class KnoxServiceTest method testSignedJwt.

@Test
public void testSignedJwt() throws Exception {
    final String subject = "user-1";
    final Date expiration = new Date(System.currentTimeMillis() + TimeUnit.MILLISECONDS.convert(5, TimeUnit.SECONDS));
    final KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
    final KeyPair pair = keyGen.generateKeyPair();
    final RSAPrivateKey privateKey = (RSAPrivateKey) pair.getPrivate();
    final RSAPublicKey publicKey = (RSAPublicKey) pair.getPublic();
    final JWTAuthenticationClaimsSet claimsSet = getAuthenticationClaimsSet(subject, AUDIENCE, expiration);
    final PrivateKeyJWT privateKeyJWT = new PrivateKeyJWT(claimsSet, JWSAlgorithm.RS256, privateKey, null, null);
    final KnoxConfiguration configuration = getConfiguration(publicKey);
    final KnoxService service = new KnoxService(configuration);
    Assert.assertEquals(subject, service.getAuthenticationFromToken(privateKeyJWT.getClientAssertion().serialize()));
}
Also used : KeyPair(java.security.KeyPair) RSAPublicKey(java.security.interfaces.RSAPublicKey) PrivateKeyJWT(com.nimbusds.oauth2.sdk.auth.PrivateKeyJWT) JWTAuthenticationClaimsSet(com.nimbusds.oauth2.sdk.auth.JWTAuthenticationClaimsSet) KeyPairGenerator(java.security.KeyPairGenerator) RSAPrivateKey(java.security.interfaces.RSAPrivateKey) Date(java.util.Date) Test(org.junit.Test)

Example 13 with Subject

use of com.nimbusds.oauth2.sdk.id.Subject in project nifi by apache.

the class KnoxServiceTest method testBadSignedJwt.

@Test(expected = InvalidAuthenticationException.class)
public void testBadSignedJwt() throws Exception {
    final String subject = "user-1";
    final Date expiration = new Date(System.currentTimeMillis() + TimeUnit.MILLISECONDS.convert(5, TimeUnit.SECONDS));
    final KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
    final KeyPair pair1 = keyGen.generateKeyPair();
    final RSAPrivateKey privateKey1 = (RSAPrivateKey) pair1.getPrivate();
    final KeyPair pair2 = keyGen.generateKeyPair();
    final RSAPublicKey publicKey2 = (RSAPublicKey) pair2.getPublic();
    // sign the jwt with pair 1
    final JWTAuthenticationClaimsSet claimsSet = getAuthenticationClaimsSet(subject, AUDIENCE, expiration);
    final PrivateKeyJWT privateKeyJWT = new PrivateKeyJWT(claimsSet, JWSAlgorithm.RS256, privateKey1, null, null);
    // attempt to verify it with pair 2
    final KnoxConfiguration configuration = getConfiguration(publicKey2);
    final KnoxService service = new KnoxService(configuration);
    service.getAuthenticationFromToken(privateKeyJWT.getClientAssertion().serialize());
}
Also used : KeyPair(java.security.KeyPair) RSAPublicKey(java.security.interfaces.RSAPublicKey) PrivateKeyJWT(com.nimbusds.oauth2.sdk.auth.PrivateKeyJWT) JWTAuthenticationClaimsSet(com.nimbusds.oauth2.sdk.auth.JWTAuthenticationClaimsSet) KeyPairGenerator(java.security.KeyPairGenerator) RSAPrivateKey(java.security.interfaces.RSAPrivateKey) Date(java.util.Date) Test(org.junit.Test)

Example 14 with Subject

use of com.nimbusds.oauth2.sdk.id.Subject in project pac4j by pac4j.

the class OidcProfileCreator method create.

@Override
@SuppressWarnings("unchecked")
public U create(final OidcCredentials credentials, final WebContext context) {
    init();
    final AccessToken accessToken = credentials.getAccessToken();
    // Create profile
    final U profile = getProfileDefinition().newProfile();
    profile.setAccessToken(accessToken);
    final JWT idToken = credentials.getIdToken();
    profile.setIdTokenString(idToken.getParsedString());
    // Check if there is a refresh token
    final RefreshToken refreshToken = credentials.getRefreshToken();
    if (refreshToken != null && !refreshToken.getValue().isEmpty()) {
        profile.setRefreshToken(refreshToken);
        logger.debug("Refresh Token successful retrieved");
    }
    try {
        // check idToken
        final Nonce nonce;
        if (configuration.isUseNonce()) {
            nonce = new Nonce((String) context.getSessionStore().get(context, OidcConfiguration.NONCE_SESSION_ATTRIBUTE));
        } else {
            nonce = null;
        }
        // Check ID Token
        final IDTokenClaimsSet claimsSet = this.idTokenValidator.validate(idToken, nonce);
        assertNotNull("claimsSet", claimsSet);
        profile.setId(ProfileHelper.sanitizeIdentifier(profile, claimsSet.getSubject()));
        // User Info request
        if (configuration.findProviderMetadata().getUserInfoEndpointURI() != null && accessToken != null) {
            final UserInfoRequest userInfoRequest = new UserInfoRequest(configuration.findProviderMetadata().getUserInfoEndpointURI(), (BearerAccessToken) accessToken);
            final HTTPRequest userInfoHttpRequest = userInfoRequest.toHTTPRequest();
            userInfoHttpRequest.setConnectTimeout(configuration.getConnectTimeout());
            userInfoHttpRequest.setReadTimeout(configuration.getReadTimeout());
            final HTTPResponse httpResponse = userInfoHttpRequest.send();
            logger.debug("Token response: status={}, content={}", httpResponse.getStatusCode(), httpResponse.getContent());
            final UserInfoResponse userInfoResponse = UserInfoResponse.parse(httpResponse);
            if (userInfoResponse instanceof UserInfoErrorResponse) {
                logger.error("Bad User Info response, error={}", ((UserInfoErrorResponse) userInfoResponse).getErrorObject());
            } else {
                final UserInfoSuccessResponse userInfoSuccessResponse = (UserInfoSuccessResponse) userInfoResponse;
                final JWTClaimsSet userInfoClaimsSet;
                if (userInfoSuccessResponse.getUserInfo() != null) {
                    userInfoClaimsSet = userInfoSuccessResponse.getUserInfo().toJWTClaimsSet();
                } else {
                    userInfoClaimsSet = userInfoSuccessResponse.getUserInfoJWT().getJWTClaimsSet();
                }
                getProfileDefinition().convertAndAdd(profile, userInfoClaimsSet.getClaims(), null);
            }
        }
        // add attributes of the ID token if they don't already exist
        for (final Map.Entry<String, Object> entry : idToken.getJWTClaimsSet().getClaims().entrySet()) {
            final String key = entry.getKey();
            final Object value = entry.getValue();
            // it's not the subject and this attribute does not already exist, add it
            if (!JwtClaims.SUBJECT.equals(key) && profile.getAttribute(key) == null) {
                getProfileDefinition().convertAndAdd(profile, PROFILE_ATTRIBUTE, key, value);
            }
        }
        return profile;
    } catch (final IOException | ParseException | JOSEException | BadJOSEException | java.text.ParseException e) {
        throw new TechnicalException(e);
    }
}
Also used : HTTPRequest(com.nimbusds.oauth2.sdk.http.HTTPRequest) TechnicalException(org.pac4j.core.exception.TechnicalException) JWT(com.nimbusds.jwt.JWT) HTTPResponse(com.nimbusds.oauth2.sdk.http.HTTPResponse) IDTokenClaimsSet(com.nimbusds.openid.connect.sdk.claims.IDTokenClaimsSet) IOException(java.io.IOException) RefreshToken(com.nimbusds.oauth2.sdk.token.RefreshToken) BadJOSEException(com.nimbusds.jose.proc.BadJOSEException) AccessToken(com.nimbusds.oauth2.sdk.token.AccessToken) BearerAccessToken(com.nimbusds.oauth2.sdk.token.BearerAccessToken) JWTClaimsSet(com.nimbusds.jwt.JWTClaimsSet) ParseException(com.nimbusds.oauth2.sdk.ParseException) Map(java.util.Map) JOSEException(com.nimbusds.jose.JOSEException) BadJOSEException(com.nimbusds.jose.proc.BadJOSEException)

Example 15 with Subject

use of com.nimbusds.oauth2.sdk.id.Subject in project pac4j by pac4j.

the class OidcProfileCreator method create.

@Override
@SuppressWarnings("unchecked")
public Optional<UserProfile> create(final Credentials cred, final WebContext context, final SessionStore sessionStore) {
    init();
    final var credentials = (OidcCredentials) cred;
    final var accessToken = credentials.getAccessToken();
    // Create profile
    final var profile = (OidcProfile) getProfileDefinition().newProfile();
    profile.setAccessToken(accessToken);
    final var idToken = credentials.getIdToken();
    profile.setIdTokenString(idToken.getParsedString());
    // Check if there is a refresh token
    final var refreshToken = credentials.getRefreshToken();
    if (refreshToken != null && !refreshToken.getValue().isEmpty()) {
        profile.setRefreshToken(refreshToken);
        logger.debug("Refresh Token successful retrieved");
    }
    try {
        final Nonce nonce;
        if (configuration.isUseNonce()) {
            nonce = new Nonce((String) sessionStore.get(context, client.getNonceSessionAttributeName()).orElse(null));
        } else {
            nonce = null;
        }
        // Check ID Token
        final var claimsSet = configuration.findTokenValidator().validate(idToken, nonce);
        assertNotNull("claimsSet", claimsSet);
        profile.setId(ProfileHelper.sanitizeIdentifier(claimsSet.getSubject()));
        // User Info request
        if (configuration.findProviderMetadata().getUserInfoEndpointURI() != null && accessToken != null) {
            final var userInfoRequest = new UserInfoRequest(configuration.findProviderMetadata().getUserInfoEndpointURI(), accessToken);
            final var userInfoHttpRequest = userInfoRequest.toHTTPRequest();
            configuration.configureHttpRequest(userInfoHttpRequest);
            final var httpResponse = userInfoHttpRequest.send();
            logger.debug("User info response: status={}, content={}", httpResponse.getStatusCode(), httpResponse.getContent());
            final var userInfoResponse = UserInfoResponse.parse(httpResponse);
            if (userInfoResponse instanceof UserInfoErrorResponse) {
                logger.error("Bad User Info response, error={}", ((UserInfoErrorResponse) userInfoResponse).getErrorObject());
            } else {
                final var userInfoSuccessResponse = (UserInfoSuccessResponse) userInfoResponse;
                final JWTClaimsSet userInfoClaimsSet;
                if (userInfoSuccessResponse.getUserInfo() != null) {
                    userInfoClaimsSet = userInfoSuccessResponse.getUserInfo().toJWTClaimsSet();
                } else {
                    userInfoClaimsSet = userInfoSuccessResponse.getUserInfoJWT().getJWTClaimsSet();
                }
                if (userInfoClaimsSet != null) {
                    getProfileDefinition().convertAndAdd(profile, userInfoClaimsSet.getClaims(), null);
                } else {
                    logger.warn("Cannot retrieve claims from user info");
                }
            }
        }
        // add attributes of the ID token if they don't already exist
        for (final var entry : idToken.getJWTClaimsSet().getClaims().entrySet()) {
            final var key = entry.getKey();
            final var value = entry.getValue();
            // it's not the subject and this attribute does not already exist, add it
            if (!JwtClaims.SUBJECT.equals(key) && profile.getAttribute(key) == null) {
                getProfileDefinition().convertAndAdd(profile, PROFILE_ATTRIBUTE, key, value);
            }
        }
        // session expiration with token behavior
        profile.setTokenExpirationAdvance(configuration.getTokenExpirationAdvance());
        // keep the session ID if provided
        final var sid = (String) claimsSet.getClaim(Pac4jConstants.OIDC_CLAIM_SESSIONID);
        if (isNotBlank(sid)) {
            configuration.findLogoutHandler().recordSession(context, sessionStore, sid);
        }
        return Optional.of(profile);
    } catch (final IOException | ParseException | JOSEException | BadJOSEException | java.text.ParseException e) {
        throw new TechnicalException(e);
    }
}
Also used : TechnicalException(org.pac4j.core.exception.TechnicalException) IOException(java.io.IOException) OidcCredentials(org.pac4j.oidc.credentials.OidcCredentials) BadJOSEException(com.nimbusds.jose.proc.BadJOSEException) JWTClaimsSet(com.nimbusds.jwt.JWTClaimsSet) OidcProfile(org.pac4j.oidc.profile.OidcProfile) ParseException(com.nimbusds.oauth2.sdk.ParseException) JOSEException(com.nimbusds.jose.JOSEException) BadJOSEException(com.nimbusds.jose.proc.BadJOSEException)

Aggregations

Subject (com.nimbusds.oauth2.sdk.id.Subject)59 Test (org.junit.jupiter.api.Test)36 SignedJWT (com.nimbusds.jwt.SignedJWT)22 Date (java.util.Date)22 ApiGatewayHandlerIntegrationTest (uk.gov.di.authentication.sharedtest.basetest.ApiGatewayHandlerIntegrationTest)19 UserProfile (uk.gov.di.authentication.shared.entity.UserProfile)18 KeyPair (java.security.KeyPair)16 BearerAccessToken (com.nimbusds.oauth2.sdk.token.BearerAccessToken)15 JWTClaimsSet (com.nimbusds.jwt.JWTClaimsSet)13 ParseException (com.nimbusds.oauth2.sdk.ParseException)12 Scope (com.nimbusds.oauth2.sdk.Scope)12 APIGatewayProxyRequestEvent (com.amazonaws.services.lambda.runtime.events.APIGatewayProxyRequestEvent)11 APIGatewayProxyResponseEvent (com.amazonaws.services.lambda.runtime.events.APIGatewayProxyResponseEvent)11 AccessToken (com.nimbusds.oauth2.sdk.token.AccessToken)10 ECKeyGenerator (com.nimbusds.jose.jwk.gen.ECKeyGenerator)9 ParameterizedTest (org.junit.jupiter.params.ParameterizedTest)9 ECDSASigner (com.nimbusds.jose.crypto.ECDSASigner)8 Issuer (com.nimbusds.oauth2.sdk.id.Issuer)8 IDTokenClaimsSet (com.nimbusds.openid.connect.sdk.claims.IDTokenClaimsSet)8 LocalDateTime (java.time.LocalDateTime)8