Search in sources :

Example 6 with OAuth

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

the class RemoteAPITokenServiceImpl method updateTokenFromRefreshToken.

/**
 * {@inheritDoc}
 */
@Transactional
public RemoteAPIToken updateTokenFromRefreshToken(RemoteAPI api) {
    RemoteAPIToken token = null;
    try {
        token = getToken(api);
        String refreshToken = token.getRefreshToken();
        if (refreshToken != null) {
            URI serviceTokenLocation = UriBuilder.fromUri(api.getServiceURI()).path("oauth").path("token").build();
            OAuthClientRequest tokenRequest = OAuthClientRequest.tokenLocation(serviceTokenLocation.toString()).setClientId(api.getClientId()).setClientSecret(api.getClientSecret()).setRefreshToken(refreshToken).setGrantType(GrantType.REFRESH_TOKEN).buildBodyMessage();
            OAuthJSONAccessTokenResponse accessToken = oauthClient.accessToken(tokenRequest);
            token = buildTokenFromResponse(accessToken, api);
            delete(api);
            token = create(token);
            logger.debug("Token for api " + api + " updated by refresh token.");
        } else {
            logger.debug("No refresh token for api " + api + ". Cannot update access token.");
        }
    } catch (EntityNotFoundException ex) {
        logger.debug("Token not found for api " + api + ".  Cannot update access token.");
    } catch (OAuthProblemException | OAuthSystemException ex) {
        logger.error("Updating token by refresh token failed", ex.getMessage());
    }
    return token;
}
Also used : OAuthProblemException(org.apache.oltu.oauth2.common.exception.OAuthProblemException) RemoteAPIToken(ca.corefacility.bioinformatics.irida.model.RemoteAPIToken) OAuthSystemException(org.apache.oltu.oauth2.common.exception.OAuthSystemException) OAuthJSONAccessTokenResponse(org.apache.oltu.oauth2.client.response.OAuthJSONAccessTokenResponse) EntityNotFoundException(ca.corefacility.bioinformatics.irida.exceptions.EntityNotFoundException) OAuthClientRequest(org.apache.oltu.oauth2.client.request.OAuthClientRequest) URI(java.net.URI) Transactional(org.springframework.transaction.annotation.Transactional)

Example 7 with OAuth

use of org.apache.oltu.oauth2.common.OAuth in project aos-MediaLib by nova-video-player.

the class TraktV2 method getAccessToken.

/**
 * Request an access token from trakt. Builds the request with {@link #getAccessTokenRequest(String, String, String,
 * String)} and executes it, then returns the response which includes the access token.
 *
 * <p> Supply the received access token to {@link #setAccessToken(String)}.
 *
 * <p> On failure re-authorization of your app is required (see {@link #getAuthorizationRequest(String, String,
 * String, String)}).
 *
 * @param clientId The OAuth client id obtained from trakt.
 * @param clientSecret The OAuth client secret obtained from trakt.
 * @param redirectUri The redirect URI previously used for obtaining the auth code.
 * @param authCode A valid authorization code (see {@link #getAuthorizationRequest(String, String, String,
 * String)}).
 */
public static OAuthAccessTokenResponse getAccessToken(String clientId, String clientSecret, String redirectUri, String authCode) throws OAuthSystemException, OAuthProblemException {
    OAuthClientRequest request = getAccessTokenRequest(clientId, clientSecret, redirectUri, authCode);
    OAuthClient client = new OAuthClient(new TraktHttpClient());
    return client.accessToken(request);
}
Also used : OAuthClient(org.apache.oltu.oauth2.client.OAuthClient) OAuthClientRequest(org.apache.oltu.oauth2.client.request.OAuthClientRequest)

Example 8 with OAuth

use of org.apache.oltu.oauth2.common.OAuth 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 9 with OAuth

use of org.apache.oltu.oauth2.common.OAuth 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 10 with OAuth

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

Aggregations

OAuthSystemException (org.apache.oltu.oauth2.common.exception.OAuthSystemException)22 OAuthProblemException (org.apache.oltu.oauth2.common.exception.OAuthProblemException)17 OAuthClientRequest (org.apache.oltu.oauth2.client.request.OAuthClientRequest)14 OAuthResponse (org.apache.oltu.oauth2.common.message.OAuthResponse)11 RequestMapping (org.springframework.web.bind.annotation.RequestMapping)10 URI (java.net.URI)9 HashMap (java.util.HashMap)7 OAuthIssuerImpl (org.apache.oltu.oauth2.as.issuer.OAuthIssuerImpl)6 OAuthASResponse (org.apache.oltu.oauth2.as.response.OAuthASResponse)6 ResponseEntity (org.springframework.http.ResponseEntity)6 IdentityOAuth2Exception (org.wso2.carbon.identity.oauth2.IdentityOAuth2Exception)6 MD5Generator (org.apache.oltu.oauth2.as.issuer.MD5Generator)5 OAuthAuthzRequest (org.apache.oltu.oauth2.as.request.OAuthAuthzRequest)5 OAuthClient (org.apache.oltu.oauth2.client.OAuthClient)5 IOException (java.io.IOException)4 ArrayList (java.util.ArrayList)4 ConcurrentHashMap (java.util.concurrent.ConcurrentHashMap)4 OAuthAuthzResponse (org.apache.oltu.oauth2.client.response.OAuthAuthzResponse)4 HttpHeaders (org.springframework.http.HttpHeaders)4 ServletException (javax.servlet.ServletException)3