java – 通过HttpURLConnection进行浏览器身份验证

前端之家收集整理的这篇文章主要介绍了java – 通过HttpURLConnection进行浏览器身份验证前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
目前我正在研究 TMDb API的实现.有一种叫做 User Authentication方法.我已成功实施了第1步

Step 1: Generate a Request Token

Start by making an API call to the new token method. This will return
a new request token that will be valid for 60 minutes. The request
token is not authorized by the user at this stage. Request tokens are
API account specific and are the tie between your application and the
user in step 2.

对于第1步,我有以下代码

URL url = new URL("http://api.themoviedb.org/3/authentication/token/new?api_key=the_key");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
StringWriter writer = new StringWriter();
String line;
while ((line = reader.readLine()) != null) {
    writer.write(line);
}
reader.close();
Map<String,List<String>> headerFields = connection.getHeaderFields();
String callBackUrl = null;
for(Map.Entry<String,List<String>> entry : headerFields.entrySet()) {
    if(entry.getKey() != null && entry.getKey().equals("Authentication-Callback")) {
        callBackUrl = entry.getValue().get(0);
    }
}

它在控制台中打印回调URL以及请求令牌(如果我将writer.toString()转换为Json对象).

但第二部分是用户名和密码的用户身份验证.回调URL将用户重定向到TMDb的登录页面.我已经通过将回调网址从控制台复制粘贴到浏览器来测试它.

第2步说明:

Step 2: Request Authorization From the User

Once you have a valid request token,your application needs to open a
web browser and send them to TMDb. The HTTP response when generating a
new token will include a Authentication-Callback header that you can
easily use for the redirect.

If the user is not logged in to TMDb,they will be redirected to the
login page before being asked to grant your application permission to
use their account. Once the user has granted your application
permission to use their account,the browser-based part of this
process is over and you can return them to your application.

Just like the request for a new token,the approved response will
include a Authentication-Callback header which again,is a convenient
way to redirect your application back to the API and generate the real
session id.

现在我的问题是:如果我有用户名和密码,我可以通过HttpURLConnection或任何其他方式验证该用户吗?

我试过这个:

url = new URL(callBackUrl);
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");        
BASE64Encoder encoder = new BASE64Encoder();
String usernamepassword = "myusername" + ":" + "mypassword";
String encodedAuthorization = encoder.encode(usernamepassword.getBytes());
connection.setRequestProperty("Authorization","Basic "+ encodedAuthorization);
headerFields = connection.getHeaderFields();

for(Map.Entry<String,List<String>> entry : headerFields.entrySet()) {
    System.out.println(entry.getKey() + " : " +entry.getValue());
}

但在控制台我得到:

null : [HTTP/1.1 404 Not Found]
Status : [404 Not Found]
X-Frame-Options : [sameorigin]
Date : [Tue,28 Feb 2012 08:30:17 GMT]
Vary : [Accept-Encoding]
X-Cascade : [pass]
Content-Length : [7835]
X-XSS-Protection : [1; mode=block]
Set-Cookie : [tmdb.session=BAh7CUkiD3Nlc3Npb25faWQGOgZFRiJFNGRkMjc5ODYwMjJmYWYwZDlmOGE5%0AOTVjY2E0NWFjMzhhYTRiOGFjOGJiYjQ5ZGFhNzExNDdkMGM4MWNhZGUyMEki%0ADWxhbmd1YWdlBjsARkkiB2VuBjsARkkiC2xvY2FsZQY7AEZJIgd1cwY7AEZJ%0AIg5sb2dnZWRfaW4GOwBGRg%3D%3D%0A; path=/; expires=Thu,29-Mar-2012 08:30:17 GMT; HttpOnly]
Content-Type : [text/html;charset=utf-8]
Connection : [keep-alive]
Server : [Nginx]

如你看到的:

Status : [404 Not Found]

所以最后的程序并不富有成效.

我是以错误的方式实施身份验证吗?

我非常感谢你的建议.

提前致谢.

解决方法

我不熟悉TmDB,但我已经在他们的用户身份验证过程中阅读了该页面,我认为你误解了它.

他们明确表示他们不希望第三方应用程序存储用户名/密码凭据,或者在请求中传递它(“对此系统的好处是我们从未通过空中传递用户用户名或密码或要求第三方应用程序,以在本地存储它“). callbackUrl中的页面不是你,第三方应用程序,应该发布任何东西;它是供人类使用的.用户看到此页面,询问“您是否要授予对[第三方应用程序名称]的访问权限?”如果是,请在此处登录“.您的应用程序无法控制该过程;它故意与您分开,因此您永远不会截获或存储用户的凭据.一旦用户批准了您,您将能够获得您使用的不透明令牌(会话ID)而不是凭据.

这与三足OAuth基本相同;主要区别在于OAuth需要一些额外的字段和签名计算,因此这更简单.但它与HTTP basicauth无关.

我相信你想要做的是:

>就像你正在做的那样,做第1步.但是不要只抓住Authentication-Callback标头;还解析JSON响应并获取“request_token”的值.
>通过调用new session API,检查用户是否已经授权您,再次传递API密钥以及先前获取的“request_token”.如果您使用“session_id”获得成功响应,则您已获得授权,您可以跳过其余步骤.>否则,将用户重定向(或打开浏览器,如果您还没有在浏览器中)到Authentication-Callback中指定的URL.>现在,由于登录/审批流程与您的应用程序是分开的,您如何知道它何时完成?文档不清楚,并没有描述任何方式让您获得有关它的通知(或使TMDb重定向回您的应用程序).可能需要在某个合理的时间间隔内轮询结果(即返回步骤2).

猜你在找的Java相关文章