12

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?

2
  • Signup, Register & Authenticate using Javascript ? I would say no. Put these pieces using backend framework using Php, Erlang, Python, Asp.net. After user log's in, set a cookie (best solution i can think of). Each xml http request will possess the cookie that would help you validate the user on server side. There are certain stuff that you got to do on server and Authentication, Authorization is one of them. Do the Js stuff after user logs in Jul 6, 2012 at 11:27
  • 1
    That is what I am saying in my question but I am wondering if my method is a good way to deal with a logged in or unauthorised user
    – jamcoupe
    Jul 6, 2012 at 12:38

1 Answer 1

32

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();
        });
    });
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.