Search in sources :

Example 26 with OAuthClientRequest

use of org.apache.amber.oauth2.client.request.OAuthClientRequest in project mbed-cloud-sdk-java by ARMmbed.

the class OAuth method retryingIntercept.

private Response retryingIntercept(Chain chain, boolean updateTokenAndRetryOnAuthorizationFailure) throws IOException {
    Request request = chain.request();
    // If the request already have an authorization (eg. Basic auth), do nothing
    if (request.header("Authorization") != null) {
        return chain.proceed(request);
    }
    // If first time, get the token
    OAuthClientRequest oAuthRequest;
    if (getAccessToken() == null) {
        updateAccessToken(null);
    }
    if (getAccessToken() != null) {
        // Build the request
        Builder rb = request.newBuilder();
        String requestAccessToken = new String(getAccessToken());
        try {
            oAuthRequest = new OAuthBearerClientRequest(request.url().toString()).setAccessToken(requestAccessToken).buildHeaderMessage();
        } catch (OAuthSystemException e) {
            throw new IOException(e);
        }
        for (Map.Entry<String, String> header : oAuthRequest.getHeaders().entrySet()) {
            rb.addHeader(header.getKey(), header.getValue());
        }
        rb.url(oAuthRequest.getLocationUri());
        // Execute the request
        Response response = chain.proceed(rb.build());
        // 401/403 most likely indicates that access token has expired. Unless it happens two times in a row.
        if (response != null && (response.code() == HTTP_UNAUTHORIZED || response.code() == HTTP_FORBIDDEN) && updateTokenAndRetryOnAuthorizationFailure) {
            if (updateAccessToken(requestAccessToken)) {
                return retryingIntercept(chain, false);
            }
        }
        return response;
    } else {
        return chain.proceed(chain.request());
    }
}
Also used : OAuthBearerClientRequest(org.apache.oltu.oauth2.client.request.OAuthBearerClientRequest) OAuthJSONAccessTokenResponse(org.apache.oltu.oauth2.client.response.OAuthJSONAccessTokenResponse) Response(okhttp3.Response) OAuthSystemException(org.apache.oltu.oauth2.common.exception.OAuthSystemException) AuthenticationRequestBuilder(org.apache.oltu.oauth2.client.request.OAuthClientRequest.AuthenticationRequestBuilder) Builder(okhttp3.Request.Builder) TokenRequestBuilder(org.apache.oltu.oauth2.client.request.OAuthClientRequest.TokenRequestBuilder) Request(okhttp3.Request) OAuthClientRequest(org.apache.oltu.oauth2.client.request.OAuthClientRequest) OAuthBearerClientRequest(org.apache.oltu.oauth2.client.request.OAuthBearerClientRequest) IOException(java.io.IOException) OAuthClientRequest(org.apache.oltu.oauth2.client.request.OAuthClientRequest) Map(java.util.Map)

Example 27 with OAuthClientRequest

use of org.apache.amber.oauth2.client.request.OAuthClientRequest in project mbed-cloud-sdk-java by ARMmbed.

the class OAuthOkHttpClient method execute.

public <T extends OAuthClientResponse> T execute(OAuthClientRequest request, Map<String, String> headers, String requestMethod, Class<T> responseClass) throws OAuthSystemException, OAuthProblemException {
    MediaType mediaType = MediaType.parse("application/json");
    Request.Builder requestBuilder = new Request.Builder().url(request.getLocationUri());
    if (headers != null) {
        for (Entry<String, String> entry : headers.entrySet()) {
            if (entry.getKey().equalsIgnoreCase("Content-Type")) {
                mediaType = MediaType.parse(entry.getValue());
            } else {
                requestBuilder.addHeader(entry.getKey(), entry.getValue());
            }
        }
    }
    RequestBody body = request.getBody() != null ? RequestBody.create(mediaType, request.getBody()) : null;
    requestBuilder.method(requestMethod, body);
    try {
        Response response = client.newCall(requestBuilder.build()).execute();
        return OAuthClientResponseFactory.createCustomResponse(response.body().string(), response.body().contentType().toString(), response.code(), responseClass);
    } catch (IOException e) {
        throw new OAuthSystemException(e);
    }
}
Also used : Builder(okhttp3.Request.Builder) OAuthClientResponse(org.apache.oltu.oauth2.client.response.OAuthClientResponse) Response(okhttp3.Response) OAuthSystemException(org.apache.oltu.oauth2.common.exception.OAuthSystemException) Request(okhttp3.Request) OAuthClientRequest(org.apache.oltu.oauth2.client.request.OAuthClientRequest) MediaType(okhttp3.MediaType) IOException(java.io.IOException) RequestBody(okhttp3.RequestBody)

Example 28 with OAuthClientRequest

use of org.apache.amber.oauth2.client.request.OAuthClientRequest in project mbed-cloud-sdk-java by ARMmbed.

the class OAuthOkHttpClient method execute.

public <T extends OAuthClientResponse> T execute(OAuthClientRequest request, Map<String, String> headers, String requestMethod, Class<T> responseClass) throws OAuthSystemException, OAuthProblemException {
    MediaType mediaType = MediaType.parse("application/json");
    Request.Builder requestBuilder = new Request.Builder().url(request.getLocationUri());
    if (headers != null) {
        for (Entry<String, String> entry : headers.entrySet()) {
            if (entry.getKey().equalsIgnoreCase("Content-Type")) {
                mediaType = MediaType.parse(entry.getValue());
            } else {
                requestBuilder.addHeader(entry.getKey(), entry.getValue());
            }
        }
    }
    RequestBody body = request.getBody() != null ? RequestBody.create(mediaType, request.getBody()) : null;
    requestBuilder.method(requestMethod, body);
    try {
        Response response = client.newCall(requestBuilder.build()).execute();
        return OAuthClientResponseFactory.createCustomResponse(response.body().string(), response.body().contentType().toString(), response.code(), responseClass);
    } catch (IOException e) {
        throw new OAuthSystemException(e);
    }
}
Also used : Builder(okhttp3.Request.Builder) OAuthClientResponse(org.apache.oltu.oauth2.client.response.OAuthClientResponse) Response(okhttp3.Response) OAuthSystemException(org.apache.oltu.oauth2.common.exception.OAuthSystemException) Request(okhttp3.Request) OAuthClientRequest(org.apache.oltu.oauth2.client.request.OAuthClientRequest) MediaType(okhttp3.MediaType) IOException(java.io.IOException) RequestBody(okhttp3.RequestBody)

Example 29 with OAuthClientRequest

use of org.apache.amber.oauth2.client.request.OAuthClientRequest in project identity-test-integration by wso2-incubator.

the class LoginProxy method getAuthzCode.

/**
 * this is the first API, the SPA should call to initiate user authentication. this method will redirect the user to
 * the identity server's OAuth 2.0 authorization endpoint.the value of the code parameter will be written to a
 * cookie, so it can be accessed when get redirected back from the identity server, after user authentication.
 *
 * @param spaName paName is a unique identifier for each SPA, and the proxy application should be aware of that
 *            identifier.the proxy end-point uses the spaName later to load the callback URL corresponding to the
 *            SPA.
 * @param code each times the SPA gets rendered on the browser it has to generate the code.spas should not uses
 *            statically configured code values.
 * @return
 */
@Path("login")
@GET
public Response getAuthzCode(@QueryParam("spaName") String spaName, @QueryParam("code") String code) {
    if (spaName == null || spaName.isEmpty()) {
        return ProxyUtils.handleResponse(ProxyUtils.OperationStatus.BAD_REQUEST, ProxyFaultCodes.ERROR_002, ProxyFaultCodes.Name.INVALID_INPUTS, "The value of the spaName cannot be null.");
    }
    if (code == null || code.isEmpty()) {
        return ProxyUtils.handleResponse(ProxyUtils.OperationStatus.BAD_REQUEST, ProxyFaultCodes.ERROR_002, ProxyFaultCodes.Name.INVALID_INPUTS, "The value of the code cannot be null.");
    }
    HttpServletResponse resp = context.getHttpServletResponse();
    // loads the client key corresponding to the SPA. you do not need to have SPA specific consumer keys, rather can
    // use one client key for all the SPAs. you get the consumer key from the identity server, at the time you
    // register the service provider, and configure it in oauth_proxy.properties file.
    String consumerKey = ProxyUtils.getConsumerKey(spaName);
    // this is the OpenID 2.0 authorization end-point of the identity server.
    String authzEndpoint = ProxyUtils.getAuthzEp();
    // get the grant type. the proxy works only with the authorization code grant type.
    String authzGrantType = ProxyUtils.getAuthzGrantType();
    // get the scope associated with the SPA. each SPA can define its own scopes in the oauth_proxy.properties file,
    // but in each case OPENID is used as a mandatory scope value.
    String scope = ProxyUtils.getScope(spaName);
    // load the callback URL of the proxy. there is only one callback URL. even when you create multiple service
    // providers in identity server to get multiple client key/client secret pairs, the callback URL would be the
    // same.
    String callbackUrl = ProxyUtils.getCallbackUrl();
    OAuthClientRequest authzRequest = null;
    try {
        // create a cookie under the proxy domain having code as the key and spaName as the value.
        Cookie cookie = new Cookie(code, spaName);
        // this cookie is only accessible by HTTPS transport.
        cookie.setSecure(true);
        // add cookie to the response.
        resp.addCookie(cookie);
        // create the OAuth 2.0 request with all necessary parameters. the code passed by the SPA is set as the
        // state - so the identity server will return it back with the OAuth response. we use the value of the code
        // (or the state here) to retrieve the cookie later. this is done in a way to make this proxy application
        // state-less.
        authzRequest = OAuthClientRequest.authorizationLocation(authzEndpoint).setClientId(consumerKey).setRedirectURI(callbackUrl).setResponseType(authzGrantType).setScope(scope).setState(code).buildQueryMessage();
    } catch (OAuthSystemException e) {
        log.error(e);
        return ProxyUtils.handleResponse(ProxyUtils.OperationStatus.INTERNAL_SERVER_ERROR, ProxyFaultCodes.ERROR_003, ProxyFaultCodes.Name.INTERNAL_SERVER_ERROR, e.getMessage());
    }
    try {
        // redirects the user to the identity server's authorization end-point.
        resp.sendRedirect(authzRequest.getLocationUri());
        return null;
    } catch (IOException e) {
        log.error(e);
        return ProxyUtils.handleResponse(ProxyUtils.OperationStatus.INTERNAL_SERVER_ERROR, ProxyFaultCodes.ERROR_003, ProxyFaultCodes.Name.INTERNAL_SERVER_ERROR, e.getMessage());
    }
}
Also used : Cookie(javax.servlet.http.Cookie) OAuthSystemException(org.apache.amber.oauth2.common.exception.OAuthSystemException) HttpServletResponse(javax.servlet.http.HttpServletResponse) IOException(java.io.IOException) OAuthClientRequest(org.apache.amber.oauth2.client.request.OAuthClientRequest) Path(javax.ws.rs.Path) GET(javax.ws.rs.GET)

Example 30 with OAuthClientRequest

use of org.apache.amber.oauth2.client.request.OAuthClientRequest in project BIMserver by opensourceBIM.

the class SendUrl method main.

public static void main(String[] args) {
    try {
        OAuthClientRequest request = OAuthClientRegistrationRequest.location("https://thisisanexperimentalserver.com/oauth/register/", OAuthRegistration.Type.PUSH).setName("Zapier").setUrl("https://zapier.com/dashboard/auth/oauth/return/App56192API").setDescription("App Description").setRedirectURL("https://zapier.com/dashboard/auth/oauth/return/App56192API").buildJSONMessage();
        OAuthRegistrationClient oauthclient = new OAuthRegistrationClient(new org.bimserver.webservices.impl.URLConnectionClient());
        OAuthClientRegistrationResponse response = oauthclient.clientInfo(request);
        System.out.println(response.getClientId());
        System.out.println(response.getClientSecret());
    } catch (OAuthSystemException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (OAuthProblemException e) {
        e.printStackTrace();
    }
}
Also used : OAuthProblemException(org.apache.oltu.oauth2.common.exception.OAuthProblemException) OAuthRegistrationClient(org.apache.oltu.oauth2.ext.dynamicreg.client.OAuthRegistrationClient) OAuthClientRegistrationResponse(org.apache.oltu.oauth2.ext.dynamicreg.client.response.OAuthClientRegistrationResponse) OAuthSystemException(org.apache.oltu.oauth2.common.exception.OAuthSystemException) IOException(java.io.IOException) OAuthClientRequest(org.apache.oltu.oauth2.client.request.OAuthClientRequest)

Aggregations

OAuthClientRequest (org.apache.oltu.oauth2.client.request.OAuthClientRequest)36 OAuthSystemException (org.apache.oltu.oauth2.common.exception.OAuthSystemException)24 IOException (java.io.IOException)21 Request (okhttp3.Request)18 Response (okhttp3.Response)18 Builder (okhttp3.Request.Builder)17 OAuthJSONAccessTokenResponse (org.apache.oltu.oauth2.client.response.OAuthJSONAccessTokenResponse)13 OAuthBearerClientRequest (org.apache.oltu.oauth2.client.request.OAuthBearerClientRequest)11 AuthenticationRequestBuilder (org.apache.oltu.oauth2.client.request.OAuthClientRequest.AuthenticationRequestBuilder)10 TokenRequestBuilder (org.apache.oltu.oauth2.client.request.OAuthClientRequest.TokenRequestBuilder)10 Map (java.util.Map)9 MediaType (okhttp3.MediaType)9 RequestBody (okhttp3.RequestBody)9 OAuthClientResponse (org.apache.oltu.oauth2.client.response.OAuthClientResponse)9 URI (java.net.URI)6 URLConnectionClient (org.apache.oltu.oauth2.client.URLConnectionClient)6 OAuthClient (org.apache.oltu.oauth2.client.OAuthClient)5 OAuthProblemException (org.apache.oltu.oauth2.common.exception.OAuthProblemException)5 OAuthRegistrationClient (org.apache.oltu.oauth2.ext.dynamicreg.client.OAuthRegistrationClient)3 OAuthClientRegistrationResponse (org.apache.oltu.oauth2.ext.dynamicreg.client.response.OAuthClientRegistrationResponse)3