Authentication and authorization are essential applications in building secure web applications. this essential function is required when logging into personal online accounts for websites like Netflix, bank applications, and buildings that require secure access.
To utilize the function described, as a user you must register an account and provide personal information. However, even though register an account, you cannot access all systems because permissions are granted differently as administrator, developer, or user with different levels of accessibility.
Authentication is the process of verifying who you are when entering a secured application or building.
For example, to log in to the Amazon website, you must enter your ID and password. This verifies that legitimate users actually exist in the database and which permissions are granted to the account.
When logging in using password-based authentication, you must use a secret key which is a random key that protects the user's account from hacking.
from flask import Flask, make_response, jsonify, request, session
from flask_migrate import Migrate
from flask_restful import API, Resource
from models import db, Article, User
app = Flask(__name__)
app.secret_key = b'Y\xf1Xz\x00\xad|eQ\x80t \xca\x1a\x10K'
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///app.db'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
app.json.compact = False
migrate = Migrate(app, db)
db.init_app(app)
api = Api(app)
Authorization refers to the process of allowing or denying users' access to an application. For example, all Amazon members are given minimum privileges, and if they purchase for prime access, they are given the privilege to use the Amazon Prime service and the privilege to use music and video applications.
How to write the code.
First, create data in models.py.
class Video(db.Model, SerializerMixin):
__tablename__ = 'videos'
id = db.Column(db.Integer, primary_key=True)
title = db.Column(db.String)
author = db.Column(db.String)
files = db.Column(db.String)
is_member_only = db.Column(db.Boolean, default=False)
user_id = db.Column(db.Integer, db.ForeignKey('users.id'))
def __repr__(self):
return f'Article {self.id} by {self.title}'
class User(db.Model):
__tablename__ = "users"
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String)
password = db.Column(db.String)
created_at = db.Column(db.DateTime,
server_default=db.func.now())
videos = db.relationship('Video', backref='user')
The code below ensures that the password is securely hashed before storing and provides authenticate method to check whether a given bcrypt matches the stored hash.
@hybrid_property
def password_hash(self):
raise Exception('Password hashes may not be viewed.')
@password_hash.setter
def password_hash(self, password):
password_hash = bcrypt.generate_password_hash(
password.encode('utf-8'))
self._password_hash = password_hash.decode('utf-8')
def authenticate(self, password):
return bcrypt.check_password_hash(
self._password_hash, password.encode('utf-8'))
def __repr__(self):
return f'User {self.username}, ID {self.id}'
The before_request decorator allows you to run a function before the request. In other words, the function is defined with the .before_request() decorator to check whether any permissions are granted or not before every request is made.
@app.before_request
def is_member_only():
if request.endpoint == 'member_video' and not session.get('user_id'):
#endpoint refers to member_video route/path
return {'error':'Unauthorized'},401
class Signup(Resource):
ddef post(self):
json = request.get_json()
user = User(
username=json['username'],
)
user.password_hash=json['password']
db.session.add(user)
db.session.commit()
session['user_id']= user.id
return user.to_dict(), 201
class CheckSession(Resource):
def get(self):
#the 'get' method, will check if a session 'user_id'
#exists and matches values in session.get('user_id')
if session.get('user_id'):
user =User.query.filter(User.id==session.get('user_id')).first()
#because of filter and .first() will retrieve the first
#matching user. If a matching found will return 200
# if it's not then will return 204
return user.to_dict(),200
return {}, 204
class Login(Resource):
def post(self):
json = request.get_json()
username=json['username']
user =User.query.filter(User.username==username).first()
password=json['password']
if user.authenticate(password):
session['user_id']=user.id
return user.to_dict(), 200
return{'error': 'Invalid username or password'}, 401
class Logout(Resource):
def delete(self):
session['user_id'] = None
return {}, 204
class MemberVideo(Resource):
def get(self):
videos = [video.to_dict() for video in Video.query.all() if video.is_member_only == True]
return videos, 200
#because of @app.before_request function above, the code now checking the MemberVideo (endpoint 'member_video) and and whether there is a valid user_id in the session.
api.add_resource(Signup, '/signup', endpoint='signup')
api.add_resource(CheckSession, '/check_session', endpoint='check_session')
api.add_resource(Login, '/login', endpoint='login')
api.add_resource(Logout, '/logout', endpoint='logout')
api.add_resource(MemberVideo, '/member_video', endpoint='member_video')
Conclusion
We learned the difference between authentication and authorization.
Authentication is the process that confirms the user's identity, while authorization determines which level of access the account holder has. Thank you for your time reading my post and I hope this helps you understand the difference between authentication and authorization better.
Top comments (0)