Search in sources :

Example 16 with OAuthClientRequest

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

the class StructrOAuthClient method getEndUserAuthorizationRequestUri.

/**
 * Create an end-user authorization request
 *
 * Use with {@literal response.setRedirect(request.getLocationUri());}
 *
 * @param request
 * @return request URI
 */
public String getEndUserAuthorizationRequestUri(final HttpServletRequest request) {
    OAuthClientRequest oauthClientRequest;
    try {
        oauthClientRequest = OAuthClientRequest.authorizationLocation(authorizationLocation).setClientId(clientId).setRedirectURI(getAbsoluteUrl(request, redirectUri)).setScope(getScope()).setResponseType(getResponseType()).setState(getState()).buildQueryMessage();
        logger.info("Authorization request location URI: {}", oauthClientRequest.getLocationUri());
        return oauthClientRequest.getLocationUri();
    } catch (OAuthSystemException ex) {
        logger.error("", ex);
    }
    return null;
}
Also used : OAuthSystemException(org.apache.oltu.oauth2.common.exception.OAuthSystemException) OAuthClientRequest(org.apache.oltu.oauth2.client.request.OAuthClientRequest)

Example 17 with OAuthClientRequest

use of org.apache.amber.oauth2.client.request.OAuthClientRequest in project dq-easy-cloud by dq-open-cloud.

the class EcBaseOauthToken method doGetOauthAccessToken.

/**
 * <p>
 * 执行获取授权accessToken
 * </p>
 * <pre>
 *     子类可以通过重写该方法实现自己的获取授权accessToken的数据
 * </pre>
 *
 * @param
 * @return java.util.Map<java.lang.String,java.lang.Object>
 * @author daiqi
 * @date 2018/7/18 11:54
 */
public Map<String, Object> doGetOauthAccessToken() throws Exception {
    // 获取token请求构建者
    EcBaseTokenRequestBuilder tokenRequestBuilder = getTokenRequestBuilder();
    // 构建客户端请求数据
    OAuthClientRequest accessTokenRequest = tokenRequestBuilder.buildClientRequest(getTokenRequestParam());
    // 返回accessToken响应对象
    EcBaseOauthTokenResponse response = oAuthClient.accessToken(accessTokenRequest, OAuth.HttpMethod.POST, tokenRequestBuilder.getTokenResponseClass());
    // 将accessToken放入map中
    return response.getParameters();
}
Also used : EcBaseOauthTokenResponse(com.easy.cloud.core.oauth.client.base.response.resource.EcBaseOauthTokenResponse) OAuthClientRequest(org.apache.oltu.oauth2.client.request.OAuthClientRequest) EcBaseTokenRequestBuilder(com.easy.cloud.core.oauth.client.base.request.builder.EcBaseTokenRequestBuilder)

Example 18 with OAuthClientRequest

use of org.apache.amber.oauth2.client.request.OAuthClientRequest 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 19 with OAuthClientRequest

use of org.apache.amber.oauth2.client.request.OAuthClientRequest 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 20 with OAuthClientRequest

use of org.apache.amber.oauth2.client.request.OAuthClientRequest in project incubator-gobblin by apache.

the class SalesforceRestWriter method onConnect.

/**
 * Retrieve access token, if needed, retrieve instance url, and set server host URL
 * {@inheritDoc}
 * @see org.apache.gobblin.writer.http.HttpWriter#onConnect(org.apache.http.HttpHost)
 */
@Override
public void onConnect(URI serverHost) throws IOException {
    if (!StringUtils.isEmpty(accessToken)) {
        // No need to be called if accessToken is active.
        return;
    }
    try {
        getLog().info("Getting Oauth2 access token.");
        OAuthClientRequest request = OAuthClientRequest.tokenLocation(serverHost.toString()).setGrantType(GrantType.PASSWORD).setClientId(clientId).setClientSecret(clientSecret).setUsername(userId).setPassword(password + securityToken).buildQueryMessage();
        OAuthClient client = new OAuthClient(new URLConnectionClient());
        OAuthJSONAccessTokenResponse response = client.accessToken(request, OAuth.HttpMethod.POST);
        accessToken = response.getAccessToken();
        setCurServerHost(new URI(response.getParam("instance_url")));
    } catch (OAuthProblemException e) {
        throw new NonTransientException("Error while authenticating with Oauth2", e);
    } catch (OAuthSystemException e) {
        throw new RuntimeException("Failed getting access token", e);
    } catch (URISyntaxException e) {
        throw new RuntimeException("Failed due to invalid instance url", e);
    }
}
Also used : OAuthProblemException(org.apache.oltu.oauth2.common.exception.OAuthProblemException) NonTransientException(org.apache.gobblin.exception.NonTransientException) URLConnectionClient(org.apache.oltu.oauth2.client.URLConnectionClient) OAuthClient(org.apache.oltu.oauth2.client.OAuthClient) OAuthSystemException(org.apache.oltu.oauth2.common.exception.OAuthSystemException) OAuthJSONAccessTokenResponse(org.apache.oltu.oauth2.client.response.OAuthJSONAccessTokenResponse) URISyntaxException(java.net.URISyntaxException) OAuthClientRequest(org.apache.oltu.oauth2.client.request.OAuthClientRequest) URI(java.net.URI)

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