Sobes.tech
Junior — Middle

Have you had experience working with authentication systems for server applications?

sobes.tech AI

Answer from AI

Yes, I have experience working with authentication systems for server applications in Python. I usually used JWT (JSON Web Tokens) for user authentication in REST API. Here's an example of basic authentication using Flask and PyJWT:

from flask import Flask, request, jsonify
import jwt
import datetime

app = Flask(__name__)
app.config['SECRET_KEY'] = 'your_secret_key'

users = {'user1': 'password1'}

@app.route('/login', methods=['POST'])
def login():
    auth = request.json
    username = auth.get('username')
    password = auth.get('password')
    if username in users and users[username] == password:
        token = jwt.encode({'user': username, 'exp': datetime.datetime.utcnow() + datetime.timedelta(hours=1)}, app.config['SECRET_KEY'])
        return jsonify({'token': token})
    return jsonify({'message': 'Invalid credentials'}), 401

@app.route('/protected')
def protected():
    token = request.headers.get('Authorization')
    if not token:
        return jsonify({'message': 'Token is missing'}), 401
    try:
        data = jwt.decode(token, app.config['SECRET_KEY'], algorithms=['HS256'])
        return jsonify({'message': f'Welcome {data["user"]}'})
    except jwt.ExpiredSignatureError:
        return jsonify({'message': 'Token expired'}), 401
    except jwt.InvalidTokenError:
        return jsonify({'message': 'Invalid token'}), 401

if __name__ == '__main__':
    app.run()

I am also familiar with using OAuth2 and the django-rest-framework library for authentication in Django projects.

Have you had experience working with authentication… - sobes.tech