Search in sources :

Example 1 with Subject

use of com.nimbusds.oauth2.sdk.id.Subject in project asgardeo-java-oidc-sdk by asgardeo.

the class DefaultOIDCManagerTest method setUp.

@BeforeMethod
public void setUp() throws Exception {
    mockServer = ClientAndServer.startClientAndServer(9441);
    Issuer issuer = new Issuer("issuer");
    ClientID clientID = new ClientID("sampleClientId");
    Secret clientSecret = new Secret("sampleClientSecret");
    URI callbackURI = new URI("http://localhost:9441/sampleCallbackURL");
    URI tokenEPURI = new URI("http://localhost:9441/sampleTokenEP");
    URI jwksURI = new URI("http://localhost:9441/jwksEP");
    URI logoutEP = new URI("http://test/sampleLogoutEP");
    Scope scope = new Scope("sampleScope1", "openid");
    JWT idToken = JWTParser.parse("eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwia" + "WF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c");
    request = mock(HttpServletRequest.class);
    response = mock(HttpServletResponse.class);
    requestResolver = mock(OIDCRequestResolver.class);
    sessionContext = mock(SessionContext.class);
    oidcAgentConfig.setConsumerKey(clientID);
    oidcAgentConfig.setConsumerSecret(clientSecret);
    oidcAgentConfig.setCallbackUrl(callbackURI);
    oidcAgentConfig.setTokenEndpoint(tokenEPURI);
    oidcAgentConfig.setLogoutEndpoint(logoutEP);
    oidcAgentConfig.setScope(scope);
    oidcAgentConfig.setIssuer(issuer);
    oidcAgentConfig.setJwksEndpoint(jwksURI);
    when(sessionContext.getIdToken()).thenReturn(idToken.getParsedString());
    IDTokenClaimsSet claimsSet = mock(IDTokenClaimsSet.class);
    IDTokenValidator idTokenValidator = mock(IDTokenValidator.class);
    com.nimbusds.openid.connect.sdk.validators.IDTokenValidator validator = mock(com.nimbusds.openid.connect.sdk.validators.IDTokenValidator.class);
    PowerMockito.whenNew(IDTokenValidator.class).withAnyArguments().thenReturn(idTokenValidator);
    PowerMockito.whenNew(com.nimbusds.openid.connect.sdk.validators.IDTokenValidator.class).withAnyArguments().thenReturn(validator);
    when(validator.validate(any(JWT.class), any(Nonce.class))).thenReturn(claimsSet);
    Mockito.when(idTokenValidator.validate(any(Nonce.class))).thenReturn(claimsSet);
    Mockito.when(claimsSet.getSubject()).thenReturn(new Subject("alex@carbon.super"));
}
Also used : Issuer(com.nimbusds.oauth2.sdk.id.Issuer) JWT(com.nimbusds.jwt.JWT) HttpServletResponse(javax.servlet.http.HttpServletResponse) IDTokenClaimsSet(com.nimbusds.openid.connect.sdk.claims.IDTokenClaimsSet) URI(java.net.URI) Subject(com.nimbusds.oauth2.sdk.id.Subject) Secret(com.nimbusds.oauth2.sdk.auth.Secret) HttpServletRequest(javax.servlet.http.HttpServletRequest) Nonce(com.nimbusds.openid.connect.sdk.Nonce) Scope(com.nimbusds.oauth2.sdk.Scope) ClientID(com.nimbusds.oauth2.sdk.id.ClientID) OIDCRequestResolver(io.asgardeo.java.oidc.sdk.request.OIDCRequestResolver) SessionContext(io.asgardeo.java.oidc.sdk.bean.SessionContext) IDTokenValidator(io.asgardeo.java.oidc.sdk.validators.IDTokenValidator) BeforeMethod(org.testng.annotations.BeforeMethod)

Example 2 with Subject

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

the class AccessTokenServiceTest method createSignedAccessTokenWithIdentityClaims.

private AccessToken createSignedAccessTokenWithIdentityClaims(OIDCClaimsRequest identityClaims) {
    try {
        LocalDateTime localDateTime = LocalDateTime.now().plusMinutes(3);
        Date expiryDate = Date.from(localDateTime.atZone(ZoneId.of("UTC")).toInstant());
        ECKey ecSigningKey = new ECKeyGenerator(Curve.P_256).keyID(KEY_ID).algorithm(JWSAlgorithm.ES256).generate();
        ECDSASigner signer = new ECDSASigner(ecSigningKey);
        SignedJWT signedJWT = TokenGeneratorHelper.generateSignedToken(CLIENT_ID, BASE_URL, SCOPES, signer, SUBJECT, ecSigningKey.getKeyID(), expiryDate, identityClaims);
        return new BearerAccessToken(signedJWT.serialize());
    } catch (JOSEException e) {
        throw new RuntimeException(e);
    }
}
Also used : LocalDateTime(java.time.LocalDateTime) ECDSASigner(com.nimbusds.jose.crypto.ECDSASigner) ECKeyGenerator(com.nimbusds.jose.jwk.gen.ECKeyGenerator) ECKey(com.nimbusds.jose.jwk.ECKey) SignedJWT(com.nimbusds.jwt.SignedJWT) BearerAccessToken(com.nimbusds.oauth2.sdk.token.BearerAccessToken) JOSEException(com.nimbusds.jose.JOSEException) Date(java.util.Date)

Example 3 with Subject

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

the class TokenHandler method processRefreshTokenRequest.

private APIGatewayProxyResponseEvent processRefreshTokenRequest(Map<String, String> requestBody, List<String> clientScopes, RefreshToken currentRefreshToken) {
    boolean refreshTokenSignatureValid = tokenValidationService.validateRefreshTokenSignatureAndExpiry(currentRefreshToken);
    if (!refreshTokenSignatureValid) {
        return generateApiGatewayProxyResponse(400, OAuth2Error.INVALID_GRANT.toJSONObject().toJSONString());
    }
    Subject publicSubject;
    List<String> scopes;
    try {
        SignedJWT signedJwt = SignedJWT.parse(currentRefreshToken.getValue());
        publicSubject = new Subject(signedJwt.getJWTClaimsSet().getSubject());
        scopes = (List<String>) signedJwt.getJWTClaimsSet().getClaim("scope");
    } catch (java.text.ParseException e) {
        LOG.warn("Unable to parse RefreshToken");
        return generateApiGatewayProxyResponse(400, new ErrorObject(OAuth2Error.INVALID_GRANT_CODE, "Invalid Refresh token").toJSONObject().toJSONString());
    }
    boolean areScopesValid = tokenValidationService.validateRefreshTokenScopes(clientScopes, scopes);
    if (!areScopesValid) {
        return generateApiGatewayProxyResponse(400, OAuth2Error.INVALID_SCOPE.toJSONObject().toJSONString());
    }
    String clientId = requestBody.get("client_id");
    String redisKey = REFRESH_TOKEN_PREFIX + clientId + "." + publicSubject.getValue();
    Optional<String> refreshToken = Optional.ofNullable(redisConnectionService.getValue(redisKey));
    RefreshTokenStore tokenStore;
    try {
        tokenStore = new ObjectMapper().readValue(refreshToken.get(), RefreshTokenStore.class);
    } catch (JsonProcessingException | NoSuchElementException | IllegalArgumentException e) {
        LOG.warn("Refresh token not found with given key");
        return generateApiGatewayProxyResponse(400, new ErrorObject(OAuth2Error.INVALID_GRANT_CODE, "Invalid Refresh token").toJSONObject().toJSONString());
    }
    if (!tokenStore.getRefreshTokens().contains(currentRefreshToken.getValue())) {
        LOG.warn("Refresh token store does not contain Refresh token in request");
        return generateApiGatewayProxyResponse(400, new ErrorObject(OAuth2Error.INVALID_GRANT_CODE, "Invalid Refresh token").toJSONObject().toJSONString());
    }
    if (tokenStore.getRefreshTokens().size() > 1) {
        LOG.info("Removing Refresh Token from refresh token store");
        try {
            redisConnectionService.saveWithExpiry(redisKey, new ObjectMapper().writeValueAsString(tokenStore.removeRefreshToken(currentRefreshToken.getValue())), configurationService.getSessionExpiry());
        } catch (JsonProcessingException e) {
            LOG.error("Unable to serialize refresh token store when updating");
            throw new RuntimeException(e);
        }
    } else {
        LOG.info("Deleting refresh token store as no other refresh tokens exist");
        redisConnectionService.deleteValue(redisKey);
    }
    OIDCTokenResponse tokenResponse = tokenService.generateRefreshTokenResponse(clientId, new Subject(tokenStore.getInternalSubjectId()), scopes, publicSubject);
    LOG.info("Generating successful RefreshToken response");
    return generateApiGatewayProxyResponse(200, tokenResponse.toJSONObject().toJSONString());
}
Also used : RefreshTokenStore(uk.gov.di.authentication.shared.entity.RefreshTokenStore) ErrorObject(com.nimbusds.oauth2.sdk.ErrorObject) OIDCTokenResponse(com.nimbusds.openid.connect.sdk.OIDCTokenResponse) SignedJWT(com.nimbusds.jwt.SignedJWT) Subject(com.nimbusds.oauth2.sdk.id.Subject) Context(com.amazonaws.services.lambda.runtime.Context) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) NoSuchElementException(java.util.NoSuchElementException)

Example 4 with Subject

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

the class UserInfoServiceTest method createSignedAccessToken.

private AccessToken createSignedAccessToken() throws JOSEException {
    ECKey ecSigningKey = new ECKeyGenerator(Curve.P_256).keyID(KEY_ID).algorithm(JWSAlgorithm.ES256).generate();
    ECDSASigner signer = new ECDSASigner(ecSigningKey);
    SignedJWT signedJWT = TokenGeneratorHelper.generateSignedToken(CLIENT_ID, BASE_URL, SCOPES, signer, SUBJECT, ecSigningKey.getKeyID());
    return new BearerAccessToken(signedJWT.serialize());
}
Also used : ECDSASigner(com.nimbusds.jose.crypto.ECDSASigner) ECKeyGenerator(com.nimbusds.jose.jwk.gen.ECKeyGenerator) ECKey(com.nimbusds.jose.jwk.ECKey) SignedJWT(com.nimbusds.jwt.SignedJWT) BearerAccessToken(com.nimbusds.oauth2.sdk.token.BearerAccessToken)

Example 5 with Subject

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

the class TokenIntegrationTest method shouldCallTokenResourceAndReturnAccessAndRefreshToken.

@ParameterizedTest
@MethodSource("validVectorValues")
void shouldCallTokenResourceAndReturnAccessAndRefreshToken(Optional<String> vtr) throws Exception {
    KeyPair keyPair = KeyPairHelper.GENERATE_RSA_KEY_PAIR();
    Scope scope = new Scope(OIDCScopeValue.OPENID.getValue(), OIDCScopeValue.OFFLINE_ACCESS.getValue());
    setUpDynamo(keyPair, scope, new Subject());
    var response = generateTokenRequest(keyPair, scope, vtr, Optional.empty());
    assertThat(response, hasStatus(200));
    JSONObject jsonResponse = JSONObjectUtils.parse(response.getBody());
    assertNotNull(TokenResponse.parse(jsonResponse).toSuccessResponse().getTokens().getRefreshToken());
    assertNotNull(TokenResponse.parse(jsonResponse).toSuccessResponse().getTokens().getBearerAccessToken());
    if (vtr.isEmpty()) {
        vtr = Optional.of(VectorOfTrust.getDefaults().getCredentialTrustLevel().getValue());
    }
    assertThat(OIDCTokenResponse.parse(jsonResponse).getOIDCTokens().getIDToken().getJWTClaimsSet().getClaim("vot"), equalTo(vtr.get()));
    assertNoAuditEventsReceived(auditTopic);
}
Also used : KeyPair(java.security.KeyPair) Scope(com.nimbusds.oauth2.sdk.Scope) JSONObject(net.minidev.json.JSONObject) Subject(com.nimbusds.oauth2.sdk.id.Subject) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest) MethodSource(org.junit.jupiter.params.provider.MethodSource)

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