use of com.nimbusds.oauth2.sdk.token.AccessToken in project iaf by ibissource.
the class OAuthAccessTokenManager method parseResponse.
private void parseResponse(HTTPResponse httpResponse, String responseBody) throws HttpAuthenticationException {
try {
TokenResponse response = TokenResponse.parse(httpResponse);
if (!response.indicatesSuccess()) {
// We got an error response...
TokenErrorResponse errorResponse = response.toErrorResponse();
throw new HttpAuthenticationException(errorResponse.toJSONObject().toString());
}
AccessTokenResponse successResponse = response.toSuccessResponse();
// Get the access token
accessToken = successResponse.getTokens().getAccessToken();
// accessToken will be refreshed when it is half way expiration
accessTokenRefreshTime = System.currentTimeMillis() + expiryMs < 0 ? 500 * accessToken.getLifetime() : expiryMs;
} catch (ParseException e) {
throw new HttpAuthenticationException("Could not parse TokenResponse: " + responseBody, e);
}
}
use of com.nimbusds.oauth2.sdk.token.AccessToken in project pac4j by pac4j.
the class OidcExtractor method extract.
@Override
public OidcCredentials extract(final WebContext context) {
final String computedCallbackUrl = client.computeFinalCallbackUrl(context);
final Map<String, String> parameters = retrieveParameters(context);
AuthenticationResponse response;
try {
response = AuthenticationResponseParser.parse(new URI(computedCallbackUrl), parameters);
} catch (final URISyntaxException | ParseException e) {
throw new TechnicalException(e);
}
if (response instanceof AuthenticationErrorResponse) {
logger.error("Bad authentication response, error={}", ((AuthenticationErrorResponse) response).getErrorObject());
return null;
}
logger.debug("Authentication response successful");
AuthenticationSuccessResponse successResponse = (AuthenticationSuccessResponse) response;
final State state = successResponse.getState();
if (state == null) {
throw new TechnicalException("Missing state parameter");
}
if (!state.equals(context.getSessionStore().get(context, OidcConfiguration.STATE_SESSION_ATTRIBUTE))) {
throw new TechnicalException("State parameter is different from the one sent in authentication request. " + "Session expired or possible threat of cross-site request forgery");
}
final OidcCredentials credentials = new OidcCredentials();
// get authorization code
final AuthorizationCode code = successResponse.getAuthorizationCode();
if (code != null) {
credentials.setCode(code);
}
// get ID token
final JWT idToken = successResponse.getIDToken();
if (idToken != null) {
credentials.setIdToken(idToken);
}
// get access token
final AccessToken accessToken = successResponse.getAccessToken();
if (accessToken != null) {
credentials.setAccessToken(accessToken);
}
return credentials;
}
use of com.nimbusds.oauth2.sdk.token.AccessToken in project pac4j by pac4j.
the class OidcProfileCreator method create.
@Override
@SuppressWarnings("unchecked")
public U create(final OidcCredentials credentials, final WebContext context) {
init();
final AccessToken accessToken = credentials.getAccessToken();
// Create profile
final U profile = getProfileDefinition().newProfile();
profile.setAccessToken(accessToken);
final JWT idToken = credentials.getIdToken();
profile.setIdTokenString(idToken.getParsedString());
// Check if there is a refresh token
final RefreshToken refreshToken = credentials.getRefreshToken();
if (refreshToken != null && !refreshToken.getValue().isEmpty()) {
profile.setRefreshToken(refreshToken);
logger.debug("Refresh Token successful retrieved");
}
try {
// check idToken
final Nonce nonce;
if (configuration.isUseNonce()) {
nonce = new Nonce((String) context.getSessionStore().get(context, OidcConfiguration.NONCE_SESSION_ATTRIBUTE));
} else {
nonce = null;
}
// Check ID Token
final IDTokenClaimsSet claimsSet = this.idTokenValidator.validate(idToken, nonce);
assertNotNull("claimsSet", claimsSet);
profile.setId(ProfileHelper.sanitizeIdentifier(profile, claimsSet.getSubject()));
// User Info request
if (configuration.findProviderMetadata().getUserInfoEndpointURI() != null && accessToken != null) {
final UserInfoRequest userInfoRequest = new UserInfoRequest(configuration.findProviderMetadata().getUserInfoEndpointURI(), (BearerAccessToken) accessToken);
final HTTPRequest userInfoHttpRequest = userInfoRequest.toHTTPRequest();
userInfoHttpRequest.setConnectTimeout(configuration.getConnectTimeout());
userInfoHttpRequest.setReadTimeout(configuration.getReadTimeout());
final HTTPResponse httpResponse = userInfoHttpRequest.send();
logger.debug("Token response: status={}, content={}", httpResponse.getStatusCode(), httpResponse.getContent());
final UserInfoResponse userInfoResponse = UserInfoResponse.parse(httpResponse);
if (userInfoResponse instanceof UserInfoErrorResponse) {
logger.error("Bad User Info response, error={}", ((UserInfoErrorResponse) userInfoResponse).getErrorObject());
} else {
final UserInfoSuccessResponse userInfoSuccessResponse = (UserInfoSuccessResponse) userInfoResponse;
final JWTClaimsSet userInfoClaimsSet;
if (userInfoSuccessResponse.getUserInfo() != null) {
userInfoClaimsSet = userInfoSuccessResponse.getUserInfo().toJWTClaimsSet();
} else {
userInfoClaimsSet = userInfoSuccessResponse.getUserInfoJWT().getJWTClaimsSet();
}
getProfileDefinition().convertAndAdd(profile, userInfoClaimsSet.getClaims(), null);
}
}
// add attributes of the ID token if they don't already exist
for (final Map.Entry<String, Object> entry : idToken.getJWTClaimsSet().getClaims().entrySet()) {
final String key = entry.getKey();
final Object value = entry.getValue();
// it's not the subject and this attribute does not already exist, add it
if (!JwtClaims.SUBJECT.equals(key) && profile.getAttribute(key) == null) {
getProfileDefinition().convertAndAdd(profile, PROFILE_ATTRIBUTE, key, value);
}
}
return profile;
} catch (final IOException | ParseException | JOSEException | BadJOSEException | java.text.ParseException e) {
throw new TechnicalException(e);
}
}
use of com.nimbusds.oauth2.sdk.token.AccessToken in project pac4j by pac4j.
the class OidcProfileTests method testReadWriteObjectNullIdToken.
/**
* Test that serialization and deserialization of the OidcProfile work when the Id token is null.
*/
@Test
public void testReadWriteObjectNullIdToken() {
OidcProfile profile = new OidcProfile();
profile.setAccessToken(populatedAccessToken);
profile.setRefreshToken(new RefreshToken(REFRESH_TOKEN));
byte[] result = SerializationUtils.serialize(profile);
profile = SerializationUtils.deserialize(result);
assertNotNull("accessToken", profile.getAccessToken());
assertNotNull("value", profile.getAccessToken().getValue());
assertEquals(profile.getAccessToken().getLifetime(), populatedAccessToken.getLifetime());
assertEquals(profile.getAccessToken().getScope(), populatedAccessToken.getScope());
assertEquals(profile.getRefreshToken().getValue(), REFRESH_TOKEN);
assertNull(profile.getIdTokenString());
}
use of com.nimbusds.oauth2.sdk.token.AccessToken in project pac4j by pac4j.
the class OidcProfileTests method testReadWriteObject.
@Test
public void testReadWriteObject() {
OidcProfile profile = new OidcProfile();
profile.setAccessToken(populatedAccessToken);
profile.setIdTokenString(ID_TOKEN);
profile.setRefreshToken(new RefreshToken(REFRESH_TOKEN));
byte[] result = SerializationUtils.serialize(profile);
profile = SerializationUtils.deserialize(result);
assertNotNull("accessToken", profile.getAccessToken());
assertNotNull("value", profile.getAccessToken().getValue());
assertEquals(profile.getAccessToken().getLifetime(), populatedAccessToken.getLifetime());
assertEquals(profile.getAccessToken().getScope(), populatedAccessToken.getScope());
assertEquals(profile.getIdTokenString(), ID_TOKEN);
assertEquals(profile.getRefreshToken().getValue(), REFRESH_TOKEN);
}
Aggregations