Authentication With Flask/Django And A Javascript Front End

- 1 answer

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?



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.