Backbone.js 和用户认证 [英] Backbone.js and user authentication
问题描述
我一直想知道如何使用 Backbone 对用户进行身份验证,因为我已经阅读了一些关于它的文章,其中很多都在谈论令牌和密钥.但我只想能够像往常一样登录用户并注册用户.
我在想,在 Web 应用程序启动时,会有一个对路由/me"的请求,然后如果用户登录,服务器会向用户返回适当的信息.
就像如果路由返回 {loggedIn: false}
一样,骨干路由器只会将用户发送到登录/注册页面.但是如果它返回一个用户的个人资料信息,那么这显然意味着他有一个会话.
这是在使用 Backbone 时返回用户身份验证的好方法吗?
简短回答:连接 $.ajax 以响应 401(未授权)状态代码.
长答案:我们正在使用来自单页网站的 RESTful api.当服务器检测到未经授权的请求时,它只会返回 401.客户端将重定向到/login?#requested/resource.
/login
将提示授权(在我们的例子中重定向到 google 的 oath 服务器)然后添加一个授权 cookie 并重定向到最初请求的 #requested/resource
>
我们还在每个 $.ajax 请求上发送 auth cookie.
希望这会有所帮助.
定义(['jquery','jquery.cookie'],功能($){var redirectToLogin = 函数 () {var locationhref = "/登录";如果 (location.hash && location.hash.length > 0) {locationhref += "?hash=" + location.hash.substring(1);}location.href = locationhref;};var $doc = $(document);$doc.ajaxSend(function (event, xhr) {var authToken = $.cookie('access_token');如果(身份验证令牌){xhr.setRequestHeader("Authorization", "Bearer" + authToken);}});$doc.ajaxError(function (event, xhr) {如果(xhr.status == 401)重定向登录();});});
I have been wondering for quite a while how I would go about authenticating users using Backbone because I have been reading a few articles about it and a lot of them are talking about tokens and keys.. But I just want to be able to sign in a user and register a user like you would normally.
I was thinking that on the web app start up there would be a request to the route '/me' and then the server gives the user back appropriate information if he/she is logged in.
Like if the route came back with {loggedIn: false}
the backbone router would send the user to the login/register pages only. But if it came back with a users profile information then it would obviously mean he had a session.
Is this an okay way of going back user authentication when using Backbone?
Short answer: wire up $.ajax to respond to 401 (Unauthorized) status codes.
Long answer: We're consuming a RESTful api from a single page website. when the server detects an unauthorized request, it just returns a 401. The client will redirect to /login?#requested/resource.
/login
will prompt for authorization (redirect to google's oath server in our case) then add an authorization cookie and redirect to the originally requested #requested/resource
we're also sending the auth cookie on every $.ajax request.
Hopefully this is helpful.
define(
[
'jquery',
'jquery.cookie'
],
function ($) {
var redirectToLogin = function () {
var locationhref = "/login";
if (location.hash && location.hash.length > 0) {
locationhref += "?hash=" + location.hash.substring(1);
}
location.href = locationhref;
};
var $doc = $(document);
$doc.ajaxSend(function (event, xhr) {
var authToken = $.cookie('access_token');
if (authToken) {
xhr.setRequestHeader("Authorization", "Bearer " + authToken);
}
});
$doc.ajaxError(function (event, xhr) {
if (xhr.status == 401)
redirectToLogin();
});
});
这篇关于Backbone.js 和用户认证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!