Authentication with Flask/Django and a javascript front end

Question:

I’m struggling to understand how flask_login or django knows when a user logs in that they retain access?

If I were to use ReactJs or Angular with flask-restful or django/tastypie, what is being added to the header/body of future json requests to ensure that my user stays logged in?

Asked By: Rob

||

Answers:

This is done via sessions, which is based on cookies. From the Flask documentation:

In addition to the request object there is also a second object called session which allows you to store information specific to a user from one request to the next. This is implemented on top of cookies for you and signs the cookies cryptographically.

and the Django docs:

Django provides full support for anonymous sessions. The session framework lets you store and retrieve arbitrary data on a per-site-visitor basis. It stores data on the server side and abstracts the sending and receiving of cookies. Cookies contain a session ID – not the data itself (unless you’re using the cookie based backend).

So, the requests to the server automatically include a cookie that indicates some ID that the server then uses to figure out what the session data should be for the given user. In general, when Ajax requests are made from client-side applications to the server, this cookie is included and so ensures that the user is considered to be logged in for those requests.

In some cases, you can also (optionally) manually add a special header to HTTP requests to indicate which user is logged in.

See also Securing RESTapi in flask for some more information.

Answered By: Michelle Tilley

If you use REST service then you should take a look at oAuth. In other words it uses token which you attach to every request from client to server and the last can determine which user sent this request by this token.

On the other hand, you can use cookie or session to determine a user status. And in this case you don’t need to add any headers to your request.

Also I recommend you this package for Django – Django Rest Framework (there you can read more about token and auth via REST) and this extension for Flask.

Answered By: Alexander Ivantsov
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.