com.nimbusds.oauth2.sdk.http.HTTPRequest Java Examples

The following examples show how to use com.nimbusds.oauth2.sdk.http.HTTPRequest. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: OidcClient.java    From sonar-auth-oidc with Apache License 2.0 6 votes vote down vote up
public AuthorizationCode getAuthorizationCode(HttpServletRequest callbackRequest) {
  LOGGER.debug("Retrieving authorization code from callback request's query parameters: {}",
      callbackRequest.getQueryString());
  AuthenticationResponse authResponse = null;
  try {
    HTTPRequest request = ServletUtils.createHTTPRequest(callbackRequest);
    authResponse = AuthenticationResponseParser.parse(request.getURL().toURI(), request.getQueryParameters());
  } catch (ParseException | URISyntaxException | IOException e) {
    throw new IllegalStateException("Error while parsing callback request", e);
  }
  if (authResponse instanceof AuthenticationErrorResponse) {
    ErrorObject error = ((AuthenticationErrorResponse) authResponse).getErrorObject();
    throw new IllegalStateException("Authentication request failed: " + error.toJSONObject());
  }
  AuthorizationCode authorizationCode = ((AuthenticationSuccessResponse) authResponse).getAuthorizationCode();
  LOGGER.debug("Authorization code: {}", authorizationCode.getValue());
  return authorizationCode;
}
 
Example #2
Source File: ClientSecretGet.java    From OAuth-2.0-Cookbook with MIT License 6 votes vote down vote up
@Override
public void applyTo(final HTTPRequest httpRequest) {
    if (httpRequest.getMethod() != HTTPRequest.Method.GET)
        throw new SerializeException("The HTTP request method must be GET");

    ContentType ct = httpRequest.getContentType();
    if (ct == null)
        throw new SerializeException("Missing HTTP Content-Type header");

    if (! ct.match(CommonContentTypes.APPLICATION_URLENCODED))
        throw new SerializeException("The HTTP Content-Type header must be "
        + CommonContentTypes.APPLICATION_URLENCODED);

    Map<String,String> params = httpRequest.getQueryParameters();
    params.putAll(toParameters());
    String queryString = URLUtils.serializeParameters(params);
    httpRequest.setQuery(queryString);
}
 
Example #3
Source File: FacebookAuthorizationGrantTokenExchanger.java    From OAuth-2.0-Cookbook with MIT License 6 votes vote down vote up
private HTTPRequest createTokenRequest(ClientRegistration clientRegistration,
       AuthorizationGrant authorizationCodeGrant, URI tokenUri,
       ClientAuthentication clientAuthentication) throws MalformedURLException {

    HTTPRequest httpRequest = new HTTPRequest(HTTPRequest.Method.GET, tokenUri.toURL());
    httpRequest.setContentType(CommonContentTypes.APPLICATION_URLENCODED);
    clientAuthentication.applyTo(httpRequest);
    Map<String,String> params = httpRequest.getQueryParameters();
    params.putAll(authorizationCodeGrant.toParameters());
    if (clientRegistration.getScope() != null && !clientRegistration.getScope().isEmpty()) {
        params.put("scope", clientRegistration.getScope().stream().reduce((a, b) -> a + " " + b).get());
    }
    if (clientRegistration.getClientId() != null) {
        params.put("client_id", clientRegistration.getClientId());
    }
    httpRequest.setQuery(URLUtils.serializeParameters(params));
    httpRequest.setAccept(MediaType.APPLICATION_JSON_VALUE);
    httpRequest.setConnectTimeout(30000);
    httpRequest.setReadTimeout(30000);
    return httpRequest;
}
 
Example #4
Source File: StandardOidcIdentityProvider.java    From nifi with Apache License 2.0 5 votes vote down vote up
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);
}
 
Example #5
Source File: StandardOidcIdentityProvider.java    From nifi with Apache License 2.0 5 votes vote down vote up
private String lookupIdentityInUserInfo(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 identity = claimsSet.getStringClaim(properties.getOidcClaimIdentifyingUser());

            // ensure we were able to get the user's identity
            if (StringUtils.isBlank(identity)) {
                throw new IllegalStateException("Unable to extract identity from the UserInfo token using the claim '" +
                        properties.getOidcClaimIdentifyingUser() + "'.");
            } else {
                return identity;
            }
        } 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());
    }
}
 
Example #6
Source File: FacebookAuthorizationGrantTokenExchanger.java    From OAuth-2.0-Cookbook with MIT License 4 votes vote down vote up
@Override
public TokenResponseAttributes exchange(
    AuthorizationCodeAuthenticationToken authorizationCodeAuthenticationToken)
    throws OAuth2AuthenticationException {

    ClientRegistration clientRegistration = authorizationCodeAuthenticationToken.getClientRegistration();

    AuthorizationCode authorizationCode = new AuthorizationCode(
        authorizationCodeAuthenticationToken.getAuthorizationCode());
    AuthorizationGrant authorizationCodeGrant = new AuthorizationCodeGrant(
        authorizationCode, URI.create(clientRegistration.getRedirectUri()));
    URI tokenUri = URI.create(clientRegistration.getProviderDetails().getTokenUri());

    ClientID clientId = new ClientID(clientRegistration.getClientId());
    Secret clientSecret = new Secret(clientRegistration.getClientSecret());
    ClientAuthentication clientAuthentication = new ClientSecretGet(clientId, clientSecret);

    try {
        HTTPRequest httpRequest = createTokenRequest(
                clientRegistration, authorizationCodeGrant,
                tokenUri, clientAuthentication);

        TokenResponse tokenResponse = TokenResponse.parse(httpRequest.send());

        if (!tokenResponse.indicatesSuccess()) {
            OAuth2Error errorObject = new OAuth2Error("invalid_token_response");
            throw new OAuth2AuthenticationException(errorObject, "error");
        }

        return createTokenResponse((AccessTokenResponse) tokenResponse);

    } catch (MalformedURLException e) {
        throw new SerializeException(e.getMessage(), e);
    } catch (ParseException pe) {
        throw new OAuth2AuthenticationException(new OAuth2Error("invalid_token_response"), pe);
    } catch (IOException ioe) {
        throw new AuthenticationServiceException(
            "An error occurred while sending the Access Token Request: " +
            ioe.getMessage(), ioe);
    }

}