Junior — Middle
What tools or approaches would you use to implement an authentication and authorization system?
sobes.tech AI
Answer from AI
To implement authentication and authorization systems in Python applications, you can use the following approaches and tools:
- Libraries and frameworks: for example, Flask-Login or Django Authentication for web applications.
- JWT (JSON Web Tokens): for stateless authentication, where the token is transmitted to the client and verified on the server.
- OAuth 2.0: for authorization through third-party services (Google, Facebook, etc.).
- Password storage: always use password hashing with bcrypt or Argon2.
Example with Flask-Login:
from flask import Flask, request, redirect, url_for
from flask_login import LoginManager, UserMixin, login_user, login_required, logout_user
app = Flask(__name__)
app.secret_key = 'secret'
login_manager = LoginManager()
login_manager.init_app(app)
class User(UserMixin):
def __init__(self, id):
self.id = id
@login_manager.user_loader
def load_user(user_id):
return User(user_id)
@app.route('/login', methods=['POST'])
def login():
username = request.form['username']
password = request.form['password']
# User and password verification
user = User(username)
login_user(user)
return redirect(url_for('protected'))
@app.route('/protected')
@login_required
def protected():
return 'Access granted'
@app.route('/logout')
def logout():
logout_user()
return 'Logged out'
This approach provides basic authentication and user authorization.