Search in sources :

Example 1 with OAuthJSONProvider

use of org.apache.cxf.rs.security.oauth2.provider.OAuthJSONProvider in project cxf by apache.

the class OAuthClientUtils method getAccessToken.

/**
 * 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) {
            StringBuilder sb = new StringBuilder();
            sb.append("Basic ");
            try {
                String data = consumer.getClientId() + ":" + consumer.getClientSecret();
                sb.append(Base64Utility.encode(data.getBytes(StandardCharsets.UTF_8)));
            } catch (Exception ex) {
                throw new ProcessingException(ex);
            }
            accessTokenService.replaceHeader("Authorization", sb.toString());
        } 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);
    Map<String, String> map = null;
    try {
        map = new OAuthJSONProvider().readJSONResponse((InputStream) response.getEntity());
    } catch (IOException 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);
}
Also used : OAuthServiceException(org.apache.cxf.rs.security.oauth2.provider.OAuthServiceException) Form(javax.ws.rs.core.Form) InputStream(java.io.InputStream) ClientAccessToken(org.apache.cxf.rs.security.oauth2.common.ClientAccessToken) OAuthJSONProvider(org.apache.cxf.rs.security.oauth2.provider.OAuthJSONProvider) IOException(java.io.IOException) OAuthServiceException(org.apache.cxf.rs.security.oauth2.provider.OAuthServiceException) IOException(java.io.IOException) ProcessingException(javax.ws.rs.ProcessingException) ResponseProcessingException(javax.ws.rs.client.ResponseProcessingException) Response(javax.ws.rs.core.Response) OAuthError(org.apache.cxf.rs.security.oauth2.common.OAuthError) ResponseProcessingException(javax.ws.rs.client.ResponseProcessingException) Map(java.util.Map) ProcessingException(javax.ws.rs.ProcessingException) ResponseProcessingException(javax.ws.rs.client.ResponseProcessingException)

Example 2 with OAuthJSONProvider

use of org.apache.cxf.rs.security.oauth2.provider.OAuthJSONProvider in project cxf by apache.

the class OAuthJSONProviderTest method testReadTokenIntrospectionMultipleAuds.

@Test
@SuppressWarnings({ "unchecked", "rawtypes" })
public void testReadTokenIntrospectionMultipleAuds() throws Exception {
    String response = "{\"active\":true,\"client_id\":\"WjcK94pnec7CyA\",\"username\":\"alice\",\"token_type\":\"Bearer\"" + ",\"scope\":\"a\",\"aud\":[\"https://localhost:8082/service\",\"https://localhost:8083/service\"]," + "\"iat\":1453472181,\"exp\":1453475781}";
    OAuthJSONProvider provider = new OAuthJSONProvider();
    TokenIntrospection t = (TokenIntrospection) provider.readFrom((Class) TokenIntrospection.class, TokenIntrospection.class, new Annotation[] {}, MediaType.APPLICATION_JSON_TYPE, new MetadataMap<String, String>(), new ByteArrayInputStream(response.getBytes()));
    assertTrue(t.isActive());
    assertEquals("WjcK94pnec7CyA", t.getClientId());
    assertEquals("alice", t.getUsername());
    assertEquals("a", t.getScope());
    assertEquals(2, t.getAud().size());
    assertEquals("https://localhost:8082/service", t.getAud().get(0));
    assertEquals("https://localhost:8083/service", t.getAud().get(1));
    assertEquals(1453472181L, t.getIat().longValue());
    assertEquals(1453475781L, t.getExp().longValue());
}
Also used : TokenIntrospection(org.apache.cxf.rs.security.oauth2.common.TokenIntrospection) MetadataMap(org.apache.cxf.jaxrs.impl.MetadataMap) ByteArrayInputStream(java.io.ByteArrayInputStream) Annotation(java.lang.annotation.Annotation) Test(org.junit.Test)

Example 3 with OAuthJSONProvider

use of org.apache.cxf.rs.security.oauth2.provider.OAuthJSONProvider in project cxf by apache.

the class OAuthJSONProviderTest method testWriteBearerClientAccessToken.

@Test
public void testWriteBearerClientAccessToken() throws Exception {
    ClientAccessToken token = new ClientAccessToken(OAuthConstants.BEARER_TOKEN_TYPE, "1234");
    token.setExpiresIn(12345);
    token.setRefreshToken("5678");
    token.setApprovedScope("read");
    token.setParameters(Collections.singletonMap("my_parameter", "http://abc"));
    OAuthJSONProvider provider = new OAuthJSONProvider();
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    provider.writeTo(token, ClientAccessToken.class, ClientAccessToken.class, new Annotation[] {}, MediaType.APPLICATION_JSON_TYPE, new MetadataMap<String, Object>(), bos);
    doReadClientAccessToken(bos.toString(), OAuthConstants.BEARER_TOKEN_TYPE, token.getParameters());
}
Also used : ClientAccessToken(org.apache.cxf.rs.security.oauth2.common.ClientAccessToken) ByteArrayOutputStream(java.io.ByteArrayOutputStream) Test(org.junit.Test)

Example 4 with OAuthJSONProvider

use of org.apache.cxf.rs.security.oauth2.provider.OAuthJSONProvider in project cxf by apache.

the class BigQueryServer method getAccessToken.

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);
}
Also used : JwtToken(org.apache.cxf.rs.security.jose.jwt.JwtToken) JwsHeaders(org.apache.cxf.rs.security.jose.jws.JwsHeaders) JwsJwtCompactProducer(org.apache.cxf.rs.security.jose.jws.JwsJwtCompactProducer) JwtClaims(org.apache.cxf.rs.security.jose.jwt.JwtClaims) JwtBearerGrant(org.apache.cxf.rs.security.oauth2.grants.jwt.JwtBearerGrant) AccessTokenGrantWriter(org.apache.cxf.rs.security.oauth2.client.AccessTokenGrantWriter) OAuthJSONProvider(org.apache.cxf.rs.security.oauth2.provider.OAuthJSONProvider) LoggingInInterceptor(org.apache.cxf.interceptor.LoggingInInterceptor) WebClient(org.apache.cxf.jaxrs.client.WebClient)

Example 5 with OAuthJSONProvider

use of org.apache.cxf.rs.security.oauth2.provider.OAuthJSONProvider in project cxf by apache.

the class OAuth2TestUtils method setupProviders.

public static List<Object> setupProviders() {
    List<Object> providers = new ArrayList<>();
    JSONProvider<OAuthAuthorizationData> jsonP = new JSONProvider<OAuthAuthorizationData>();
    jsonP.setNamespaceMap(Collections.singletonMap("http://org.apache.cxf.rs.security.oauth", "ns2"));
    providers.add(jsonP);
    providers.add(new OAuthJSONProvider());
    providers.add(new JsonWebKeysProvider());
    providers.add(new JsonMapObjectProvider());
    return providers;
}
Also used : JsonWebKeysProvider(org.apache.cxf.rs.security.jose.jaxrs.JsonWebKeysProvider) ArrayList(java.util.ArrayList) JSONProvider(org.apache.cxf.jaxrs.provider.json.JSONProvider) OAuthJSONProvider(org.apache.cxf.rs.security.oauth2.provider.OAuthJSONProvider) OAuthJSONProvider(org.apache.cxf.rs.security.oauth2.provider.OAuthJSONProvider) JsonMapObjectProvider(org.apache.cxf.jaxrs.provider.json.JsonMapObjectProvider) OAuthAuthorizationData(org.apache.cxf.rs.security.oauth2.common.OAuthAuthorizationData)

Aggregations

OAuthJSONProvider (org.apache.cxf.rs.security.oauth2.provider.OAuthJSONProvider)21 OAuthAuthorizationData (org.apache.cxf.rs.security.oauth2.common.OAuthAuthorizationData)16 ArrayList (java.util.ArrayList)15 JSONProvider (org.apache.cxf.jaxrs.provider.json.JSONProvider)15 Test (org.junit.Test)8 JsonMapObjectProvider (org.apache.cxf.jaxrs.provider.json.JsonMapObjectProvider)7 JsonWebKeysProvider (org.apache.cxf.rs.security.jose.jaxrs.JsonWebKeysProvider)7 ClientAccessToken (org.apache.cxf.rs.security.oauth2.common.ClientAccessToken)7 ByteArrayInputStream (java.io.ByteArrayInputStream)4 Annotation (java.lang.annotation.Annotation)4 Form (javax.ws.rs.core.Form)4 MetadataMap (org.apache.cxf.jaxrs.impl.MetadataMap)4 Client (javax.ws.rs.client.Client)3 TokenIntrospection (org.apache.cxf.rs.security.oauth2.common.TokenIntrospection)3 ByteArrayOutputStream (java.io.ByteArrayOutputStream)2 Response (javax.ws.rs.core.Response)2 WebClient (org.apache.cxf.jaxrs.client.WebClient)2 IOException (java.io.IOException)1 InputStream (java.io.InputStream)1 LinkedHashMap (java.util.LinkedHashMap)1