Search in sources :

Example 16 with Subject

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

the class OAuthPlugin method process.

/**
 * Verifies that a source configured to use OAuth has a valid access token to process and that the
 * user has authorized the use of their data against this source.
 *
 * @param source source being queried
 * @param input query request
 * @throws OAuthPluginException if the user's access token is not available or if the source is
 *     not authorized
 * @throws StopProcessingException for errors not related to OAuth
 */
@Override
public QueryRequest process(Source source, QueryRequest input) throws StopProcessingException {
    OAuthFederatedSource oauthSource = getSource(source);
    if (oauthSource == null) {
        return input;
    }
    Object securityAssertion = input.getProperties().get(SECURITY_SUBJECT);
    if (!(securityAssertion instanceof Subject)) {
        LOGGER.warn("The user's subject is not available.");
        throw new StopProcessingException("The user's subject is not available.");
    }
    Subject subject = (Subject) securityAssertion;
    Session session = subject.getSession(false);
    if (session == null) {
        LOGGER.warn("The user's session is not available.");
        throw new StopProcessingException("The user's session is not available.");
    }
    String sessionId = (String) session.getId();
    if (sessionId == null) {
        LOGGER.warn("The user's session ID is not available.");
        throw new StopProcessingException("The user's session ID is not available.");
    }
    OIDCProviderMetadata metadata;
    try {
        metadata = OIDCProviderMetadata.parse(resourceRetriever.retrieveResource(new URL(oauthSource.getOauthDiscoveryUrl())).getContent());
    } catch (OAuthServiceException | IOException | ParseException e) {
        LOGGER.error("Unable to retrieve OAuth provider's metadata for the {} source.", oauthSource.getId());
        throw new StopProcessingException("Unable to retrieve OAuth provider's metadata.");
    }
    TokenEntry tokenEntry = tokenStorage.read(sessionId, oauthSource.getId());
    if (tokenEntry == null) {
        // See if the user already logged in to the OAuth provider for a different source
        findExistingTokens(oauthSource, sessionId, metadata);
        throw createNoAuthException(oauthSource, sessionId, metadata, "the user's tokens were not found.");
    }
    // an outdated token)
    if (!oauthSource.getOauthDiscoveryUrl().equals(tokenEntry.getDiscoveryUrl())) {
        // the discoveryUrl is different from the one stored - the user must login
        tokenStorage.delete(sessionId, oauthSource.getId());
        findExistingTokens(oauthSource, sessionId, metadata);
        throw createNoAuthException(oauthSource, sessionId, metadata, "the oauth provider information has been changed and is different from the one stored.");
    }
    verifyAccessToken(oauthSource, sessionId, tokenEntry, metadata);
    return input;
}
Also used : OAuthFederatedSource(ddf.catalog.source.OAuthFederatedSource) OAuthServiceException(org.apache.cxf.rs.security.oauth2.provider.OAuthServiceException) StopProcessingException(ddf.catalog.plugin.StopProcessingException) IOException(java.io.IOException) Subject(ddf.security.Subject) URL(java.net.URL) DISCOVERY_URL(org.codice.ddf.security.token.storage.api.TokenStorage.DISCOVERY_URL) TokenEntry(org.codice.ddf.security.token.storage.api.TokenInformation.TokenEntry) OIDCProviderMetadata(com.nimbusds.openid.connect.sdk.op.OIDCProviderMetadata) ParseException(com.nimbusds.oauth2.sdk.ParseException) Session(org.apache.shiro.session.Session)

Example 17 with Subject

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

the class TokenService method generateAndStoreRefreshToken.

private RefreshToken generateAndStoreRefreshToken(String clientId, Subject internalSubject, List<String> scopes, Subject subject) {
    LOG.info("Generating RefreshToken");
    Date expiryDate = NowHelper.nowPlus(configService.getSessionExpiry(), ChronoUnit.SECONDS);
    var jwtId = IdGenerator.generate();
    JWTClaimsSet claimsSet = new JWTClaimsSet.Builder().claim("scope", scopes).issuer(configService.getOidcApiBaseURL().get()).expirationTime(expiryDate).issueTime(NowHelper.now()).claim("client_id", clientId).subject(subject.getValue()).jwtID(jwtId).build();
    SignedJWT signedJWT = generateSignedJWT(claimsSet, Optional.empty());
    RefreshToken refreshToken = new RefreshToken(signedJWT.serialize());
    String redisKey = REFRESH_TOKEN_PREFIX + jwtId;
    var store = new RefreshTokenStore(refreshToken.getValue(), internalSubject.toString());
    try {
        redisConnectionService.saveWithExpiry(redisKey, objectMapper.writeValueAsString(store), configService.getSessionExpiry());
    } catch (JsonException e) {
        throw new RuntimeException("Error serializing refresh token store", e);
    }
    return refreshToken;
}
Also used : JsonException(uk.gov.di.authentication.shared.serialization.Json.JsonException) RefreshTokenStore(uk.gov.di.authentication.shared.entity.RefreshTokenStore) RefreshToken(com.nimbusds.oauth2.sdk.token.RefreshToken) JWTClaimsSet(com.nimbusds.jwt.JWTClaimsSet) SignedJWT(com.nimbusds.jwt.SignedJWT) HashHelper.hashSha256String(uk.gov.di.authentication.shared.helpers.HashHelper.hashSha256String) Date(java.util.Date)

Example 18 with Subject

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

the class TokenService method generateTokenResponse.

public OIDCTokenResponse generateTokenResponse(String clientID, Subject internalSubject, Scope authRequestScopes, Map<String, Object> additionalTokenClaims, Subject subject, String vot, List<ClientConsent> clientConsents, boolean isConsentRequired, OIDCClaimsRequest claimsRequest, boolean isDocAppJourney) {
    List<String> scopesForToken;
    if (isConsentRequired) {
        scopesForToken = calculateScopesForToken(clientConsents, clientID, authRequestScopes);
    } else {
        scopesForToken = authRequestScopes.toStringList();
    }
    AccessToken accessToken = segmentedFunctionCall("generateAndStoreAccessToken", () -> generateAndStoreAccessToken(clientID, internalSubject, scopesForToken, subject, claimsRequest));
    AccessTokenHash accessTokenHash = segmentedFunctionCall("AccessTokenHash.compute", () -> AccessTokenHash.compute(accessToken, TOKEN_ALGORITHM, null));
    SignedJWT idToken = segmentedFunctionCall("generateIDToken", () -> generateIDToken(clientID, subject, additionalTokenClaims, accessTokenHash, vot, isDocAppJourney));
    if (scopesForToken.contains(OIDCScopeValue.OFFLINE_ACCESS.getValue())) {
        RefreshToken refreshToken = segmentedFunctionCall("generateAndStoreRefreshToken", () -> generateAndStoreRefreshToken(clientID, internalSubject, scopesForToken, subject));
        return new OIDCTokenResponse(new OIDCTokens(idToken, accessToken, refreshToken));
    } else {
        return new OIDCTokenResponse(new OIDCTokens(idToken, accessToken, null));
    }
}
Also used : AccessTokenHash(com.nimbusds.openid.connect.sdk.claims.AccessTokenHash) RefreshToken(com.nimbusds.oauth2.sdk.token.RefreshToken) AccessToken(com.nimbusds.oauth2.sdk.token.AccessToken) BearerAccessToken(com.nimbusds.oauth2.sdk.token.BearerAccessToken) OIDCTokenResponse(com.nimbusds.openid.connect.sdk.OIDCTokenResponse) OIDCTokens(com.nimbusds.openid.connect.sdk.token.OIDCTokens) HashHelper.hashSha256String(uk.gov.di.authentication.shared.helpers.HashHelper.hashSha256String) SignedJWT(com.nimbusds.jwt.SignedJWT)

Example 19 with Subject

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

the class ClientSubjectHelperTest method shouldReturnSameSubjectIDForMultipleClientsWithPublicSubjectType.

@Test
void shouldReturnSameSubjectIDForMultipleClientsWithPublicSubjectType() {
    KeyPair keyPair = generateRsaKeyPair();
    UserProfile userProfile = generateUserProfile();
    ClientRegistry clientRegistry1 = generateClientRegistryPairwise(keyPair, "test-client-id-1", "public", "https://test.com");
    ClientRegistry clientRegistry2 = generateClientRegistryPairwise(keyPair, "test-client-id-2", "public", "https://test.com");
    Subject subject1 = ClientSubjectHelper.getSubject(userProfile, clientRegistry1, authenticationService);
    Subject subject2 = ClientSubjectHelper.getSubject(userProfile, clientRegistry2, authenticationService);
    assertEquals(subject1, subject2);
}
Also used : KeyPair(java.security.KeyPair) UserProfile(uk.gov.di.authentication.shared.entity.UserProfile) ClientRegistry(uk.gov.di.authentication.shared.entity.ClientRegistry) Subject(com.nimbusds.oauth2.sdk.id.Subject) Test(org.junit.jupiter.api.Test)

Example 20 with Subject

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

the class ClientSubjectHelperTest method shouldReturnSameSubjectIDForMultipleClientsWithSameSector.

@Test
void shouldReturnSameSubjectIDForMultipleClientsWithSameSector() {
    stubAuthenticationService();
    KeyPair keyPair = generateRsaKeyPair();
    UserProfile userProfile = generateUserProfile();
    ClientRegistry clientRegistry1 = generateClientRegistryPairwise(keyPair, "test-client-id-1", "pairwise", "https://test.com");
    ClientRegistry clientRegistry2 = generateClientRegistryPairwise(keyPair, "test-client-id-2", "pairwise", "https://test.com");
    Subject subject1 = ClientSubjectHelper.getSubject(userProfile, clientRegistry1, authenticationService);
    Subject subject2 = ClientSubjectHelper.getSubject(userProfile, clientRegistry2, authenticationService);
    assertEquals(subject1, subject2);
}
Also used : KeyPair(java.security.KeyPair) UserProfile(uk.gov.di.authentication.shared.entity.UserProfile) ClientRegistry(uk.gov.di.authentication.shared.entity.ClientRegistry) Subject(com.nimbusds.oauth2.sdk.id.Subject) Test(org.junit.jupiter.api.Test)

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