Backbone HTTP basic rest api authentication

2020-06-16 04:12发布

问题:

I am using Backbone.js and it communicates with a stateless rest API. Some calls require authentication, through HTTP basic.

What I don't understand is, somehow I have to authenticate each request, how could I do this securely? My first thought was to have a cookie, store the username and password but this would be vulnerable?

Can this be done securely?

回答1:

Is https://github.com/fiznool/backbone.basicauth something you'd find useful?

This plugin enables access to remote resources which are protected by HTTP Basic Authentication through your Backbone Models and Collections.

How does it work?

A resource protected with HTTP Basic Authentication requires the following HTTP header to be set on every request:

Authorization: Basic The access token is formed by taking the username and password, concatenating together with a : separator and encoding into Base64.

This plugin handles the Base64 encoding and automatically sets the Authorization header on every request which uses Backbone.sync.



回答2:

There are two themes to this question. One is about security and one seems to be about REST rules.

The way to do authentication securely, is to pass that data through an SSL connection. It's the only way to securely transfer data over the wire.

With regards to sending authentication using basic auth over each request (REST), not many people I know do this in reality.

There's always a big long discussion on how much security is enough security and it really depends on your application and what the purpose is. I know this isn't the definitive answer you might be looking for but I'll just give you my take and how I'm going about dealing with the issues you mention.

With RESTful apps, the story is one should authenticate each request but in real practice I find this is more a "guide" than a hard rule. Rare is the fully RESTful application that follows all the rules. I use an encrypted cookie to store the user session data with a standard authentication flow that happens once and expires in a week. Data transfers happen through SSL to prevent MITM attacks and a modified Backbone sync sends a CSRF token along with each POST, PUT, DELETE to prevent cross site request forgeries. Probably "good enough" for the social app that I am working on. Maybe not if you're doing bank wire transfers and stuff. Hope this sort of gives you a point of reference in judging what you might want to do.