Authentication

Authentication

·

2 min read

Imagine logging into your Instagram, tapping on a post, and you are redirected to the login form. You log in and finally get to see the post. You read the caption then you tap the heart and once again you are asked to log in again. You log in... once again and see your like was added to the post. You tap on the icon to take you back to your main feed and... you guessed it you are redirected to the login form again. Can you imagine how extremely annoying that would be?!?!?! Thank God for authentication! In Flask, authentication refers to verifying a user's identity. Persisting authentication allows a user to remain logged in across multiple requests. Let's take a look at how to create a persisting authentication environment for our users.

Flask Session

Creating a persisting authentication environment for our users is simple we can use Flask session.

Persisting Authentication

  from flask import session

  app.config['SESSION_PERMANENT'] = True  
  app.config['PERMANENT_SESSION_LIFETIME'] =  timedelta(minutes=10)
  app.secret_key = "secret key"
  #After login:
  session['user_id'] = user.id

  #On subsequent requests:
  user_id = session.get('user_id')

  #To end a session
  session['user_id'] = None

A session is a dictionary that stores data specific to a user across requests. Flask assigns the session data with a secret key and uses cookies to tie the data to the user's browser. To persist a session, configure a SESSION_PERMANENT time in your Flask app to be True. To keep the session alive for 10 minutes of inactivity just add PERMANENT_SESSION_LIFETIME.

Storing and Retrieving Data

session['user_id'] = user.id stores the user data as a dictionary. HTTP is stateless which means it does not store data in the server. That is why in an imperfect undeveloped world we could have to consistently log in just to view a post, then to like that post, and then to see our main feed. Thankfully Flask session stores cookies that hold the user data as an id. We can access session data using the session object. The get() method returns the default value (None) if the key does not exist.

Clearing Session

In the front end, we will code a fetch with a 'DELETE' HTTP verb method and have its end point direct to the route in the backend that performs session['user_id'] = None. Having it return None clears the data in the session.

Conclusion

The session object works just like a dictionary, allowing you to store, access and clear data to persist users across requests in Flask.