Search in sources :

Example 6 with OAuthClientResponse

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

the class LoginProxy method handleCallback.

/**
 * this is the method, which gets fired when the identity server returns back the authorization code, after
 * authenticating the user. in addition to the authorization code, the response from the identity server must also
 * include the state parameter, which contains the value we set when we initiate the authorization grant.
 *
 * @param code the authorization code generated by the identity server. the proxy application will exchange this
 *            token to get an access token from the identity server.
 * @param state this is the same value we set as state, when we initiate the authorization grant request to the
 *            identity server.
 * @return
 */
@Path("callback")
@GET
public Response handleCallback(@QueryParam("code") String code, @QueryParam("state") String state) {
    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.");
    }
    if (state == null || state.isEmpty()) {
        return ProxyUtils.handleResponse(ProxyUtils.OperationStatus.BAD_REQUEST, ProxyFaultCodes.ERROR_002, ProxyFaultCodes.Name.INVALID_INPUTS, "The value of the state cannot be null.");
    }
    HttpServletResponse resp = context.getHttpServletResponse();
    HttpServletRequest req = context.getHttpServletRequest();
    Cookie[] cookies = req.getCookies();
    String spaName = null;
    // try to load the cookie corresponding to the value of the state.
    if (cookies != null && cookies.length > 0) {
        for (int i = 0; i < cookies.length; i++) {
            if (cookies[i].getName().equals(state)) {
                spaName = cookies[i].getValue();
                break;
            }
        }
    }
    if (spaName == null) {
        return ProxyUtils.handleResponse(ProxyUtils.OperationStatus.BAD_REQUEST, ProxyFaultCodes.ERROR_002, ProxyFaultCodes.Name.INVALID_INPUTS, "No valid cookie found.");
    }
    // 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);
    // loads the client secret corresponding to the SPA. you do not need to have SPA specific client secret, rather
    // can use one client secret for all the SPAs. you get the client secret from the identity server, at the time
    // you register the service provider, and configure it in oauth_proxy.properties file.
    String consumerSecret = ProxyUtils.getConsumerSecret(spaName);
    // this is the OAuth 2.0 token end-point of the identity server.
    String tokenEndpoint = ProxyUtils.getTokenEp();
    // 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 accessRequest = null;
    try {
        // create an OAuth 2.0 token request.
        accessRequest = OAuthClientRequest.tokenLocation(tokenEndpoint).setGrantType(GrantType.AUTHORIZATION_CODE).setClientId(consumerKey).setClientSecret(consumerSecret).setRedirectURI(callbackUrl).setCode(code).buildBodyMessage();
    } catch (OAuthSystemException e) {
        log.error(e);
        return ProxyUtils.handleResponse(ProxyUtils.OperationStatus.INTERNAL_SERVER_ERROR, ProxyFaultCodes.ERROR_003, ProxyFaultCodes.Name.INTERNAL_SERVER_ERROR, e.getMessage());
    }
    // create an OAuth 2.0 client that uses custom HTTP client under the hood
    OAuthClient oAuthClient = new OAuthClient(new URLConnectionClient());
    OAuthClientResponse oAuthResponse = null;
    try {
        // talk to the OAuth token end-point of identity server to get the OAuth access token, refresh token and id
        // token.
        oAuthResponse = oAuthClient.accessToken(accessRequest);
    } catch (OAuthSystemException e) {
        log.error(e);
        return ProxyUtils.handleResponse(ProxyUtils.OperationStatus.INTERNAL_SERVER_ERROR, ProxyFaultCodes.ERROR_003, ProxyFaultCodes.Name.INTERNAL_SERVER_ERROR, e.getMessage());
    } catch (OAuthProblemException e) {
        log.error(e);
        return ProxyUtils.handleResponse(ProxyUtils.OperationStatus.INTERNAL_SERVER_ERROR, ProxyFaultCodes.ERROR_003, ProxyFaultCodes.Name.INTERNAL_SERVER_ERROR, e.getMessage());
    }
    // read the access token from the OAuth token end-point response.
    String accessToken = oAuthResponse.getParam(ProxyUtils.ACCESS_TOKEN);
    // read the refresh token from the OAuth token end-point response.
    String refreshToken = oAuthResponse.getParam(ProxyUtils.REFRESH_TOKEN);
    // read the expiration from the OAuth token endpoint response.
    long expiration = Long.parseLong(oAuthResponse.getParam(ProxyUtils.EXPIRATION));
    // read the id token from the OAuth token end-point response.
    String idToken = oAuthResponse.getParam(ProxyUtils.ID_TOKEN);
    if (idToken != null) {
        // extract out the content of the JWT, which comes in the id token.
        String[] idTkElements = idToken.split(Pattern.quote("."));
        idToken = idTkElements[1];
    }
    // create a JSON object aggregating OAuth access token, refresh token and id token
    JSONObject json = new JSONObject();
    try {
        json.put(ProxyUtils.ID_TOKEN, idToken);
        json.put(ProxyUtils.ACCESS_TOKEN, accessToken);
        json.put(ProxyUtils.REFRESH_TOKEN, refreshToken);
        json.put(ProxyUtils.SPA_NAME, spaName);
        json.put(ProxyUtils.EXPIRATION, new Long(expiration));
    } catch (JSONException e) {
        return ProxyUtils.handleResponse(ProxyUtils.OperationStatus.INTERNAL_SERVER_ERROR, ProxyFaultCodes.ERROR_003, ProxyFaultCodes.Name.INTERNAL_SERVER_ERROR, e.getMessage());
    }
    try {
        // encrypt the JSON message.
        String encryptedCookieValue = ProxyUtils.encrypt(json.toString());
        // create a cookie under the proxy domain with the encrypted message. cookie name is set to the value of the
        // code, initially passed by the SPA.
        Cookie cookie = new Cookie(state, encryptedCookieValue);
        // the cookie is only accessible by the HTTPS transport.
        cookie.setSecure(true);
        // add cookie to the response.
        resp.addCookie(cookie);
        // get the SPA callback URL. each SPA has its own callback URL, which is defined in the
        // oauth_proxy.properties file
        resp.sendRedirect(ProxyUtils.getSpaCallbackUrl(spaName));
        return null;
    } catch (Exception 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) OAuthClient(org.apache.amber.oauth2.client.OAuthClient) OAuthSystemException(org.apache.amber.oauth2.common.exception.OAuthSystemException) HttpServletResponse(javax.servlet.http.HttpServletResponse) JSONException(org.codehaus.jettison.json.JSONException) OAuthClientResponse(org.apache.amber.oauth2.client.response.OAuthClientResponse) OAuthSystemException(org.apache.amber.oauth2.common.exception.OAuthSystemException) OAuthProblemException(org.apache.amber.oauth2.common.exception.OAuthProblemException) IOException(java.io.IOException) JSONException(org.codehaus.jettison.json.JSONException) HttpServletRequest(javax.servlet.http.HttpServletRequest) OAuthProblemException(org.apache.amber.oauth2.common.exception.OAuthProblemException) URLConnectionClient(org.apache.amber.oauth2.client.URLConnectionClient) JSONObject(org.codehaus.jettison.json.JSONObject) OAuthClientRequest(org.apache.amber.oauth2.client.request.OAuthClientRequest) Path(javax.ws.rs.Path) GET(javax.ws.rs.GET)

Example 7 with OAuthClientResponse

use of org.apache.amber.oauth2.client.response.OAuthClientResponse in project android-client by GenesisVision.

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(), response.headers().toMultimap(), responseClass);
    } catch (IOException e) {
        throw new OAuthSystemException(e);
    }
}
Also used : 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 8 with OAuthClientResponse

use of org.apache.amber.oauth2.client.response.OAuthClientResponse 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 9 with OAuthClientResponse

use of org.apache.amber.oauth2.client.response.OAuthClientResponse 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 10 with OAuthClientResponse

use of org.apache.amber.oauth2.client.response.OAuthClientResponse 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)

Aggregations

IOException (java.io.IOException)10 MediaType (okhttp3.MediaType)9 Request (okhttp3.Request)9 RequestBody (okhttp3.RequestBody)9 Response (okhttp3.Response)9 OAuthClientRequest (org.apache.oltu.oauth2.client.request.OAuthClientRequest)9 OAuthClientResponse (org.apache.oltu.oauth2.client.response.OAuthClientResponse)9 OAuthSystemException (org.apache.oltu.oauth2.common.exception.OAuthSystemException)9 Builder (okhttp3.Request.Builder)8 Cookie (javax.servlet.http.Cookie)1 HttpServletRequest (javax.servlet.http.HttpServletRequest)1 HttpServletResponse (javax.servlet.http.HttpServletResponse)1 GET (javax.ws.rs.GET)1 Path (javax.ws.rs.Path)1 OAuthClient (org.apache.amber.oauth2.client.OAuthClient)1 URLConnectionClient (org.apache.amber.oauth2.client.URLConnectionClient)1 OAuthClientRequest (org.apache.amber.oauth2.client.request.OAuthClientRequest)1 OAuthClientResponse (org.apache.amber.oauth2.client.response.OAuthClientResponse)1 OAuthProblemException (org.apache.amber.oauth2.common.exception.OAuthProblemException)1 OAuthSystemException (org.apache.amber.oauth2.common.exception.OAuthSystemException)1