Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Backbone.js and user authentication

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?

like image 746
jamcoupe Avatar asked Jul 06 '12 09:07

jamcoupe


1 Answers

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();
        });
    });
like image 59
timDunham Avatar answered Nov 02 '22 17:11

timDunham