Search in sources :

Example 41 with OAuthSystemException

use of org.apache.oltu.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)

Example 42 with OAuthSystemException

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

the class AccessTokenController method token.

@RequestMapping("/accessToken")
public HttpEntity token(HttpServletRequest request) throws OAuthSystemException {
    try {
        // 构建Oauth请求
        OAuthTokenRequest oAuthTokenRequest = new OAuthTokenRequest(request);
        // 检查提交的客户端id是否正确
        if (!authorizationService.checkClientId(oAuthTokenRequest.getClientId())) {
            OAuthResponse response = OAuthASResponse.errorResponse(HttpServletResponse.SC_BAD_REQUEST).setError(OAuthError.TokenResponse.INVALID_CLIENT).setErrorDescription("客户端验证失败,client_id错误!").buildJSONMessage();
            return new ResponseEntity(response.getBody(), HttpStatus.valueOf(response.getResponseStatus()));
        }
        // 检查客户端安全Key是否正确
        if (!authorizationService.checkClientSecret(oAuthTokenRequest.getClientSecret())) {
            OAuthResponse response = OAuthASResponse.errorResponse(HttpServletResponse.SC_UNAUTHORIZED).setError(OAuthError.TokenResponse.UNAUTHORIZED_CLIENT).setErrorDescription("客户端验证失败,client_secret错误!").buildJSONMessage();
            return new ResponseEntity(response.getBody(), HttpStatus.valueOf(response.getResponseStatus()));
        }
        String authCode = oAuthTokenRequest.getParam(OAuth.OAUTH_CODE);
        // 检查验证类型,此处只检查AUTHORIZATION类型,其他的还有PASSWORD或者REFRESH_TOKEN
        if (oAuthTokenRequest.getParam(OAuth.OAUTH_GRANT_TYPE).equals(GrantType.AUTHORIZATION_CODE.toString())) {
            if (!authorizationService.checkAuthCode(authCode)) {
                OAuthResponse response = OAuthASResponse.errorResponse(HttpServletResponse.SC_BAD_REQUEST).setError(OAuthError.TokenResponse.INVALID_GRANT).setErrorDescription("auth_code错误!").buildJSONMessage();
                return new ResponseEntity(response.getBody(), HttpStatus.valueOf(response.getResponseStatus()));
            }
        }
        // 生成Access Token
        OAuthIssuer issuer = new OAuthIssuerImpl(new MD5Generator());
        final String accessToken = issuer.accessToken();
        authorizationService.addAccessToken(accessToken, authorizationService.getUsernameByAuthCode(authCode));
        // 生成OAuth响应
        OAuthResponse response = OAuthASResponse.tokenResponse(HttpServletResponse.SC_OK).setAccessToken(accessToken).setExpiresIn(String.valueOf(authorizationService.getExpireIn())).buildJSONMessage();
        return new ResponseEntity(response.getBody(), HttpStatus.valueOf(response.getResponseStatus()));
    } catch (OAuthProblemException e) {
        OAuthResponse res = OAuthASResponse.errorResponse(HttpServletResponse.SC_BAD_REQUEST).error(e).buildBodyMessage();
        return new ResponseEntity(res.getBody(), HttpStatus.valueOf(res.getResponseStatus()));
    }
}
Also used : OAuthProblemException(org.apache.oltu.oauth2.common.exception.OAuthProblemException) OAuthIssuerImpl(org.apache.oltu.oauth2.as.issuer.OAuthIssuerImpl) ResponseEntity(org.springframework.http.ResponseEntity) OAuthTokenRequest(org.apache.oltu.oauth2.as.request.OAuthTokenRequest) MD5Generator(org.apache.oltu.oauth2.as.issuer.MD5Generator) OAuthIssuer(org.apache.oltu.oauth2.as.issuer.OAuthIssuer) OAuthResponse(org.apache.oltu.oauth2.common.message.OAuthResponse) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Example 43 with OAuthSystemException

use of org.apache.oltu.oauth2.common.exception.OAuthSystemException in project lusid-sdk-java by finbourne.

the class OAuthOkHttpClient method execute.

@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(request.getBody(), mediaType) : 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 : 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 44 with OAuthSystemException

use of org.apache.oltu.oauth2.common.exception.OAuthSystemException in project aos-Video by nova-video-player.

the class TraktSigninDialogPreference method onClick.

@Override
public void onClick() {
    try {
        OAuthClientRequest t = Trakt.getAuthorizationRequest(getSharedPreferences());
        final OAuthData oa = new OAuthData();
        OAuthCallback codeCallBack = new OAuthCallback() {

            @Override
            public void onFinished(final OAuthData data) {
                // TODO Auto-generated method stub
                if (data.code != null) {
                    final ProgressDialog mProgress = new ProgressDialog(getContext());
                    AsyncTask t = new AsyncTask() {

                        @Override
                        protected void onPreExecute() {
                            mProgress.show();
                        }

                        @Override
                        protected Object doInBackground(Object... params) {
                            OAuthAccessTokenResponse res = Trakt.getAccessToken(oa.code);
                            return res;
                        }

                        @Override
                        protected void onPostExecute(Object result) {
                            mProgress.dismiss();
                            if (result != null && result instanceof OAuthAccessTokenResponse) {
                                OAuthAccessTokenResponse res = (OAuthAccessTokenResponse) result;
                                if (res.getAccessToken() != null) {
                                    Trakt.setAccessToken(getSharedPreferences(), res.getAccessToken());
                                    Trakt.setRefreshToken(getSharedPreferences(), res.getRefreshToken());
                                    TraktSigninDialogPreference.this.notifyChanged();
                                }
                            }
                        }
                    };
                    t.execute();
                } else {
                    new AlertDialog.Builder(getContext()).setNegativeButton(android.R.string.ok, null).setMessage(R.string.dialog_subloader_nonetwork_title).setIcon(android.R.drawable.ic_dialog_alert).show();
                }
            }
        };
        od = new OAuthDialog(getContext(), codeCallBack, oa, t);
        od.show();
        od.setOnDismissListener(mOnDismissListener);
        od.setOnCancelListener(new DialogInterface.OnCancelListener() {

            @Override
            public void onCancel(DialogInterface dialogInterface) {
                mOnDismissListener.onDismiss(dialogInterface);
            }
        });
    } catch (OAuthSystemException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}
Also used : DialogInterface(android.content.DialogInterface) OAuthSystemException(org.apache.oltu.oauth2.common.exception.OAuthSystemException) AsyncTask(android.os.AsyncTask) ProgressDialog(android.app.ProgressDialog) OAuthAccessTokenResponse(org.apache.oltu.oauth2.client.response.OAuthAccessTokenResponse) OAuthClientRequest(org.apache.oltu.oauth2.client.request.OAuthClientRequest)

Example 45 with OAuthSystemException

use of org.apache.oltu.oauth2.common.exception.OAuthSystemException in project pyramus by otavanopisto.

the class SecurityFilter method hasOAuthApiAccess.

private boolean hasOAuthApiAccess() {
    try {
        OAuthAccessResourceRequest oauthRequest = new OAuthAccessResourceRequest(request, ParameterStyle.HEADER);
        String accessToken = oauthRequest.getAccessToken();
        ClientApplicationAccessToken clientApplicationAccessToken = oauthController.findByAccessToken(accessToken);
        if (clientApplicationAccessToken == null) {
            return false;
        } else {
            Long currentTime = System.currentTimeMillis() / 1000L;
            if (currentTime > clientApplicationAccessToken.getExpires()) {
                return false;
            } else {
                return true;
            }
        }
    } catch (OAuthProblemException e) {
        return false;
    } catch (OAuthSystemException e) {
        return false;
    }
}
Also used : OAuthProblemException(org.apache.oltu.oauth2.common.exception.OAuthProblemException) OAuthAccessResourceRequest(org.apache.oltu.oauth2.rs.request.OAuthAccessResourceRequest) ClientApplicationAccessToken(fi.otavanopisto.pyramus.domainmodel.clientapplications.ClientApplicationAccessToken) OAuthSystemException(org.apache.oltu.oauth2.common.exception.OAuthSystemException)

Aggregations

OAuthSystemException (org.apache.oltu.oauth2.common.exception.OAuthSystemException)100 OAuthClientRequest (org.apache.oltu.oauth2.client.request.OAuthClientRequest)55 OAuthProblemException (org.apache.oltu.oauth2.common.exception.OAuthProblemException)49 OAuthResponse (org.apache.oltu.oauth2.common.message.OAuthResponse)49 IOException (java.io.IOException)40 Request (okhttp3.Request)29 Response (okhttp3.Response)29 OAuthJSONAccessTokenResponse (org.apache.oltu.oauth2.client.response.OAuthJSONAccessTokenResponse)22 Builder (okhttp3.Request.Builder)19 URI (java.net.URI)17 OAuthBearerClientRequest (org.apache.oltu.oauth2.client.request.OAuthBearerClientRequest)17 Map (java.util.Map)16 OAuthClientResponse (org.apache.oltu.oauth2.client.response.OAuthClientResponse)15 MediaType (okhttp3.MediaType)14 RequestBody (okhttp3.RequestBody)14 TokenRequestBuilder (org.apache.oltu.oauth2.client.request.OAuthClientRequest.TokenRequestBuilder)14 MD5Generator (org.apache.oltu.oauth2.as.issuer.MD5Generator)12 OAuthClient (org.apache.oltu.oauth2.client.OAuthClient)12 RequestMapping (org.springframework.web.bind.annotation.RequestMapping)12 Path (javax.ws.rs.Path)11