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