簡體   English   中英

使用Java中的Apache OAuth客戶端2.0庫生成授權代碼和用戶令牌的問題

[英]Issues with Generating Authorization code and User Token using Apache OAuth client 2.0 library in Java

我試圖使用Java中的Apache OAuth Client 2.0 Library自動執行用戶級別令牌創建/生成過程(REST /授權授予代碼)。 以下是我從https://cwiki.apache.org/confluence/display/OLTU/OAuth+2.0+Client+Quickstart獲得的正在使用的代碼,

`/*Previous Codes & starting the below with Try/Catch*/
OAuthClientRequest request = OAuthClientRequest
   .authorizationLocation("Authorization URL")
   .setClientId("ClientID")
   .setRedirectURI("Redirect URL")
   .buildQueryMessage();
request.getLocationUri();
OAuthAuthzResponse oar = OAuthAuthzResponse.oauthCodeAuthzResponse(request);
String code = oar.getCode();
/*Other Codes and starting the below with Try/Catch*/
OAuthClientRequest request = OAuthClientRequest
                .tokenLocation("TokenEndPointURL")
                .setGrantType(GrantType.AUTHORIZATION_CODE)
                .setClientId("ClientID")
                .setClientSecret("ClientSecret")
                .setRedirectURI("REdirectURL")
                .setCode(code)//Authorization Code from above
                .buildQueryMessage();
OAuthClient oAuthClient = new OAuthClient(new URLConnectionClient());
GitHubTokenResponse oAuthResponse = oAuthClient.accessToken(request, GitHubTokenResponse.class);
String accessToken = oAuthResponse.getAccessToken();
String expiresIn = oAuthResponse.getExpiresIn();`

但是,我在以下幾行中收到了(來自Eclipse中錯誤的推斷)編譯錯誤,

oauthCodeAuthzResponse方法接受httpservlet對象,並且不支持OAuthAuthzReponse Type

OAuthAuthzResponse oar = OAuthAuthzResponse.oauthCodeAuthzResponse(request);

有人可以讓我知道是否有解決方法嗎? 或如何將oauthCodeAuthzResponse請求轉換為httpservlet請求? 還是我做錯了什么或缺少什么?

OAuthAuthzResponse oar = OAuthAuthzResponse.oauthCodeAuthzResponse(request);
String code = oar.getCode();

我認為上面的代碼應該寫在重定向URI端點的實現中,而不是在客戶端代碼中。

正確理解授權碼流將有所幫助。 授權代碼從授權服務器的授權端點發出,並將其傳遞到重定向URI指向的位置。 也就是說,授權代碼不會直接傳遞到客戶端應用程序。

當授權服務器發出授權代碼時,它將以下所示的HTTP響應發送回客戶端的Web瀏覽器。

HTTP/1.1 302 Found
Location: {Redirect URI}
  ?code={Authorization Code}  // - Always included
  &state={Arbitrary String}   // - Included if the authorization
                              //   request included 'state'.

302 Found觸發Web瀏覽器轉到Location標頭指向的Location 因此,您必須實現接收授權代碼的位置,並且實現必須以某種方式將授權代碼傳遞給客戶端應用程序。

還要注意,在(a)授權請求(=對授權端點的請求)和(b)令牌請求(=對令牌端點的請求)之間顯示授權頁面(HTML),並且該頁面需要最終用戶相互作用。 有關詳細信息,請參見“ 所有OAuth 2.0流程的圖表和影片 ”中的“ 1.授權代碼流程”。

最終,我能夠使用httpclient生成令牌-請參見下面的邏輯。

獲取授權碼

public String getAuthCode(String authUrl, String userName, String password, String scope, String clientId, 
        String redirectUrl) throws ClientProtocolException, IOException, URISyntaxException
{
    DefaultHttpClient httpclient = new DefaultHttpClient();

    System.out.println("Adding Paramters to a Array List as NameValuePair");
    List<NameValuePair> params = new ArrayList<NameValuePair>();
    params.add(new BasicNameValuePair("scope", scope));
    params.add(new BasicNameValuePair("response_type", "code"));
    params.add(new BasicNameValuePair("client_id", clientId));
    params.add(new BasicNameValuePair("redirect_uri", redirectUrl));

    System.out.println("Parameters List:" + params);

    System.out.println("Building the URI with Authorization Endpoint by adding the Parameters create in Array List");
    URI uri = new URIBuilder(authUrl)
            .addParameters(params)
            .build();
    System.out.println("Built URI:" + uri);

    System.out.println("Creating HTTPGET with the Created URI");
    HttpGet get = new HttpGet(uri);
    System.out.println("HttpGet:" + get);

    System.out.println("Creating Client Context");
    HttpClientContext context = HttpClientContext.create();
    System.out.println("Created Client Context:" + context);


    System.out.println("Executing the GET Method with the created Client Context");
    HttpResponse response = httpclient.execute(get, context);
    System.out.println("HttpResponse:" + response);

    System.out.println("Getting the Final URI from the Submitted Get Method");
    URI finalUrl = get.getURI();
    System.out.println("Final URL:" + finalUrl);

    System.out.println("Creating a List of URI from the Redirection Locations using Client Context");
    List<URI> locations = context.getRedirectLocations();
    System.out.println("List of URI:" + locations);

    if (locations != null) {
        finalUrl = locations.get(locations.size() - 1);
    }
    System.out.println("Taking the last URL as Final:" + finalUrl);

    System.out.println("Creating Entity");
    EntityUtils.consume(response.getEntity());
    System.out.println("Consume the Entity:" + response.getEntity());

    String userid = "username=".concat(userName);
    System.out.println("UserID:" + userid);
    String userPassword = "Password=".concat(password);
    System.out.println("User Password:" + userPassword);
    String cred = userid+"&"+userPassword;
    System.out.println("User Credentials:" + cred);
    HttpPost postReq = new HttpPost(finalUrl);
    StringEntity entity = new StringEntity(cred);
    postReq.setEntity(entity);
    postReq.addHeader("Content-Type", "application/x-www-form-urlencoded"); 
    postReq.addHeader("User-Agent", "MSIE 8.0");


    HttpResponse responsePost = httpclient.execute(postReq,context);
    List<Header> location = Arrays.asList(responsePost.getHeaders("Location"));
    String locationUrl = location.get(0).getValue().toString();
    String[] locationArray = locationUrl.split("=");
    String authCode = locationArray[1].trim().toString();
    //System.out.println(authCode);

    EntityUtils.consume(responsePost.getEntity());
    System.out.println("Response Post Entity:"+responsePost);
    System.out.println("Authorization Code:" +authCode);
    return authCode;
}

獲取令牌

public List<String> getJwtToken(String clientId,String clientSecret, String authUrl,String tokenUrl,
            String redirectUrl,String accessTokenScope, String LDAPuserName,String LDAPpassword) throws Exception
    {

        List<String> tokens = new ArrayList<String>();
        //Generate the User Level Token & JWT Token using the Get/Post Method
        DefaultHttpClient httpclient = new DefaultHttpClient();


        System.out.println("Calling the get Auth Code Method");
        String authCode = getAuthCode(authUrl, LDAPuserName, LDAPpassword, accessTokenScope, clientId, redirectUrl);
        System.out.println("Authorization Code:" + authCode);

        HttpPost tokenPost = new HttpPost(tokenUrl);
        System.out.println("Token HttpPost:" + tokenPost);

        System.out.println("Adding the Parameters in an ArrayList as NameValuePair");
        List<NameValuePair> tokenParams = new ArrayList<NameValuePair>();
        tokenParams.add(new BasicNameValuePair("client_id", clientId));
        tokenParams.add(new BasicNameValuePair("client_secret", clientSecret));
        tokenParams.add(new BasicNameValuePair("code", authCode));
        tokenParams.add(new BasicNameValuePair("grant_type", "authorization_code"));
        System.out.println("Token Call Parameter:" + tokenParams);

        System.out.println("Setting the Parameters as URL Encoded Entity");
        tokenPost.setEntity(new UrlEncodedFormEntity(tokenParams));
        System.out.println("URL Encoded Entity" + tokenPost);

        System.out.println("Executing the Token Post Method");
        HttpResponse responseJWT = httpclient.execute(tokenPost);
        System.out.println("Setting the Parameters as URL Encoded Entity" + responseJWT);

        System.out.println("Parsing the ResponseJWT using JsonParser & JsonObjet");
        JsonParser parser = new JsonParser();   
        System.out.println("Json Parser:" + parser);
        JsonObject data = (JsonObject) parser.parse(new InputStreamReader(responseJWT.getEntity().getContent()));
        System.out.println("Json Object" + data);

        String token = data.get("access_token").toString();
        System.out.println("Access Token:" + token);

        String jwt="";
        try
        {
            jwt = data.get("jwt_token").toString();
            System.out.println("JWT Token:" + jwt);
        }
        catch(Exception ejwt)
        {
            System.out.println("Exception occured converting Jwt Token to String");
            ejwt.printStackTrace();
        }

        String refresh = data.get("refresh_token").toString();
        System.out.println("Refresh Token:" + refresh);

        String accessToken = token.substring(1, token.length()-1);
        tokens.add(0, accessToken);
        System.out.println("Real Access Token:" + accessToken);

        String jwtToken ="";
        try
        {
        jwtToken = jwt.substring(1, jwt.length()-1);
        tokens.add(1, jwtToken);
        System.out.println("Real JWT Token:" + jwtToken);
        }

        catch(Exception ejwt)
        {
            System.out.println("Exception occured adding Jwt Token to String List");
            ejwt.printStackTrace();
        }

        String refreshToken = refresh.substring(1, refresh.length()-1);
        System.out.println("Real Refresh Token:" + refreshToken);

        return tokens;

    }

我已經使用了這種驗證碼方法。 制作驗證碼時出現此錯誤

> location->[] 
[ERROR] 2018-10-12 14:16:59.414 [http-nio-8080-exec-3]
> [dispatcherServlet] - Servlet.service() for servlet
> [dispatcherServlet] in context with path [] threw exception [Request
> processing failed; nested exception is
> java.lang.ArrayIndexOutOfBoundsException: 0] with root cause
> java.lang.ArrayIndexOutOfBoundsException: 0

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM