Authentication and Authorization Explained
Key Concepts
- Authentication
- Authorization
- Sessions
- Tokens
- Role-Based Access Control (RBAC)
- OAuth
1. Authentication
Authentication is the process of verifying the identity of a user. It ensures that the user is who they claim to be. Common methods of authentication include username/password, biometric verification, and multi-factor authentication (MFA).
from flask import Flask, request, session app = Flask(__name__) app.secret_key = 'secret' @app.route('/login', methods=['POST']) def login(): username = request.form['username'] password = request.form['password'] if username == 'admin' and password == 'password': session['username'] = username return 'Logged in successfully' return 'Invalid credentials'
2. Authorization
Authorization is the process of determining what actions a user is allowed to perform after they have been authenticated. It ensures that authenticated users have the appropriate permissions to access resources or perform certain operations.
from flask import Flask, session, redirect, url_for app = Flask(__name__) @app.route('/admin') def admin(): if 'username' in session and session['username'] == 'admin': return 'Welcome to the admin page' return redirect(url_for('login'))
3. Sessions
Sessions are used to maintain state between requests. In web applications, sessions allow the server to recognize the user across multiple requests. Flask uses cookies to store session data, which is encrypted to prevent tampering.
from flask import Flask, session app = Flask(__name__) app.secret_key = 'secret' @app.route('/') def index(): if 'username' in session: return f'Logged in as {session["username"]}' return 'You are not logged in'
4. Tokens
Tokens are used as an alternative to sessions for authentication and authorization. JSON Web Tokens (JWT) are a common type of token used in web applications. Tokens are issued by the server and sent to the client, which then includes the token in subsequent requests.
import jwt from flask import Flask, request app = Flask(__name__) app.config['SECRET_KEY'] = 'secret' @app.route('/login', methods=['POST']) def login(): username = request.form['username'] password = request.form['password'] if username == 'admin' and password == 'password': token = jwt.encode({'username': username}, app.config['SECRET_KEY']) return token return 'Invalid credentials'
5. Role-Based Access Control (RBAC)
Role-Based Access Control (RBAC) is a method of regulating access to resources based on the roles of individual users within an organization. Roles are defined based on job responsibilities, and permissions are assigned to these roles rather than to individual users.
from flask import Flask, session app = Flask(__name__) app.secret_key = 'secret' def check_role(role): def decorator(f): def wrapper(*args, **kwargs): if 'role' in session and session['role'] == role: return f(*args, **kwargs) return 'Access denied' return wrapper return decorator @app.route('/admin') @check_role('admin') def admin(): return 'Welcome to the admin page'
6. OAuth
OAuth is an open standard for access delegation, commonly used as a way for users to grant websites or applications access to their information on other websites without giving them the passwords. OAuth allows third-party applications to obtain limited access to a user's resources.
from flask import Flask, redirect, url_for from flask_oauthlib.client import OAuth app = Flask(__name__) app.config['GOOGLE_ID'] = 'your-google-id' app.config['GOOGLE_SECRET'] = 'your-google-secret' oauth = OAuth(app) google = oauth.remote_app( 'google', consumer_key=app.config.get('GOOGLE_ID'), consumer_secret=app.config.get('GOOGLE_SECRET'), request_token_params={ 'scope': 'email' }, base_url='https://www.googleapis.com/oauth2/v1/', request_token_url=None, access_token_method='POST', access_token_url='https://accounts.google.com/o/oauth2/token', authorize_url='https://accounts.google.com/o/oauth2/auth', ) @app.route('/login') def login(): return google.authorize(callback=url_for('authorized', _external=True)) @app.route('/authorized') def authorized(): resp = google.authorized_response() if resp is None: return 'Access denied: reason={} error={}'.format( request.args['error_reason'], request.args['error_description'] ) session['google_token'] = (resp['access_token'], '') return 'Logged in successfully'