Java源码示例:org.apache.cxf.rs.security.oauth2.provider.OAuthJSONProvider

示例1
@Test
public void getPasswordTokenNoClient() {
    final Client client = ClientBuilder.newClient().register(new OAuthJSONProvider());
    try {
        final ClientAccessToken token = client.target("http://localhost:" + MEECROWAVE.getConfiguration().getHttpPort())
                .path("oauth2/token")
                .request(APPLICATION_JSON_TYPE)
                .post(entity(
                        new Form()
                                .param("grant_type", "password")
                                .param("username", "test")
                                .param("password", "pwd"), APPLICATION_FORM_URLENCODED_TYPE), ClientAccessToken.class);
        assertNotNull(token);
        assertEquals("Bearer", token.getTokenType());
        assertNotNull(token.getTokenKey());
        assertIsJwt(token.getTokenKey(), "__default");
        assertEquals(3600, token.getExpiresIn());
        assertNotEquals(0, token.getIssuedAt());
        assertNotNull(token.getRefreshToken());
        validateJwt(token);
    } finally {
        client.close();
    }
}
 
示例2
private static ClientAccessToken getAccessToken(PrivateKey privateKey, String issuer) {
    JwsHeaders headers = new JwsHeaders(JoseType.JWT, SignatureAlgorithm.RS256);
    JwtClaims claims = new JwtClaims();
    claims.setIssuer(issuer);
    claims.setAudience("https://www.googleapis.com/oauth2/v3/token");

    long issuedAt = OAuthUtils.getIssuedAt();
    claims.setIssuedAt(issuedAt);
    claims.setExpiryTime(issuedAt + 60 * 60);
    claims.setProperty("scope", "https://www.googleapis.com/auth/bigquery.readonly");

    JwtToken token = new JwtToken(headers, claims);
    JwsJwtCompactProducer p = new JwsJwtCompactProducer(token);
    String base64UrlAssertion = p.signWith(privateKey);

    JwtBearerGrant grant = new JwtBearerGrant(base64UrlAssertion);

    WebClient accessTokenService = WebClient.create("https://www.googleapis.com/oauth2/v3/token",
                                                    Arrays.asList(new OAuthJSONProvider(),
                                                                  new AccessTokenGrantWriter()));
    WebClient.getConfig(accessTokenService).getInInterceptors().add(new LoggingInInterceptor());

    accessTokenService.type(MediaType.APPLICATION_FORM_URLENCODED).accept(MediaType.APPLICATION_JSON);

    return accessTokenService.post(grant, ClientAccessToken.class);
}
 
示例3
private ClientAccessToken getAccessToken() throws NoPrivateKeyException {
    JwsHeaders headers = new JwsHeaders(JoseType.JWT, SignatureAlgorithm.RS256);
    JwtClaims claims = new JwtClaims();
    claims.setIssuer(config.getServiceAccountEmail());
    claims.setAudience(config.getServiceAccountTokenUri());
    claims.setSubject(config.getServiceAccountSubject());

    long issuedAt = OAuthUtils.getIssuedAt();
    long tokenTimeout = config.getServiceAccountTokenLifetime();
    claims.setIssuedAt(issuedAt);
    claims.setExpiryTime(issuedAt + tokenTimeout);
    String scopes = String.join(" ", config.getServiceAccountScopes());
    claims.setProperty("scope", scopes);

    JwtToken token = new JwtToken(headers, claims);
    JwsJwtCompactProducer p = new JwsJwtCompactProducer(token);
    String base64UrlAssertion = p.signWith(config.readServiceAccountKey());

    JwtBearerGrant grant = new JwtBearerGrant(base64UrlAssertion);

    WebClient accessTokenService = WebClient.create(config.getServiceAccountTokenUri(),
            Arrays.asList(new OAuthJSONProvider(), new AccessTokenGrantWriter()));

    accessTokenService.type(MediaType.APPLICATION_FORM_URLENCODED).accept(MediaType.APPLICATION_JSON);

    return accessTokenService.post(grant, ClientAccessToken.class);
}
 
示例4
private Set<Class<?>> doGetClasses() {
    final Set<Class<?>> classes = new HashSet<>(singletonList(OAuthJSONProvider.class));
    if (builder.getExtension(OAuth2Options.class).isAuthorizationCodeSupport()) {
        classes.add(OAuth2AuthorizationCodeGrantService.class);
    }
    if (builder.getExtension(OAuth2Options.class).isTokenSupport()) {
        classes.addAll(asList(OAuth2TokenService.class, OAuth2RevokeTokenService.class));
    }
    return classes;
}
 
示例5
@Test
public void getRefreshTokenNoClient() {
    final Client client = ClientBuilder.newClient().register(new OAuthJSONProvider());
    try {
        // password
        final ClientAccessToken primary = client.target("http://localhost:" + MEECROWAVE.getConfiguration().getHttpPort())
                .path("oauth2/token")
                .request(APPLICATION_JSON_TYPE)
                .post(entity(
                        new Form()
                                .param("grant_type", "password")
                                .param("username", "test")
                                .param("password", "pwd"), APPLICATION_FORM_URLENCODED_TYPE), ClientAccessToken.class);

        // refresh
        final ClientAccessToken token = client.target("http://localhost:" + MEECROWAVE.getConfiguration().getHttpPort())
                .path("oauth2/token")
                .request(APPLICATION_JSON_TYPE)
                .post(entity(
                        new Form()
                                .param("grant_type", "refresh_token")
                                .param("refresh_token", primary.getRefreshToken()), APPLICATION_FORM_URLENCODED_TYPE), ClientAccessToken.class);
        assertNotNull(token);
        assertEquals("Bearer", token.getTokenType());
        assertIsJwt(token.getTokenKey(), "__default");
        assertEquals(3600, token.getExpiresIn());
        assertNotEquals(0, token.getIssuedAt());
        assertNotNull(token.getRefreshToken());
    } finally {
        client.close();
    }
}
 
示例6
public static List<Object> setupProviders() {
    JSONProvider<OAuthAuthorizationData> jsonP = new JSONProvider<>();
    jsonP.setNamespaceMap(Collections.singletonMap("http://org.apache.cxf.rs.security.oauth",
                                                   "ns2"));

    return Arrays.asList(jsonP, new OAuthJSONProvider(), new JsonWebKeysProvider(), new JsonMapObjectProvider());
}
 
示例7
/**
 * Obtains the access token from OAuth AccessToken Service
 * @param accessTokenServiceUri the AccessToken endpoint address
 * @param consumer {@link Consumer} representing the registered client
 * @param grant {@link AccessTokenGrant} grant
 * @param setAuthorizationHeader if set to true then HTTP Basic scheme
 *           will be used to pass client id and secret, otherwise they will
 *           be passed in the form payload
 * @return {@link ClientAccessToken} access token
 * @throws OAuthServiceException
 */
public static ClientAccessToken getAccessToken(String accessTokenServiceUri,
                                               Consumer consumer,
                                               AccessTokenGrant grant,
                                               boolean setAuthorizationHeader)
    throws OAuthServiceException {
    OAuthJSONProvider provider = new OAuthJSONProvider();
    WebClient accessTokenService =
        WebClient.create(accessTokenServiceUri, Collections.singletonList(provider));
    accessTokenService.accept("application/json");
    return getAccessToken(accessTokenService, consumer, grant, setAuthorizationHeader);
}
 
示例8
private ClientAccessToken getAccessTokenUsingCode(String tokenEndpoint, String code, String clientId,
                                                  String clientSecret, String redirectURI) {
    // Here we need to get the AccessToken using the authorization code
    List<Object> providers = new ArrayList<>();
    providers.add(new OAuthJSONProvider());

    WebClient client =
        WebClient.create(tokenEndpoint, providers, "cxf-tls.xml");

    ClientConfiguration config = WebClient.getConfig(client);

    if (LOG.isDebugEnabled()) {
        config.getOutInterceptors().add(new LoggingOutInterceptor());
        config.getInInterceptors().add(new LoggingInInterceptor());
    }

    client.type("application/x-www-form-urlencoded");
    client.accept("application/json");

    Form form = new Form();
    form.param("grant_type", "authorization_code");
    form.param("code", code);
    form.param("client_id", clientId);
    form.param("redirect_uri", redirectURI);
    form.param("client_secret", clientSecret);
    Response response = client.post(form);

    return response.readEntity(ClientAccessToken.class);
}
 
示例9
@Test
public void authorizationCode() throws URISyntaxException {
    final int httpPort = MEECROWAVE.getConfiguration().getHttpPort();

    createRedirectedClient(httpPort);

    final Client client = ClientBuilder.newClient()
            .property(Message.MAINTAIN_SESSION, true)
            .register(new OAuthJSONProvider());
    try {
        final WebTarget target = client.target("http://localhost:" + httpPort);

        final Response authorization = target
                .path("oauth2/authorize")
                .queryParam(OAuthConstants.GRANT_TYPE, OAuthConstants.AUTHORIZATION_CODE_GRANT)
                .queryParam(OAuthConstants.RESPONSE_TYPE, OAuthConstants.CODE_RESPONSE_TYPE)
                .queryParam(OAuthConstants.CLIENT_ID, "c1")
                .queryParam(OAuthConstants.CLIENT_SECRET, "cpwd")
                .queryParam(OAuthConstants.REDIRECT_URI, "http://localhost:" + httpPort + "/redirected")
                .request(APPLICATION_JSON_TYPE)
                .header("authorization", "Basic " + Base64.getEncoder().encodeToString("test:pwd".getBytes(StandardCharsets.UTF_8)))
                .get();
        final OAuthAuthorizationData data = authorization.readEntity(OAuthAuthorizationData.class);
        assertNotNull(data.getAuthenticityToken());
        assertEquals("c1", data.getClientId());
        assertEquals("http://localhost:" + httpPort + "/oauth2/authorize/decision", data.getReplyTo());
        assertEquals("code", data.getResponseType());
        assertEquals("http://localhost:" + httpPort + "/redirected", data.getRedirectUri());

        final Response decision = target
                .path("oauth2/authorize/decision")
                .queryParam(OAuthConstants.SESSION_AUTHENTICITY_TOKEN, data.getAuthenticityToken())
                .queryParam(OAuthConstants.AUTHORIZATION_DECISION_KEY, "allow")
                .request(APPLICATION_JSON_TYPE)
                .cookie(authorization.getCookies().get("JSESSIONID"))
                .header("authorization", "Basic " + Base64.getEncoder().encodeToString("test:pwd".getBytes(StandardCharsets.UTF_8)))
                .get();
        assertEquals(Response.Status.SEE_OTHER.getStatusCode(), decision.getStatus());
        assertTrue(decision.getLocation().toASCIIString(), decision.getLocation().toASCIIString().startsWith("http://localhost:" + httpPort + "/redirected?code="));

        final ClientAccessToken token = target
                .path("oauth2/token")
                .request(APPLICATION_JSON_TYPE)
                .post(entity(
                        new Form()
                                .param(OAuthConstants.GRANT_TYPE, OAuthConstants.AUTHORIZATION_CODE_GRANT)
                                .param(OAuthConstants.CODE_RESPONSE_TYPE, decision.getLocation().getRawQuery().substring("code=".length()))
                                .param(OAuthConstants.REDIRECT_URI, "http://localhost:" + httpPort + "/redirected")
                                .param(OAuthConstants.CLIENT_ID, "c1")
                                .param(OAuthConstants.CLIENT_SECRET, "cpwd"), APPLICATION_FORM_URLENCODED_TYPE), ClientAccessToken.class);
        assertNotNull(token);
        assertEquals("Bearer", token.getTokenType());
        assertIsJwt(token.getTokenKey(), "c1");
        assertEquals(3600, token.getExpiresIn());
        assertNotEquals(0, token.getIssuedAt());
        assertNotNull(token.getRefreshToken());
    } finally {
        client.close();
    }
}
 
示例10
WebClient createAccessTokenServiceClient() {
    return WebClient.create(accessTokenServiceUri, Collections.singletonList(new OAuthJSONProvider()));
}
 
示例11
/**
 * Obtains the access token from OAuth AccessToken Service
 * using the initialized web client
 * @param accessTokenService the AccessToken client
 * @param consumer {@link Consumer} representing the registered client.
 * @param grant {@link AccessTokenGrant} grant
 * @param extraParams extra parameters
 * @param defaultTokenType default expected token type - some early
 *        well-known OAuth2 services do not return a required token_type parameter
 * @param setAuthorizationHeader if set to true then HTTP Basic scheme
 *           will be used to pass client id and secret, otherwise they will
 *           be passed in the form payload
 * @return {@link ClientAccessToken} access token
 * @throws OAuthServiceException
 */
public static ClientAccessToken getAccessToken(WebClient accessTokenService,
                                               Consumer consumer,
                                               AccessTokenGrant grant,
                                               Map<String, String> extraParams,
                                               String defaultTokenType,
                                               boolean setAuthorizationHeader)
    throws OAuthServiceException {

    if (accessTokenService == null) {
        throw new OAuthServiceException(OAuthConstants.SERVER_ERROR);
    }

    Form form = new Form(grant.toMap());
    if (extraParams != null) {
        for (Map.Entry<String, String> entry : extraParams.entrySet()) {
            form.param(entry.getKey(), entry.getValue());
        }
    }
    if (consumer != null) {
        boolean secretAvailable = !StringUtils.isEmpty(consumer.getClientSecret());
        if (setAuthorizationHeader && secretAvailable) {
            accessTokenService.replaceHeader(HttpHeaders.AUTHORIZATION,
                DefaultBasicAuthSupplier.getBasicAuthHeader(consumer.getClientId(), consumer.getClientSecret()));
        } else {
            form.param(OAuthConstants.CLIENT_ID, consumer.getClientId());
            if (secretAvailable) {
                form.param(OAuthConstants.CLIENT_SECRET, consumer.getClientSecret());
            }
        }
    } else {
        // in this case the AccessToken service is expected to find a mapping between
        // the authenticated credentials and the client registration id
    }
    Response response = accessTokenService.form(form);
    final Map<String, String> map;
    try {
        map = response.getMediaType() == null
                || response.getMediaType().isCompatible(MediaType.APPLICATION_JSON_TYPE)
                        ? new OAuthJSONProvider().readJSONResponse((InputStream) response.getEntity())
                        : Collections.emptyMap();
    } catch (Exception ex) {
        throw new ResponseProcessingException(response, ex);
    }
    if (200 == response.getStatus()) {
        ClientAccessToken token = fromMapToClientToken(map, defaultTokenType);
        if (token == null) {
            throw new OAuthServiceException(OAuthConstants.SERVER_ERROR);
        }
        return token;
    } else if (response.getStatus() >= 400 && map.containsKey(OAuthConstants.ERROR_KEY)) {
        OAuthError error = new OAuthError(map.get(OAuthConstants.ERROR_KEY),
                                          map.get(OAuthConstants.ERROR_DESCRIPTION_KEY));
        error.setErrorUri(map.get(OAuthConstants.ERROR_URI_KEY));
        throw new OAuthServiceException(error);
    }
    throw new OAuthServiceException(OAuthConstants.SERVER_ERROR);
}