Search in sources :

Example 1 with AccessTokenService

use of org.apache.cxf.rs.security.oauth2.services.AccessTokenService 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.ext.logging.LoggingInInterceptor) WebClient(org.apache.cxf.jaxrs.client.WebClient)

Example 2 with AccessTokenService

use of org.apache.cxf.rs.security.oauth2.services.AccessTokenService in project cxf by apache.

the class OAuthClientUtilsTest method getAccessTokenInternalServerError.

@Test
public void getAccessTokenInternalServerError() {
    WebClient accessTokenService = mock(WebClient.class);
    expect(accessTokenService.form(anyObject(Form.class))).andReturn(Response.serverError().type(MediaType.TEXT_PLAIN).entity(new ByteArrayInputStream("Unrecoverable error in the server.".getBytes())).build());
    replay(accessTokenService);
    try {
        OAuthClientUtils.getAccessToken(accessTokenService, null, new RefreshTokenGrant(""), null, null, false);
        fail();
    } catch (OAuthServiceException e) {
        assertEquals(OAuthConstants.SERVER_ERROR, e.getMessage());
    } finally {
        verify(accessTokenService);
    }
}
Also used : Form(javax.ws.rs.core.Form) ByteArrayInputStream(java.io.ByteArrayInputStream) OAuthServiceException(org.apache.cxf.rs.security.oauth2.provider.OAuthServiceException) RefreshTokenGrant(org.apache.cxf.rs.security.oauth2.grants.refresh.RefreshTokenGrant) WebClient(org.apache.cxf.jaxrs.client.WebClient) Test(org.junit.Test)

Example 3 with AccessTokenService

use of org.apache.cxf.rs.security.oauth2.services.AccessTokenService 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) {
            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);
}
Also used : OAuthServiceException(org.apache.cxf.rs.security.oauth2.provider.OAuthServiceException) Form(javax.ws.rs.core.Form) ClientAccessToken(org.apache.cxf.rs.security.oauth2.common.ClientAccessToken) OAuthJSONProvider(org.apache.cxf.rs.security.oauth2.provider.OAuthJSONProvider) OAuthServiceException(org.apache.cxf.rs.security.oauth2.provider.OAuthServiceException) 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)

Example 4 with AccessTokenService

use of org.apache.cxf.rs.security.oauth2.services.AccessTokenService in project tesb-rt-se by Talend.

the class OAuthManagerApplication method getSingletons.

@Override
public Set<Object> getSingletons() {
    Set<Object> classes = new HashSet<Object>();
    ThirdPartyRegistrationService thirdPartyService = new ThirdPartyRegistrationService();
    thirdPartyService.setDataProvider(manager);
    AccessTokenService ats = new AccessTokenService();
    ats.setDataProvider(manager);
    classes.add(thirdPartyService);
    classes.add(ats);
    return classes;
}
Also used : ThirdPartyRegistrationService(oauth2.manager.ThirdPartyRegistrationService) AccessTokenService(org.apache.cxf.rs.security.oauth2.services.AccessTokenService) HashSet(java.util.HashSet)

Example 5 with AccessTokenService

use of org.apache.cxf.rs.security.oauth2.services.AccessTokenService in project styx by petafuel.

the class STYX09 method generateINGAccessToken.

public void generateINGAccessToken(String url) {
    AccessTokenService service = new AccessTokenService();
    AccessTokenRequest request = new AccessTokenRequest();
    try {
        AccessToken retrievedAccessToken = service.tokenRequest(url + "/oauth2/token", request);
        // give a tolerance of 30 seconds to the expiry date in case of any software
        // related delays
        this.accessTokenValidUntil = Instant.now().plusSeconds((retrievedAccessToken.getExpiresIn() - 30));
        this.accessToken = retrievedAccessToken;
    } catch (BankRequestFailedException e) {
        LOG.error("Error getting ing access token:", e);
        ResponseEntity responseEntity = new ResponseEntity("Generating ING access token failed", ResponseConstant.INTERNAL_SERVER_ERROR, ResponseCategory.ERROR, ResponseOrigin.STYX);
        throw new StyxException(responseEntity);
    }
}
Also used : ResponseEntity(net.petafuel.styx.api.exception.ResponseEntity) AccessTokenService(net.petafuel.styx.core.xs2a.standards.ing.v1_0.services.AccessTokenService) AccessToken(net.petafuel.styx.core.xs2a.standards.ing.v1_0.entities.AccessToken) AccessTokenRequest(net.petafuel.styx.core.xs2a.standards.ing.v1_0.http.AccessTokenRequest) BankRequestFailedException(net.petafuel.styx.core.xs2a.exceptions.BankRequestFailedException) StyxException(net.petafuel.styx.api.exception.StyxException)

Aggregations

WebClient (org.apache.cxf.jaxrs.client.WebClient)5 Form (javax.ws.rs.core.Form)3 ClientAccessToken (org.apache.cxf.rs.security.oauth2.common.ClientAccessToken)3 OAuthJSONProvider (org.apache.cxf.rs.security.oauth2.provider.OAuthJSONProvider)3 ByteArrayInputStream (java.io.ByteArrayInputStream)2 RefreshTokenGrant (org.apache.cxf.rs.security.oauth2.grants.refresh.RefreshTokenGrant)2 OAuthServiceException (org.apache.cxf.rs.security.oauth2.provider.OAuthServiceException)2 Test (org.junit.Test)2 HashSet (java.util.HashSet)1 Map (java.util.Map)1 ProcessingException (javax.ws.rs.ProcessingException)1 ResponseProcessingException (javax.ws.rs.client.ResponseProcessingException)1 Response (javax.ws.rs.core.Response)1 ResponseEntity (net.petafuel.styx.api.exception.ResponseEntity)1 StyxException (net.petafuel.styx.api.exception.StyxException)1 BankRequestFailedException (net.petafuel.styx.core.xs2a.exceptions.BankRequestFailedException)1 AccessToken (net.petafuel.styx.core.xs2a.standards.ing.v1_0.entities.AccessToken)1 AccessTokenRequest (net.petafuel.styx.core.xs2a.standards.ing.v1_0.http.AccessTokenRequest)1 AccessTokenService (net.petafuel.styx.core.xs2a.standards.ing.v1_0.services.AccessTokenService)1 ThirdPartyRegistrationService (oauth2.manager.ThirdPartyRegistrationService)1