RFC 2617指定HTTP Basic and Digest Auth标准,其工作原理如维基百科的";带有说明的实例";小节:
- 客户端要求提供一个需要身份验证但不提供用户名和密码的页面。通常,这是因为用户只需输入地址或跟随页面链接
- 服务器用401〃;客户端错误";响应代码,提供身份验证领域和一个随机生成的、称为nonce的一次性值
- 此时,浏览器将向用户显示身份验证领域(通常是对正在访问的计算机或系统的描述),并提示输入用户名和密码。此时用户可以决定取消
- 一旦提供了用户名和密码,客户端就会重新发送相同的请求,但会添加一个包含响应代码的身份验证标头
- 在本例中,服务器接受身份验证并返回页面。如果用户名无效和/或密码不正确;401〃;响应代码,客户端将再次提示用户
注意:客户端可能已经拥有所需的用户名和密码,而无需提示用户,例如,如果它们以前已由web浏览器存储。
我正在使用Facebook实现的OAuth2草案标准执行登录。
给定一个具有公开的公共API(例如:JSONRPC或REST)的服务器,如何编写客户端JavaScript前端以包括前面提到的RFC 2617示例中的功能,但对于Facebook验证
我发现了一个官方的(但未维护,现在正式放弃)客户端JavaScript库实现示例的存储库。点击此处查看最新的fork。以下是该页面的JQuery示例:
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<title>Connect JavaScript - jQuery Login Example</title>
</head>
<body>
<h1>Connect JavaScript - jQuery Login Example</h1>
<div>
<button id="login">Login</button>
<button id="logout">Logout</button>
<button id="disconnect">Disconnect</button>
</div>
<div id="user-info" style="display: none;"></div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js">
</script>
<div id="fb-root"></div>
<script src="http://connect.facebook.net/en_US/all.js"></script>
<script>
// initialize the library with the API key
FB.init({
apiKey: '48f06bc570aaf9ed454699ec4fe416df'
});
// fetch the status on load
FB.getLoginStatus(handleSessionResponse);
$('#login').bind('click', function () {
FB.login(handleSessionResponse);
});
$('#logout').bind('click', function () {
FB.logout(handleSessionResponse);
});
$('#disconnect').bind('click', function () {
FB.api({
method: 'Auth.revokeAuthorization'
}, function (response) {
clearDisplay();
});
});
// no user, clear display
function clearDisplay() {
$('#user-info').hide('fast');
}
// handle a session response from any of the auth related calls
function handleSessionResponse(response) {
// if we dont have a session, just hide the user info
if (!response.session) {
clearDisplay();
return;
}
// if we have a session, query for the user's profile picture and name
FB.api({
method: 'fql.query',
query: 'SELECT name, pic FROM profile WHERE id=' + FB.getSession().uid
},
function (response) {
var user = response[0];
$('#user-info').html('<img src="' + user.pic + '">' + user.name).show('fast');
});
}
</script>
请随时提出改进建议。我最希望看到:
- Vanilla JavaScript实现
- JSONRPC调用以方便在个人服务器端登录
- 路由(即:成功登录后重定向到已登录用户主页)