从java中的OAuth2中的重定向URL获取参数

时间:2018-04-08 01:18:10

标签: oauth oauth-2.0 url-redirection jersey-2.0

我需要使用OAuth 2.0来访问用户的数据。 我使用了glassfish security oauth 2库来实现OAuth 2客户端。 在用户授予访问数据的权限后,我不确定如何获取代码和状态值。

ClientIdentifier clientIdentifier = new ClientIdentifier(clientId, secret);
    OAuth2CodeGrantFlow.Builder builder = 
OAuth2ClientSupport.authorizationCodeGrantFlowBuilder(clientIdentifier,
            HOST_NAME + "/authorize",
            HOST_NAME + "/token");

    OAuth2CodeGrantFlow flow = builder
            .scope("activity")

            .redirectUri("http://example.com/#/")

            .build();
    String authorizationUri = flow.start();
    System.out.println(authorizationUri);
    String redirectedUrl = getFinalRedirectedUrl(authorizationUri);

    System.out.print("Enter the authorization code: ");
    String code = "";
    String state = "";
    try {
        code = IN.readLine();
        state = IN.readLine();
    } catch (final IOException ex) {
        throw new RuntimeException(ex);
    }
    final TokenResult result = flow.finish(code, state);
    System.out.println("Access Token: " + result.getAllProperties());

}

现在,我正在从重定向的网址手动获取代码和状态。我该如何自动化它。

我试过

public static String getFinalRedirectedUrl(String url) {
    String finalRedirectedUrl = url;
    try {
        HttpURLConnection connection;
        do {
            connection = (HttpURLConnection) new URL(finalRedirectedUrl).openConnection();
            connection.setInstanceFollowRedirects(false);
            connection.setUseCaches(false);
            connection.setRequestMethod("GET");
            connection.connect();
            int responseCode = connection.getResponseCode();
            if (responseCode >= 300 && responseCode < 400) {
                String redirectedUrl = connection.getHeaderField("Location");
                if (null == redirectedUrl) {
                    break;
                }
                finalRedirectedUrl = redirectedUrl;
            } else
                break;
        } while (connection.getResponseCode() != HttpURLConnection.HTTP_OK);
        connection.disconnect();
    } catch (Exception e) {
        e.printStackTrace();
    }
    System.out.println(finalRedirectedUrl);
    return finalRedirectedUrl;
}

但它返回登录页面。

0 个答案:

没有答案