use of com.nimbusds.oauth2.sdk.http.HTTPRequest in project nifi by apache.
the class StandardOidcIdentityProvider method lookupEmail.
private String lookupEmail(final BearerAccessToken bearerAccessToken) throws IOException {
try {
// build the user request
final UserInfoRequest request = new UserInfoRequest(oidcProviderMetadata.getUserInfoEndpointURI(), bearerAccessToken);
final HTTPRequest tokenHttpRequest = request.toHTTPRequest();
tokenHttpRequest.setConnectTimeout(oidcConnectTimeout);
tokenHttpRequest.setReadTimeout(oidcReadTimeout);
// send the user request
final UserInfoResponse response = UserInfoResponse.parse(request.toHTTPRequest().send());
// interpret the details
if (response.indicatesSuccess()) {
final UserInfoSuccessResponse successResponse = (UserInfoSuccessResponse) response;
final JWTClaimsSet claimsSet;
if (successResponse.getUserInfo() != null) {
claimsSet = successResponse.getUserInfo().toJWTClaimsSet();
} else {
claimsSet = successResponse.getUserInfoJWT().getJWTClaimsSet();
}
final String email = claimsSet.getStringClaim(EMAIL_CLAIM_NAME);
// ensure we were able to get the user email
if (StringUtils.isBlank(email)) {
throw new IllegalStateException("Unable to extract email from the UserInfo token.");
} else {
return email;
}
} else {
final UserInfoErrorResponse errorResponse = (UserInfoErrorResponse) response;
throw new RuntimeException("An error occurred while invoking the UserInfo endpoint: " + errorResponse.getErrorObject().getDescription());
}
} catch (final ParseException | java.text.ParseException e) {
throw new RuntimeException("Unable to parse the response from the UserInfo token request: " + e.getMessage());
}
}
use of com.nimbusds.oauth2.sdk.http.HTTPRequest 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.HTTPRequest 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.HTTPRequest 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);
}
use of com.nimbusds.oauth2.sdk.http.HTTPRequest in project nifi by apache.
the class StandardOidcIdentityProvider method exchangeAuthorizationCode.
@Override
public String exchangeAuthorizationCode(final AuthorizationGrant authorizationGrant) throws IOException {
if (!isOidcEnabled()) {
throw new IllegalStateException(OPEN_ID_CONNECT_SUPPORT_IS_NOT_CONFIGURED);
}
final ClientAuthentication clientAuthentication;
if (oidcProviderMetadata.getTokenEndpointAuthMethods().contains(ClientAuthenticationMethod.CLIENT_SECRET_POST)) {
clientAuthentication = new ClientSecretPost(clientId, clientSecret);
} else {
clientAuthentication = new ClientSecretBasic(clientId, clientSecret);
}
try {
// build the token request
final TokenRequest request = new TokenRequest(oidcProviderMetadata.getTokenEndpointURI(), clientAuthentication, authorizationGrant, getScope());
final HTTPRequest tokenHttpRequest = request.toHTTPRequest();
tokenHttpRequest.setConnectTimeout(oidcConnectTimeout);
tokenHttpRequest.setReadTimeout(oidcReadTimeout);
// get the token response
final TokenResponse response = OIDCTokenResponseParser.parse(tokenHttpRequest.send());
if (response.indicatesSuccess()) {
final OIDCTokenResponse oidcTokenResponse = (OIDCTokenResponse) response;
final OIDCTokens oidcTokens = oidcTokenResponse.getOIDCTokens();
final JWT oidcJwt = oidcTokens.getIDToken();
// validate the token - no nonce required for authorization code flow
final IDTokenClaimsSet claimsSet = tokenValidator.validate(oidcJwt, null);
// attempt to extract the email from the id token if possible
String email = claimsSet.getStringClaim(EMAIL_CLAIM_NAME);
if (StringUtils.isBlank(email)) {
// extract the bearer access token
final BearerAccessToken bearerAccessToken = oidcTokens.getBearerAccessToken();
if (bearerAccessToken == null) {
throw new IllegalStateException("No access token found in the ID tokens");
}
// invoke the UserInfo endpoint
email = lookupEmail(bearerAccessToken);
}
// extract expiration details from the claims set
final Calendar now = Calendar.getInstance();
final Date expiration = claimsSet.getExpirationTime();
final long expiresIn = expiration.getTime() - now.getTimeInMillis();
// convert into a nifi jwt for retrieval later
final LoginAuthenticationToken loginToken = new LoginAuthenticationToken(email, email, expiresIn, claimsSet.getIssuer().getValue());
return jwtService.generateSignedToken(loginToken);
} else {
final TokenErrorResponse errorResponse = (TokenErrorResponse) response;
throw new RuntimeException("An error occurred while invoking the Token endpoint: " + errorResponse.getErrorObject().getDescription());
}
} catch (final ParseException | JOSEException | BadJOSEException e) {
throw new RuntimeException("Unable to parse the response from the Token request: " + e.getMessage());
}
}
Aggregations