com.nimbusds.oauth2.sdk.AuthorizationGrant Java Examples

The following examples show how to use com.nimbusds.oauth2.sdk.AuthorizationGrant. 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: 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 #2
Source File: OidcService.java    From nifi with Apache License 2.0 6 votes vote down vote up
/**
 * Exchanges the specified authorization grant for an ID token for the given request identifier.
 *
 * @param oidcRequestIdentifier request identifier
 * @param authorizationGrant authorization grant
 * @throws IOException exceptional case for communication error with the OpenId Connect provider
 */
public void exchangeAuthorizationCode(final String oidcRequestIdentifier, final AuthorizationGrant authorizationGrant) throws IOException {
    if (!isOidcEnabled()) {
        throw new IllegalStateException(OPEN_ID_CONNECT_SUPPORT_IS_NOT_CONFIGURED);
    }

    final CacheKey oidcRequestIdentifierKey = new CacheKey(oidcRequestIdentifier);
    final String nifiJwt = identityProvider.exchangeAuthorizationCode(authorizationGrant);

    try {
        // cache the jwt for later retrieval
        synchronized (jwtLookupForCompletedRequests) {
            final String cachedJwt = jwtLookupForCompletedRequests.get(oidcRequestIdentifierKey, () -> nifiJwt);
            if (!timeConstantEqualityCheck(nifiJwt, cachedJwt)) {
                throw new IllegalStateException("An existing login request is already in progress.");
            }
        }
    } catch (final ExecutionException e) {
        throw new IllegalStateException("Unable to store the login authentication token.");
    }
}
 
Example #3
Source File: OpenIdConnector.java    From onedev with MIT License 4 votes vote down vote up
@Override
public SsoAuthenticated processLoginResponse() {
	HttpServletRequest request = (HttpServletRequest) RequestCycle.get().getRequest().getContainerRequest();
	try {
		AuthenticationResponse authenticationResponse = AuthenticationResponseParser.parse(
				new URI(request.getRequestURI() + "?" + request.getQueryString()));
		if (authenticationResponse instanceof AuthenticationErrorResponse) {
			throw buildException(((AuthenticationErrorResponse)authenticationResponse).getErrorObject()); 
		} else {
			AuthenticationSuccessResponse authenticationSuccessResponse = 
					(AuthenticationSuccessResponse)authenticationResponse;
			
			String state = (String) Session.get().getAttribute(SESSION_ATTR_STATE);
			
			if (state == null || !state.equals(authenticationSuccessResponse.getState().getValue()))
				throw new AuthenticationException("Unsolicited OIDC authentication response");
			
			AuthorizationGrant codeGrant = new AuthorizationCodeGrant(
					authenticationSuccessResponse.getAuthorizationCode(), getCallbackUri());

			ClientID clientID = new ClientID(getClientId());
			Secret clientSecret = new Secret(getClientSecret());
			ClientAuthentication clientAuth = new ClientSecretBasic(clientID, clientSecret);
			TokenRequest tokenRequest = new TokenRequest(
					new URI(getCachedProviderMetadata().getTokenEndpoint()), clientAuth, codeGrant);
			HTTPResponse httpResponse = tokenRequest.toHTTPRequest().send();
			if (httpResponse.getStatusCode() == HTTPResponse.SC_OK) {
				JSONObject jsonObject = httpResponse.getContentAsJSONObject();
				if (jsonObject.get("error") != null) 
					throw buildException(TokenErrorResponse.parse(jsonObject).getErrorObject());
				else 
					return processTokenResponse(OIDCAccessTokenResponse.parse(jsonObject));
			} else {
				ErrorObject error = TokenErrorResponse.parse(httpResponse).getErrorObject();
				if (error != null) {
					throw buildException(error);
				} else {
					String message = String.format("Error requesting OIDC token: http status: %d", 
							httpResponse.getStatusCode());
					throw new AuthenticationException(message);
				}
			}
		}
	} catch (ParseException | URISyntaxException|SerializeException|IOException e) {
		throw new RuntimeException(e);
	}
}
 
Example #4
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);
    }

}
 
Example #5
Source File: OidcIdentityProvider.java    From nifi with Apache License 2.0 2 votes vote down vote up
/**
 * Exchanges the supplied authorization grant for an ID token. Extracts the identity from the ID
 * token and converts it into NiFi JWT.
 *
 * @param authorizationGrant authorization grant for invoking the Token Endpoint
 * @return a NiFi JWT
 * @throws IOException if there was an exceptional error while communicating with the OIDC provider
 */
String exchangeAuthorizationCode(AuthorizationGrant authorizationGrant) throws IOException;