Search in sources :

Example 26 with OAuthSystemException

use of org.apache.amber.oauth2.common.exception.OAuthSystemException in project intermine by intermine.

the class Authenticator method execute.

/**
 * Method called for login in
 *
 * @param mapping The ActionMapping used to select this instance
 * @param form The optional ActionForm bean for this request (if any)
 * @param request The HTTP request we are processing
 * @param response The HTTP response we are creating
 * @return an ActionForward object defining where control goes next
 * @exception Exception if the application business logic throws an exception
 */
@Override
public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
    OAuthClientRequest authRequest;
    OAuthProviderType provider;
    Properties webProperties = InterMineContext.getWebProperties();
    // Suitable values are: GOOGLE, GITHUB, FACEBOOK, etc.
    String providerName = request.getParameter("provider");
    String redirectUri = getRedirectUri(webProperties, providerName);
    String realm = webProperties.getProperty("webapp.baseurl");
    String state = UUID.randomUUID().toString();
    request.getSession().setAttribute("oauth2.state", state);
    String authorisationUrl = webProperties.getProperty("oauth2." + providerName + ".url.auth");
    if (authorisationUrl == null) {
        try {
            provider = OAuthProviderType.valueOf(providerName);
            authorisationUrl = provider.getAuthzEndpoint();
        } catch (IllegalArgumentException e) {
            ActionErrors errors = new ActionErrors();
            errors.add(ActionErrors.GLOBAL_MESSAGE, new ActionMessage("oauth2.error.unknown-provider"));
            saveErrors(request, errors);
            return mapping.findForward("login");
        }
    }
    try {
        authRequest = OAuthClientRequest.authorizationLocation(authorisationUrl).setClientId(webProperties.getProperty("oauth2." + providerName + ".client-id")).setRedirectURI(redirectUri).setScope(webProperties.getProperty("oauth2." + providerName + ".scopes")).setState(state).setParameter("response_type", "code").setParameter("openid.realm", // link open-id 2.0 accounts [1]
        realm).buildQueryMessage();
        String goHere = authRequest.getLocationUri();
        // various providers require the response_type parameter.
        LOG.info("[OAuth2]: Redirecting to " + goHere);
        response.sendRedirect(goHere);
        return null;
    } catch (OAuthSystemException e) {
        ActionErrors errors = new ActionErrors();
        errors.add(ActionErrors.GLOBAL_MESSAGE, new ActionMessage("oauth2.error.system-exception", e));
        saveErrors(request, errors);
        return mapping.findForward("login");
    }
// [1]: see https://developers.google.com/identity/protocols/OpenID2Migration
}
Also used : OAuthProviderType(org.apache.oltu.oauth2.common.OAuthProviderType) OAuthSystemException(org.apache.oltu.oauth2.common.exception.OAuthSystemException) ActionMessage(org.apache.struts.action.ActionMessage) OAuthClientRequest(org.apache.oltu.oauth2.client.request.OAuthClientRequest) Properties(java.util.Properties) ActionErrors(org.apache.struts.action.ActionErrors)

Example 27 with OAuthSystemException

use of org.apache.amber.oauth2.common.exception.OAuthSystemException in project intermine by intermine.

the class CallbackService method getSaneProviderUserInfo.

/**
 * Get user info for services which are sane enough to have an identity resource
 * that serves json
 * with <code>id</code>, <code>email</code> and <code>name</code> keys.
 * @param provider Who to ask.
 * @param accessToken An access token.
 * @return The delegated identity.
 * @throws OAuthSystemException
 * @throws OAuthProblemException
 * @throws JSONException If things aren't so sane after all.
 */
private DelegatedIdentity getSaneProviderUserInfo(String provider, String accessToken) throws OAuthSystemException, OAuthProblemException, JSONException {
    Properties props = InterMineContext.getWebProperties();
    String prefix = "oauth2." + provider;
    String identityEndpoint = props.getProperty(prefix + ".identity-resource");
    String envelopeKey = props.getProperty(prefix + ".identity-envelope");
    String idKey = props.getProperty(prefix + ".id-key", "id");
    String nameKey = props.getProperty(prefix + ".name-key", "name");
    String emailKey = props.getProperty(prefix + ".email-key", "email");
    String authMechanism = props.getProperty(prefix + ".resource-auth-mechanism", "queryparam");
    OAuthBearerClientRequest requestBuilder = new OAuthBearerClientRequest(identityEndpoint).setAccessToken(accessToken);
    OAuthClientRequest bearerClientRequest;
    if ("queryparam".equals(authMechanism)) {
        bearerClientRequest = requestBuilder.buildQueryMessage();
    } else if ("header".equals(authMechanism)) {
        bearerClientRequest = requestBuilder.buildHeaderMessage();
    } else if ("body".equals(authMechanism)) {
        bearerClientRequest = requestBuilder.buildBodyMessage();
    } else {
        throw new OAuthSystemException("Unknown authorisation mechanism: " + authMechanism);
    }
    LOG.debug("Requesting identity information:" + " URI = " + bearerClientRequest.getLocationUri() + " HEADERS = " + bearerClientRequest.getHeaders() + " BODY = " + bearerClientRequest.getBody());
    bearerClientRequest.setHeader("Accept", "application/json");
    OAuthClient oauthClient = new OAuthClient(new URLConnectionClient());
    OAuthResourceResponse resp = oauthClient.resource(bearerClientRequest, OAuth.HttpMethod.GET, OAuthResourceResponse.class);
    return parseIdentity(provider, envelopeKey, idKey, nameKey, emailKey, resp.getBody());
}
Also used : OAuthBearerClientRequest(org.apache.oltu.oauth2.client.request.OAuthBearerClientRequest) URLConnectionClient(org.apache.oltu.oauth2.client.URLConnectionClient) OAuthResourceResponse(org.apache.oltu.oauth2.client.response.OAuthResourceResponse) OAuthClient(org.apache.oltu.oauth2.client.OAuthClient) OAuthSystemException(org.apache.oltu.oauth2.common.exception.OAuthSystemException) Properties(java.util.Properties) OAuthClientRequest(org.apache.oltu.oauth2.client.request.OAuthClientRequest)

Example 28 with OAuthSystemException

use of org.apache.amber.oauth2.common.exception.OAuthSystemException in project mbed-cloud-sdk-java by ARMmbed.

the class OAuthOkHttpClient method execute.

@SuppressWarnings("resource")
@Override
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(), null, 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 29 with OAuthSystemException

use of org.apache.amber.oauth2.common.exception.OAuthSystemException in project java-demos by powerLeePlus.

the class AuthAccessController method getCode.

/**
 * 这里省略了一步,父工程README.md的详细步骤图的第一步
 */
/**
 * 一、请求授权 (Authorization Request)(对应父工程README.md的流程图)
 * 向服务端获取code
 * 1、拼接url然后访问,获取code
 * 2、服务端检查成功,然后会回调到 另一个接口 /oauth-client/callbackCode
 */
@RequestMapping("/getCode")
public String getCode() throws OAuthProblemException {
    String requestUrl = null;
    try {
        // 配置请求参数,构建oauthd的请求。设置请求服务地址(authorizeUrl)、clientId、response_type、redirectUrl
        OAuthClientRequest accessTokenRequest = OAuthClientRequest.authorizationLocation(server_authorizeUrl).setResponseType(response_type).setClientId(client_clientId).setRedirectURI(client_redirectUrl_getAccessToken).buildQueryMessage();
        requestUrl = accessTokenRequest.getLocationUri();
    } catch (OAuthSystemException e) {
        e.printStackTrace();
    }
    System.out.println("==> 向服务端发起获取code的请求: " + requestUrl);
    // 这是向服务端发起获取code的请求,这是客户端的一次重定向。
    return "redirect:" + requestUrl;
}
Also used : OAuthSystemException(org.apache.oltu.oauth2.common.exception.OAuthSystemException) OAuthClientRequest(org.apache.oltu.oauth2.client.request.OAuthClientRequest) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Example 30 with OAuthSystemException

use of org.apache.amber.oauth2.common.exception.OAuthSystemException in project java-demos by powerLeePlus.

the class AuthAccessController method getAccessToken.

/**
 * 三、授权许可(Authorization Grant)(对应父工程README.md的流程图)
 * 接受服务端返回的code,提交申请access token的请求
 * 3.服务端回调,传回code值
 * 4.根据code值,调用服务端服务,根据code获取access_token
 * 5.拿到access_token重定向到客户端的服务  /oauth-client/getUserInfo
 * 6.在该服务中 再调用服务端获取用户信息
 */
@RequestMapping("/callbackCode")
public Object getAccessToken(HttpServletRequest request) throws OAuthProblemException {
    String code = request.getParameter("code");
    System.out.println("==> 服务端回调,获取的code:" + code);
    OAuthClient oAuthClient = new OAuthClient(new URLConnectionClient());
    try {
        OAuthClientRequest accessTokenRequest = OAuthClientRequest.tokenLocation(server_accessTokenUrl).setGrantType(GrantType.AUTHORIZATION_CODE).setClientId(client_clientId).setClientSecret(client_clientSecret).setCode(code).setRedirectURI(client_redirectUrl_getUserInfo).buildQueryMessage();
        System.out.println("==> 向服务端发起获取accessToken的请求:" + accessTokenRequest.getLocationUri());
        // 去服务端请求access token,并返回响应
        OAuthAccessTokenResponse oAuthResponse = oAuthClient.accessToken(accessTokenRequest, OAuth.HttpMethod.POST);
        // 获取服务端返回过来的access token
        String accessToken = oAuthResponse.getAccessToken();
        // 查看access token是否过期
        Long expiresIn = oAuthResponse.getExpiresIn();
        System.out.println("==> 客户端根据 code值 " + code + " 到服务端获取的access_token为:" + accessToken + " 过期时间为:" + expiresIn);
        System.out.println("==> 拿到access_token然后重定向到 客户端 [ " + client_redirectUrl_getUserInfo + " ]服务,传过去accessToken");
        // 客户端拿到token自动重定向到获取资源的URL。也可以交由server端自动重定向,取决于服务端如何实现的(是否会自动重定向)
        return "redirect:" + client_redirectUrl_getUserInfo + "?accessToken=" + accessToken;
    } catch (OAuthSystemException e) {
        e.printStackTrace();
    }
    return null;
}
Also used : URLConnectionClient(org.apache.oltu.oauth2.client.URLConnectionClient) OAuthClient(org.apache.oltu.oauth2.client.OAuthClient) OAuthAccessTokenResponse(org.apache.oltu.oauth2.client.response.OAuthAccessTokenResponse) OAuthSystemException(org.apache.oltu.oauth2.common.exception.OAuthSystemException) OAuthClientRequest(org.apache.oltu.oauth2.client.request.OAuthClientRequest) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Aggregations

OAuthSystemException (org.apache.oltu.oauth2.common.exception.OAuthSystemException)100 OAuthClientRequest (org.apache.oltu.oauth2.client.request.OAuthClientRequest)47 IOException (java.io.IOException)37 OAuthProblemException (org.apache.oltu.oauth2.common.exception.OAuthProblemException)36 Request (okhttp3.Request)27 Response (okhttp3.Response)27 OAuthJSONAccessTokenResponse (org.apache.oltu.oauth2.client.response.OAuthJSONAccessTokenResponse)20 Builder (okhttp3.Request.Builder)17 OAuthBearerClientRequest (org.apache.oltu.oauth2.client.request.OAuthBearerClientRequest)17 Map (java.util.Map)15 OAuthResponse (org.apache.oltu.oauth2.common.message.OAuthResponse)15 OAuthClientResponse (org.apache.oltu.oauth2.client.response.OAuthClientResponse)14 MediaType (okhttp3.MediaType)13 RequestBody (okhttp3.RequestBody)13 TokenRequestBuilder (org.apache.oltu.oauth2.client.request.OAuthClientRequest.TokenRequestBuilder)12 AuthenticationRequestBuilder (org.apache.oltu.oauth2.client.request.OAuthClientRequest.AuthenticationRequestBuilder)11 Path (javax.ws.rs.Path)10 OAuthClient (org.apache.oltu.oauth2.client.OAuthClient)9 IdentityOAuth2Exception (org.wso2.carbon.identity.oauth2.IdentityOAuth2Exception)9 HashMap (java.util.HashMap)8