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;
}
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;
}
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));
}
}
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);
}
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);
}
Aggregations