Search in sources :

Example 96 with OAuthSystemException

use of org.apache.oltu.oauth2.common.exception.OAuthSystemException in project irida by phac-nml.

the class OltuAuthorizationController method getToken.

/**
 * Receive the OAuth2 authorization code and request an OAuth2 token
 *
 * @param request
 *            The incoming request
 * @param response
 *            The response to redirect
 * @param apiId
 *            the Long ID of the API we're requesting from
 * @param redirect
 *            The URL location to redirect to after completion
 * @return A ModelAndView redirecting back to the resource that was
 *         requested
 * @throws IOException
 * @throws OAuthSystemException
 * @throws OAuthProblemException
 * @throws URISyntaxException
 */
@RequestMapping("/token")
public ModelAndView getToken(HttpServletRequest request, HttpServletResponse response, @RequestParam("redirect") String redirect) throws IOException, OAuthSystemException, OAuthProblemException, URISyntaxException {
    // Get the OAuth2 auth code
    OAuthAuthzResponse oar = OAuthAuthzResponse.oauthCodeAuthzResponse(request);
    String code = oar.getCode();
    logger.debug("got code " + code);
    // Read the RemoteAPI from the RemoteAPIService and get the base URI
    // Build the token location for this service
    URI serviceTokenLocation = UriBuilder.fromUri(serviceURI).path("oauth").path("token").build();
    logger.debug("token loc " + serviceTokenLocation);
    // Build the redirect URI to request a token from
    String tokenRedirect = buildRedirectURI(redirect);
    // Create the token request form the given auth code
    OAuthClientRequest tokenRequest = OAuthClientRequest.tokenLocation(serviceTokenLocation.toString()).setClientId(clientId).setClientSecret(clientSecret).setRedirectURI(tokenRedirect).setCode(code).setGrantType(GrantType.AUTHORIZATION_CODE).buildBodyMessage();
    // execute the request
    OAuthClient client = new OAuthClient(new URLConnectionClient());
    // read the response for the access token
    OAuthJSONAccessTokenResponse accessTokenResponse = client.accessToken(tokenRequest, OAuthJSONAccessTokenResponse.class);
    String accessToken = accessTokenResponse.getAccessToken();
    // check the token expiry
    Long expiresIn = accessTokenResponse.getExpiresIn();
    logger.debug("Token expires in " + expiresIn);
    // adding the token to the response page. This is just a demo to show
    // how to get an oauth token. NEVER DO THIS!!!
    redirect = redirect + "?token=" + accessToken;
    // redirect the response back to the requested resource
    return new ModelAndView(new RedirectView(redirect));
}
Also used : URLConnectionClient(org.apache.oltu.oauth2.client.URLConnectionClient) OAuthClient(org.apache.oltu.oauth2.client.OAuthClient) ModelAndView(org.springframework.web.servlet.ModelAndView) RedirectView(org.springframework.web.servlet.view.RedirectView) OAuthJSONAccessTokenResponse(org.apache.oltu.oauth2.client.response.OAuthJSONAccessTokenResponse) OAuthClientRequest(org.apache.oltu.oauth2.client.request.OAuthClientRequest) OAuthAuthzResponse(org.apache.oltu.oauth2.client.response.OAuthAuthzResponse) URI(java.net.URI) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Example 97 with OAuthSystemException

use of org.apache.oltu.oauth2.common.exception.OAuthSystemException in project irida by phac-nml.

the class OltuAuthorizationController method getTokenFromAuthCode.

/**
 * Receive the OAuth2 authorization code and request an OAuth2 token
 *
 * @param request
 *            The incoming request
 * @param response
 *            The response to redirect
 * @param apiId
 *            the Long ID of the API we're requesting from
 * @param redirect
 *            The URL location to redirect to after completion
 * @return A ModelAndView redirecting back to the resource that was
 *         requested
 * @throws OAuthSystemException
 *             if we can't get an access token for the current request.
 * @throws OAuthProblemException
 *             if we can't get a response from the authorization server
 */
@RequestMapping(TOKEN_ENDPOINT)
public String getTokenFromAuthCode(HttpServletRequest request, HttpServletResponse response, @RequestParam("apiId") Long apiId, @RequestParam("redirect") String redirect) throws OAuthSystemException, OAuthProblemException {
    // Get the OAuth2 auth code
    OAuthAuthzResponse oar = OAuthAuthzResponse.oauthCodeAuthzResponse(request);
    String code = oar.getCode();
    logger.trace("Received auth code: " + code);
    // Build the redirect URI to request a token from
    String tokenRedirect = buildRedirectURI(apiId, redirect);
    // Read the RemoteAPI from the RemoteAPIService and get the base URI
    RemoteAPI remoteAPI = remoteAPIService.read(apiId);
    tokenService.createTokenFromAuthCode(code, remoteAPI, tokenRedirect);
    // redirect the response back to the requested resource
    return "redirect:" + redirect;
}
Also used : RemoteAPI(ca.corefacility.bioinformatics.irida.model.RemoteAPI) OAuthAuthzResponse(org.apache.oltu.oauth2.client.response.OAuthAuthzResponse) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Example 98 with OAuthSystemException

use of org.apache.oltu.oauth2.common.exception.OAuthSystemException in project irida by phac-nml.

the class OltuAuthorizationController method authenticate.

/**
 * Begin authentication procedure by redirecting to remote authorization
 * location
 *
 * @param remoteAPI
 *            The API we need to authenticate with
 * @param redirect
 *            The location to redirect back to after authentication is
 *            complete
 * @return A ModelAndView beginning the authentication procedure
 * @throws OAuthSystemException
 *             if we can't read from the authorization server.
 */
public String authenticate(RemoteAPI remoteAPI, String redirect) throws OAuthSystemException {
    // get the URI for the remote service we'll be requesting from
    String serviceURI = remoteAPI.getServiceURI();
    // build the authorization path
    URI serviceAuthLocation = UriBuilder.fromUri(serviceURI).path("oauth").path("authorize").build();
    logger.debug("Authenticating for service: " + remoteAPI);
    logger.debug("Redirect after authentication: " + redirect);
    // build a redirect URI to redirect to after auth flow is completed
    String tokenRedirect = buildRedirectURI(remoteAPI.getId(), redirect);
    // build the redirect query to request an authorization code from the
    // remote API
    OAuthClientRequest request = OAuthClientRequest.authorizationLocation(serviceAuthLocation.toString()).setClientId(remoteAPI.getClientId()).setRedirectURI(tokenRedirect).setResponseType(ResponseType.CODE.toString()).setScope("read").buildQueryMessage();
    String locURI = request.getLocationUri();
    logger.trace("Authorization request location: " + locURI);
    return "redirect:" + locURI;
}
Also used : OAuthClientRequest(org.apache.oltu.oauth2.client.request.OAuthClientRequest) URI(java.net.URI)

Example 99 with OAuthSystemException

use of org.apache.oltu.oauth2.common.exception.OAuthSystemException 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 100 with OAuthSystemException

use of org.apache.oltu.oauth2.common.exception.OAuthSystemException 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)

Aggregations

OAuthSystemException (org.apache.oltu.oauth2.common.exception.OAuthSystemException)103 OAuthClientRequest (org.apache.oltu.oauth2.client.request.OAuthClientRequest)57 OAuthProblemException (org.apache.oltu.oauth2.common.exception.OAuthProblemException)51 OAuthResponse (org.apache.oltu.oauth2.common.message.OAuthResponse)49 IOException (java.io.IOException)41 Request (okhttp3.Request)29 Response (okhttp3.Response)29 OAuthJSONAccessTokenResponse (org.apache.oltu.oauth2.client.response.OAuthJSONAccessTokenResponse)23 Builder (okhttp3.Request.Builder)19 OAuthBearerClientRequest (org.apache.oltu.oauth2.client.request.OAuthBearerClientRequest)18 URI (java.net.URI)17 Map (java.util.Map)16 TokenRequestBuilder (org.apache.oltu.oauth2.client.request.OAuthClientRequest.TokenRequestBuilder)15 OAuthClientResponse (org.apache.oltu.oauth2.client.response.OAuthClientResponse)15 MediaType (okhttp3.MediaType)14 RequestBody (okhttp3.RequestBody)14 OAuthClient (org.apache.oltu.oauth2.client.OAuthClient)13 MD5Generator (org.apache.oltu.oauth2.as.issuer.MD5Generator)12 AuthenticationRequestBuilder (org.apache.oltu.oauth2.client.request.OAuthClientRequest.AuthenticationRequestBuilder)12 RequestMapping (org.springframework.web.bind.annotation.RequestMapping)12