Search in sources :

Example 46 with Subject

use of com.nimbusds.oauth2.sdk.id.Subject in project di-authentication-api by alphagov.

the class IPVAuthorisationServiceTest method shouldConstructASignedRequestJWT.

@Test
void shouldConstructASignedRequestJWT() throws JOSEException, ParseException {
    var ecSigningKey = new ECKeyGenerator(Curve.P_256).keyID(KEY_ID).algorithm(JWSAlgorithm.ES256).generate();
    var ecdsaSigner = new ECDSASigner(ecSigningKey);
    var jwtClaimsSet = new JWTClaimsSet.Builder().build();
    var jwsHeader = new JWSHeader(JWSAlgorithm.ES256);
    var signedJWT = new SignedJWT(jwsHeader, jwtClaimsSet);
    signedJWT.sign(ecdsaSigner);
    var signResult = new SignResult();
    byte[] signatureToDER = ECDSA.transcodeSignatureToDER(signedJWT.getSignature().decode());
    signResult.setSignature(ByteBuffer.wrap(signatureToDER));
    signResult.setKeyId(KEY_ID);
    signResult.setSigningAlgorithm(JWSAlgorithm.ES256.getName());
    when(kmsConnectionService.sign(any(SignRequest.class))).thenReturn(signResult);
    var state = new State();
    var nonce = new Nonce();
    var scope = new Scope(OIDCScopeValue.OPENID);
    var pairwise = new Subject("pairwise-identifier");
    var claims = "{\"name\":{\"essential\":true}}";
    var encryptedJWT = authorisationService.constructRequestJWT(state, nonce, scope, pairwise, claims);
    var signedJWTResponse = decryptJWT(encryptedJWT);
    assertThat(signedJWTResponse.getJWTClaimsSet().getClaim("client_id"), equalTo(IPV_CLIENT_ID));
    assertThat(signedJWTResponse.getJWTClaimsSet().getClaim("state"), equalTo(state.getValue()));
    assertThat(signedJWTResponse.getJWTClaimsSet().getClaim("nonce"), equalTo(nonce.getValue()));
    assertThat(signedJWTResponse.getJWTClaimsSet().getSubject(), equalTo(pairwise.getValue()));
    assertThat(signedJWTResponse.getJWTClaimsSet().getClaim("scope"), equalTo(scope.toString()));
    assertThat(signedJWTResponse.getJWTClaimsSet().getIssuer(), equalTo(IPV_CLIENT_ID));
    assertThat(signedJWTResponse.getJWTClaimsSet().getAudience(), equalTo(singletonList(IPV_URI.toString())));
    assertThat(signedJWTResponse.getJWTClaimsSet().getClaim("response_type"), equalTo("code"));
    assertThat(signedJWTResponse.getJWTClaimsSet().getClaim("claims"), equalTo(claims));
}
Also used : SignResult(com.amazonaws.services.kms.model.SignResult) SignRequest(com.amazonaws.services.kms.model.SignRequest) ECDSASigner(com.nimbusds.jose.crypto.ECDSASigner) ECKeyGenerator(com.nimbusds.jose.jwk.gen.ECKeyGenerator) SignedJWT(com.nimbusds.jwt.SignedJWT) Subject(com.nimbusds.oauth2.sdk.id.Subject) Nonce(com.nimbusds.openid.connect.sdk.Nonce) Scope(com.nimbusds.oauth2.sdk.Scope) JWTClaimsSet(com.nimbusds.jwt.JWTClaimsSet) State(com.nimbusds.oauth2.sdk.id.State) JWSHeader(com.nimbusds.jose.JWSHeader) Test(org.junit.jupiter.api.Test)

Example 47 with Subject

use of com.nimbusds.oauth2.sdk.id.Subject in project di-authentication-api by alphagov.

the class UserInfoIntegrationTest method shouldReturn200WhenIdentityIsEnabledAndIdentityClaimsArePresent.

@Test
void shouldReturn200WhenIdentityIsEnabledAndIdentityClaimsArePresent() throws Json.JsonException, ParseException {
    var configurationService = new UserInfoIntegrationTest.UserInfoConfigurationService();
    handler = new UserInfoHandler(configurationService);
    var claimsSetRequest = new ClaimsSetRequest().add(ValidClaims.CORE_IDENTITY_JWT.getValue()).add(ValidClaims.ADDRESS.getValue()).add(ValidClaims.PASSPORT.getValue());
    var oidcValidClaimsRequest = new OIDCClaimsRequest().withUserInfoClaimsRequest(claimsSetRequest);
    var claimsSet = new JWTClaimsSet.Builder().claim("scope", SCOPES).issuer("issuer-id").expirationTime(EXPIRY_DATE).issueTime(NowHelper.now()).claim("client_id", "client-id-one").subject(PUBLIC_SUBJECT.getValue()).jwtID(UUID.randomUUID().toString()).claim("claims", oidcValidClaimsRequest.getUserInfoClaimsRequest().getEntries().stream().map(ClaimsSetRequest.Entry::getClaimName).collect(Collectors.toList())).build();
    var signedJWT = tokenSigner.signJwt(claimsSet);
    var accessToken = new BearerAccessToken(signedJWT.serialize());
    var accessTokenStore = new AccessTokenStore(accessToken.getValue(), INTERNAL_SUBJECT.getValue());
    redis.addToRedis(ACCESS_TOKEN_PREFIX + CLIENT_ID + "." + PUBLIC_SUBJECT, objectMapper.writeValueAsString(accessTokenStore), 300L);
    var signedCredential = SignedCredentialHelper.generateCredential();
    setUpDynamo(signedCredential.serialize(), Map.of(ValidClaims.ADDRESS.getValue(), ADDRESS_CLAIM, ValidClaims.PASSPORT.getValue(), PASSPORT_CLAIM));
    var response = makeRequest(Optional.empty(), Map.of("Authorization", accessToken.toAuthorizationHeader()), Map.of());
    assertThat(response, hasStatus(200));
    var userInfoResponse = UserInfo.parse(response.getBody());
    assertThat(userInfoResponse.getEmailVerified(), equalTo(true));
    assertThat(userInfoResponse.getEmailAddress(), equalTo(TEST_EMAIL_ADDRESS));
    assertThat(userInfoResponse.getPhoneNumber(), equalTo(FORMATTED_PHONE_NUMBER));
    assertThat(userInfoResponse.getPhoneNumberVerified(), equalTo(true));
    assertThat(userInfoResponse.getSubject(), equalTo(PUBLIC_SUBJECT));
    assertThat(userInfoResponse.getClaim(ValidClaims.ADDRESS.getValue()), equalTo(ADDRESS_CLAIM));
    assertThat(userInfoResponse.getClaim(ValidClaims.PASSPORT.getValue()), equalTo(PASSPORT_CLAIM));
    assertThat(userInfoResponse.getClaim(ValidClaims.CORE_IDENTITY_JWT.getValue()), equalTo(signedCredential.serialize()));
    assertThat(userInfoResponse.toJWTClaimsSet().getClaims().size(), equalTo(8));
    assertNoAuditEventsReceived(auditTopic);
}
Also used : ClaimsSetRequest(com.nimbusds.openid.connect.sdk.claims.ClaimsSetRequest) OIDCClaimsRequest(com.nimbusds.openid.connect.sdk.OIDCClaimsRequest) AccessTokenStore(uk.gov.di.authentication.shared.entity.AccessTokenStore) JWTClaimsSet(com.nimbusds.jwt.JWTClaimsSet) UserInfoHandler(uk.gov.di.authentication.oidc.lambda.UserInfoHandler) BearerAccessToken(com.nimbusds.oauth2.sdk.token.BearerAccessToken) Test(org.junit.jupiter.api.Test) ApiGatewayHandlerIntegrationTest(uk.gov.di.authentication.sharedtest.basetest.ApiGatewayHandlerIntegrationTest)

Example 48 with Subject

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

the class KnoxServiceTest method testInvalidAudience.

@Test(expected = InvalidAuthenticationException.class)
public void testInvalidAudience() 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, "incorrect-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 49 with Subject

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

the class KnoxServiceTest method testExpiredJwt.

@Test(expected = InvalidAuthenticationException.class)
public void testExpiredJwt() throws Exception {
    final String subject = "user-1";
    // token expires in 1 sec
    final Date expiration = new Date(System.currentTimeMillis() + TimeUnit.MILLISECONDS.convert(1, 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();
    // wait 2 sec
    Thread.sleep(TimeUnit.MILLISECONDS.convert(2, TimeUnit.SECONDS));
    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);
    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 50 with Subject

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

the class OpenIdConnectUserValidator method getUserFromAccessToken.

@Override
public Optional<User> getUserFromAccessToken(String accessToken) throws UserValidationException {
    if (StringUtils.isBlank(accessToken)) {
        return Optional.empty();
    }
    final User local = users.getIfPresent(accessToken);
    if (local != null) {
        return Optional.of(local);
    }
    try {
        final Optional<UserInfo> userInfoOpt = openIdClient.getUserInfo(accessToken);
        if (userInfoOpt.isEmpty()) {
            return Optional.empty();
        }
        final UserInfo userInfo = userInfoOpt.get();
        final String subject = userInfo.getSubject().getValue();
        final Optional<User> user = userStore.userFor(subject);
        if (user.isPresent()) {
            user.ifPresent(value -> users.put(accessToken, value));
            return user;
        } else {
            final User newUser = userStore.saveNew(userInfo.getNickname(), subject);
            users.put(subject, newUser);
            return Optional.of(newUser);
        }
    } catch (AuthenticationUnavailableException | IOException | ParseException e) {
        throw new UserValidationException(e);
    }
}
Also used : UserValidationException(nl.knaw.huygens.timbuctoo.v5.security.exceptions.UserValidationException) AuthenticationUnavailableException(nl.knaw.huygens.timbuctoo.security.exceptions.AuthenticationUnavailableException) User(nl.knaw.huygens.timbuctoo.v5.security.dto.User) UserInfo(com.nimbusds.openid.connect.sdk.claims.UserInfo) IOException(java.io.IOException) ParseException(com.nimbusds.oauth2.sdk.ParseException)

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