Junior — Middle
What authentication methods have you used in your projects?
sobes.tech AI
Answer from AI
In Python projects, I have used several authentication methods:
- Basic Authentication — a simple way of transmitting login and password in HTTP headers (usually over HTTPS).
- Token-based Authentication — using tokens (e.g., JWT) to verify user identity without constantly transmitting the password.
- OAuth 2.0 — for authorization through third-party services (Google, Facebook, etc.), often used to simplify login.
- Session-based Authentication — a classic approach with sessions stored on the server and a session identifier passed to the client.
Example of using JWT with the PyJWT library:
import jwt
import datetime
SECRET_KEY = 'secret_key'
# Creating a token
payload = {
'user_id': 123,
'exp': datetime.datetime.utcnow() + datetime.timedelta(hours=1)
}
token = jwt.encode(payload, SECRET_KEY, algorithm='HS256')
# Verifying the token
try:
data = jwt.decode(token, SECRET_KEY, algorithms=['HS256'])
user_id = data['user_id']
except jwt.ExpiredSignatureError:
print('Token has expired')
except jwt.InvalidTokenError:
print('Invalid token')