use of com.nimbusds.oauth2.sdk.http.HTTPResponse in project pac4j by pac4j.
the class OidcAuthenticator method validate.
@Override
public void validate(final OidcCredentials credentials, final WebContext context) {
final AuthorizationCode code = credentials.getCode();
// if we have a code
if (code != null) {
try {
final String computedCallbackUrl = client.computeFinalCallbackUrl(context);
// Token request
final TokenRequest request = new TokenRequest(configuration.findProviderMetadata().getTokenEndpointURI(), this.clientAuthentication, new AuthorizationCodeGrant(code, new URI(computedCallbackUrl)));
HTTPRequest tokenHttpRequest = request.toHTTPRequest();
tokenHttpRequest.setConnectTimeout(configuration.getConnectTimeout());
tokenHttpRequest.setReadTimeout(configuration.getReadTimeout());
final HTTPResponse httpResponse = tokenHttpRequest.send();
logger.debug("Token response: status={}, content={}", httpResponse.getStatusCode(), httpResponse.getContent());
final TokenResponse response = OIDCTokenResponseParser.parse(httpResponse);
if (response instanceof TokenErrorResponse) {
throw new TechnicalException("Bad token response, error=" + ((TokenErrorResponse) response).getErrorObject());
}
logger.debug("Token response successful");
final OIDCTokenResponse tokenSuccessResponse = (OIDCTokenResponse) response;
// save tokens in credentials
final OIDCTokens oidcTokens = tokenSuccessResponse.getOIDCTokens();
credentials.setAccessToken(oidcTokens.getAccessToken());
credentials.setRefreshToken(oidcTokens.getRefreshToken());
credentials.setIdToken(oidcTokens.getIDToken());
} catch (final URISyntaxException | IOException | ParseException e) {
throw new TechnicalException(e);
}
}
}
use of com.nimbusds.oauth2.sdk.http.HTTPResponse 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.http.HTTPResponse in project spring-security by spring-projects.
the class NimbusReactiveOpaqueTokenIntrospector method adaptToNimbusResponse.
private Mono<HTTPResponse> adaptToNimbusResponse(ClientResponse responseEntity) {
MediaType contentType = responseEntity.headers().contentType().orElseThrow(() -> {
this.logger.trace("Did not receive Content-Type from introspection endpoint in response");
return new OAuth2IntrospectionException("Introspection endpoint response was invalid, as no Content-Type header was provided");
});
// Nimbus expects JSON, but does not appear to validate this header first.
if (!contentType.isCompatibleWith(MediaType.APPLICATION_JSON)) {
this.logger.trace("Did not receive JSON-compatible Content-Type from introspection endpoint in response");
throw new OAuth2IntrospectionException("Introspection endpoint response was invalid, as content type '" + contentType + "' is not compatible with JSON");
}
HTTPResponse response = new HTTPResponse(responseEntity.rawStatusCode());
response.setHeader(HttpHeaders.CONTENT_TYPE, contentType.toString());
if (response.getStatusCode() != HTTPResponse.SC_OK) {
this.logger.trace("Introspection endpoint returned non-OK status code");
// @formatter:off
return responseEntity.bodyToFlux(DataBuffer.class).map(DataBufferUtils::release).then(Mono.error(new OAuth2IntrospectionException("Introspection endpoint responded with HTTP status code " + response.getStatusCode())));
// @formatter:on
}
return responseEntity.bodyToMono(String.class).doOnNext(response::setContent).map((body) -> response);
}
use of com.nimbusds.oauth2.sdk.http.HTTPResponse in project ddf by codice.
the class OidcCredentialsResolver method getOidcTokens.
public static OIDCTokens getOidcTokens(AuthorizationGrant grant, OIDCProviderMetadata metadata, ClientAuthentication clientAuthentication, int connectTimeout, int readTimeout) throws IOException, ParseException {
final TokenRequest request = new TokenRequest(metadata.getTokenEndpointURI(), clientAuthentication, grant);
HTTPRequest tokenHttpRequest = request.toHTTPRequest();
tokenHttpRequest.setConnectTimeout(connectTimeout);
tokenHttpRequest.setReadTimeout(readTimeout);
final HTTPResponse httpResponse = tokenHttpRequest.send();
LOGGER.debug("Token response: status={}, content={}", httpResponse.getStatusCode(), httpResponse.getContent());
final TokenResponse response = OIDCTokenResponseParser.parse(httpResponse);
if (response instanceof TokenErrorResponse) {
throw new TechnicalException("Bad token response, error=" + ((TokenErrorResponse) response).getErrorObject());
}
LOGGER.debug("Token response successful");
final OIDCTokenResponse tokenSuccessResponse = (OIDCTokenResponse) response;
return tokenSuccessResponse.getOIDCTokens();
}
use of com.nimbusds.oauth2.sdk.http.HTTPResponse in project nifi by apache.
the class StandardOidcIdentityProvider method retrieveOidcProviderMetadata.
private OIDCProviderMetadata retrieveOidcProviderMetadata(final String discoveryUri) throws IOException, ParseException {
final URL url = new URL(discoveryUri);
final HTTPRequest httpRequest = new HTTPRequest(HTTPRequest.Method.GET, url);
httpRequest.setConnectTimeout(oidcConnectTimeout);
httpRequest.setReadTimeout(oidcReadTimeout);
final HTTPResponse httpResponse = httpRequest.send();
if (httpResponse.getStatusCode() != 200) {
throw new IOException("Unable to download OpenId Connect Provider metadata from " + url + ": Status code " + httpResponse.getStatusCode());
}
final JSONObject jsonObject = httpResponse.getContentAsJSONObject();
return OIDCProviderMetadata.parse(jsonObject);
}
Aggregations