Search in sources :

Example 6 with ParseException

use of com.nimbusds.oauth2.sdk.ParseException in project pac4j by pac4j.

the class OidcCredentialsTests method testSerialization.

@Test
public void testSerialization() throws ParseException {
    final OidcCredentials credentials = new OidcCredentials();
    credentials.setCode(new AuthorizationCode(VALUE));
    credentials.setAccessToken(new BearerAccessToken(VALUE, 0L, Scope.parse("oidc email")));
    credentials.setRefreshToken(new RefreshToken(VALUE));
    credentials.setIdToken(JWTParser.parse(ID_TOKEN));
    byte[] result = SerializationUtils.serialize(credentials);
    final OidcCredentials credentials2 = SerializationUtils.deserialize(result);
    assertEquals(credentials.getAccessToken(), credentials2.getAccessToken());
    assertEquals(credentials.getRefreshToken(), credentials2.getRefreshToken());
    assertEquals(credentials.getIdToken().getParsedString(), credentials2.getIdToken().getParsedString());
}
Also used : AuthorizationCode(com.nimbusds.oauth2.sdk.AuthorizationCode) RefreshToken(com.nimbusds.oauth2.sdk.token.RefreshToken) BearerAccessToken(com.nimbusds.oauth2.sdk.token.BearerAccessToken) Test(org.junit.Test)

Example 7 with ParseException

use of com.nimbusds.oauth2.sdk.ParseException 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)

Example 8 with ParseException

use of com.nimbusds.oauth2.sdk.ParseException 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());
    }
}
Also used : HTTPRequest(com.nimbusds.oauth2.sdk.http.HTTPRequest) JWT(com.nimbusds.jwt.JWT) OIDCTokenResponse(com.nimbusds.openid.connect.sdk.OIDCTokenResponse) Calendar(java.util.Calendar) IDTokenClaimsSet(com.nimbusds.openid.connect.sdk.claims.IDTokenClaimsSet) ClientSecretBasic(com.nimbusds.oauth2.sdk.auth.ClientSecretBasic) Date(java.util.Date) TokenErrorResponse(com.nimbusds.oauth2.sdk.TokenErrorResponse) ClientSecretPost(com.nimbusds.oauth2.sdk.auth.ClientSecretPost) OIDCTokenResponse(com.nimbusds.openid.connect.sdk.OIDCTokenResponse) TokenResponse(com.nimbusds.oauth2.sdk.TokenResponse) BadJOSEException(com.nimbusds.jose.proc.BadJOSEException) OIDCTokens(com.nimbusds.openid.connect.sdk.token.OIDCTokens) LoginAuthenticationToken(org.apache.nifi.web.security.token.LoginAuthenticationToken) TokenRequest(com.nimbusds.oauth2.sdk.TokenRequest) BearerAccessToken(com.nimbusds.oauth2.sdk.token.BearerAccessToken) ParseException(com.nimbusds.oauth2.sdk.ParseException) ClientAuthentication(com.nimbusds.oauth2.sdk.auth.ClientAuthentication) JOSEException(com.nimbusds.jose.JOSEException) BadJOSEException(com.nimbusds.jose.proc.BadJOSEException)

Example 9 with ParseException

use of com.nimbusds.oauth2.sdk.ParseException in project ORCID-Source by ORCID.

the class OpenIDConnectTest method testImplicitOauth.

@Test
public void testImplicitOauth() throws URISyntaxException, ParseException, JOSEException, JSONException, InvalidHashException {
    HashMap<String, String> requestParams = new HashMap<String, String>();
    requestParams.put("nonce", "yesMate");
    requestParams.put("state", "Boaty McBoatface");
    String response = getImplicitTokenResponse(Lists.newArrayList("openid"), requestParams, true);
    // check it's got a fragment
    assertTrue(response.contains("#"));
    // switch to query param for ease of parsing
    response = response.replace('#', '?');
    List<NameValuePair> params = URLEncodedUtils.parse(new URI(response), "UTF-8");
    Map<String, String> map = new HashMap<String, String>();
    for (NameValuePair pair : params) {
        map.put(pair.getName(), pair.getValue());
    }
    // guid length
    assertEquals(map.get("access_token").length(), 36);
    assertTrue(map.get("id_token") != null);
    assertEquals(map.get("token_type"), "bearer");
    assertEquals(map.get("name"), null);
    assertEquals(map.get("orcid"), null);
    assertEquals(map.get("state"), "Boaty McBoatface");
    // check expiry about 10 minutes
    assertTrue((Integer.parseInt(map.get("expires_in")) <= 600));
    assertTrue((Integer.parseInt(map.get("expires_in")) > 590));
    // check id_token
    SignedJWT signedJWT = checkJWT(map.get("id_token"));
    // check hash
    assertNotNull(signedJWT.getJWTClaimsSet().getClaim("at_hash"));
    AccessTokenValidator.validate(new BearerAccessToken(map.get("access_token")), JWSAlgorithm.RS256, new AccessTokenHash(signedJWT.getJWTClaimsSet().getClaim("at_hash").toString()));
    // check access token works
    Client client = Client.create();
    WebResource webResource = client.resource(baseUri + "/oauth/userinfo");
    ClientResponse userInfo = webResource.header("Authorization", "Bearer " + map.get("access_token")).accept(MediaType.APPLICATION_JSON).get(ClientResponse.class);
    String userInfoString = userInfo.getEntity(String.class);
    JSONObject user = new JSONObject(userInfoString);
    Assert.assertEquals("9999-0000-0000-0004", user.get("sub"));
}
Also used : ClientResponse(com.sun.jersey.api.client.ClientResponse) NameValuePair(org.apache.http.NameValuePair) HashMap(java.util.HashMap) WebResource(com.sun.jersey.api.client.WebResource) SignedJWT(com.nimbusds.jwt.SignedJWT) URI(java.net.URI) AccessTokenHash(com.nimbusds.openid.connect.sdk.claims.AccessTokenHash) JSONObject(org.codehaus.jettison.json.JSONObject) BearerAccessToken(com.nimbusds.oauth2.sdk.token.BearerAccessToken) Client(com.sun.jersey.api.client.Client) Test(org.junit.Test)

Example 10 with ParseException

use of com.nimbusds.oauth2.sdk.ParseException in project pac4j by pac4j.

the class AzureAdIdTokenValidator method validate.

@Override
public IDTokenClaimsSet validate(final JWT idToken, final Nonce expectedNonce) throws BadJOSEException, JOSEException {
    try {
        if (originalIssuer.contains("%7Btenantid%7D")) {
            Object tid = idToken.getJWTClaimsSet().getClaim("tid");
            if (tid == null) {
                throw new BadJWTException("ID token does not contain the 'tid' claim");
            }
            base = new IDTokenValidator(new Issuer(originalIssuer.replace("%7Btenantid%7D", tid.toString())), base.getClientID(), base.getJWSKeySelector(), base.getJWEKeySelector());
            base.setMaxClockSkew(getMaxClockSkew());
        }
    } catch (ParseException e) {
        throw new BadJWTException(e.getMessage(), e);
    }
    return base.validate(idToken, expectedNonce);
}
Also used : Issuer(com.nimbusds.oauth2.sdk.id.Issuer) BadJWTException(com.nimbusds.jwt.proc.BadJWTException) ParseException(java.text.ParseException) IDTokenValidator(com.nimbusds.openid.connect.sdk.validators.IDTokenValidator)

Aggregations

ParseException (com.nimbusds.oauth2.sdk.ParseException)5 HTTPRequest (com.nimbusds.oauth2.sdk.http.HTTPRequest)5 BearerAccessToken (com.nimbusds.oauth2.sdk.token.BearerAccessToken)4 JWT (com.nimbusds.jwt.JWT)3 AuthorizationCode (com.nimbusds.oauth2.sdk.AuthorizationCode)3 HTTPResponse (com.nimbusds.oauth2.sdk.http.HTTPResponse)3 IOException (java.io.IOException)3 URI (java.net.URI)3 TechnicalException (org.pac4j.core.exception.TechnicalException)3 JOSEException (com.nimbusds.jose.JOSEException)2 BadJOSEException (com.nimbusds.jose.proc.BadJOSEException)2 JWTClaimsSet (com.nimbusds.jwt.JWTClaimsSet)2 State (com.nimbusds.oauth2.sdk.id.State)2 AccessToken (com.nimbusds.oauth2.sdk.token.AccessToken)2 RefreshToken (com.nimbusds.oauth2.sdk.token.RefreshToken)2 OIDCTokenResponse (com.nimbusds.openid.connect.sdk.OIDCTokenResponse)2 IDTokenClaimsSet (com.nimbusds.openid.connect.sdk.claims.IDTokenClaimsSet)2 OIDCTokens (com.nimbusds.openid.connect.sdk.token.OIDCTokens)2 URISyntaxException (java.net.URISyntaxException)2 SignedJWT (com.nimbusds.jwt.SignedJWT)1