Search in sources :

Example 1 with HTTPResponse

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);
        }
    }
}
Also used : HTTPRequest(com.nimbusds.oauth2.sdk.http.HTTPRequest) TechnicalException(org.pac4j.core.exception.TechnicalException) HTTPResponse(com.nimbusds.oauth2.sdk.http.HTTPResponse) OIDCTokenResponse(com.nimbusds.openid.connect.sdk.OIDCTokenResponse) URISyntaxException(java.net.URISyntaxException) IOException(java.io.IOException) URI(java.net.URI) OIDCTokenResponse(com.nimbusds.openid.connect.sdk.OIDCTokenResponse) OIDCTokens(com.nimbusds.openid.connect.sdk.token.OIDCTokens)

Example 2 with HTTPResponse

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);
    }
}
Also used : HTTPRequest(com.nimbusds.oauth2.sdk.http.HTTPRequest) TechnicalException(org.pac4j.core.exception.TechnicalException) JWT(com.nimbusds.jwt.JWT) HTTPResponse(com.nimbusds.oauth2.sdk.http.HTTPResponse) IDTokenClaimsSet(com.nimbusds.openid.connect.sdk.claims.IDTokenClaimsSet) IOException(java.io.IOException) RefreshToken(com.nimbusds.oauth2.sdk.token.RefreshToken) BadJOSEException(com.nimbusds.jose.proc.BadJOSEException) AccessToken(com.nimbusds.oauth2.sdk.token.AccessToken) BearerAccessToken(com.nimbusds.oauth2.sdk.token.BearerAccessToken) JWTClaimsSet(com.nimbusds.jwt.JWTClaimsSet) ParseException(com.nimbusds.oauth2.sdk.ParseException) Map(java.util.Map) JOSEException(com.nimbusds.jose.JOSEException) BadJOSEException(com.nimbusds.jose.proc.BadJOSEException)

Example 3 with HTTPResponse

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);
}
Also used : HTTPResponse(com.nimbusds.oauth2.sdk.http.HTTPResponse) MediaType(org.springframework.http.MediaType)

Example 4 with HTTPResponse

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();
}
Also used : TokenErrorResponse(com.nimbusds.oauth2.sdk.TokenErrorResponse) HTTPRequest(com.nimbusds.oauth2.sdk.http.HTTPRequest) TechnicalException(org.pac4j.core.exception.TechnicalException) OIDCTokenResponse(com.nimbusds.openid.connect.sdk.OIDCTokenResponse) TokenResponse(com.nimbusds.oauth2.sdk.TokenResponse) HTTPResponse(com.nimbusds.oauth2.sdk.http.HTTPResponse) OIDCTokenResponse(com.nimbusds.openid.connect.sdk.OIDCTokenResponse) TokenRequest(com.nimbusds.oauth2.sdk.TokenRequest)

Example 5 with HTTPResponse

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);
}
Also used : HTTPRequest(com.nimbusds.oauth2.sdk.http.HTTPRequest) JSONObject(net.minidev.json.JSONObject) HTTPResponse(com.nimbusds.oauth2.sdk.http.HTTPResponse) IOException(java.io.IOException) URL(java.net.URL)

Aggregations

HTTPResponse (com.nimbusds.oauth2.sdk.http.HTTPResponse)8 HTTPRequest (com.nimbusds.oauth2.sdk.http.HTTPRequest)5 IOException (java.io.IOException)4 TechnicalException (org.pac4j.core.exception.TechnicalException)4 JWT (com.nimbusds.jwt.JWT)2 ParseException (com.nimbusds.oauth2.sdk.ParseException)2 AccessToken (com.nimbusds.oauth2.sdk.token.AccessToken)2 BearerAccessToken (com.nimbusds.oauth2.sdk.token.BearerAccessToken)2 RefreshToken (com.nimbusds.oauth2.sdk.token.RefreshToken)2 OIDCTokenResponse (com.nimbusds.openid.connect.sdk.OIDCTokenResponse)2 URI (java.net.URI)2 URISyntaxException (java.net.URISyntaxException)2 MediaType (org.springframework.http.MediaType)2 JOSEException (com.nimbusds.jose.JOSEException)1 BadJOSEException (com.nimbusds.jose.proc.BadJOSEException)1 JWTClaimsSet (com.nimbusds.jwt.JWTClaimsSet)1 PlainJWT (com.nimbusds.jwt.PlainJWT)1 AuthorizationCode (com.nimbusds.oauth2.sdk.AuthorizationCode)1 AuthorizationCodeGrant (com.nimbusds.oauth2.sdk.AuthorizationCodeGrant)1 AuthorizationGrant (com.nimbusds.oauth2.sdk.AuthorizationGrant)1