Authentication and JWT
For starters, what is a JWT?
JSON Web Token (JWT) is an open standard (RFC 7519) that defines a compact and self-contained way for securely transmitting information between parties as a JSON object. This information can be verified and trusted because it is digitally signed. ~ JWT.io.
So... in a pratical way to explain, JWT can be used for multiple purposes as Information Exchange and also as a Authorization scenario!
Once the user is logged in, each subsequent request will include the JWT, allowing the user to access routes, services, and resources that are permitted with that token. ~ JWT
Token Required Barrier
The token_required decorator function ensures that a valid JSON Web Token is present in the request headers before allowing access to the decorated route. It retrieves the token from the request headers and decodes it using a key.
Our secret key was generate using the follow command (generating a random 32-byte hexadecimal string)
node -e "console.log(require('crypto').randomBytes(32).toString('hex'))"- If the token is missing, expired, or invalid, it returns an appropriate error message and a 401 status code.
- It also checks if the user associated with the token exists in the database.
- If the user is not found, it returns a "User not found" message.
- If the token is valid and the user exists, it calls the decorated function, passing the current user.
Token Authentication is required in some of: DELETE, PUT and POST methods.
def token_required(f):
@wraps(f)
def decorated(*args, **kwargs):
token = request.headers.get('token')
if not token:
return jsonify({'code' : '400', 'status': 'Bad Request', 'message': 'Token header is required'}), 400
try:
data = jwt.decode(token, app.config['SECRET_KEY'], algorithms=["HS256"])
except jwt.ExpiredSignatureError:
return jsonify({'code' : '401', 'status': 'Unauthorized', 'message': 'Token expired'}), 401
except jwt.InvalidTokenError:
return jsonify({'code' : '401', 'status': 'Unauthorized', 'message': 'Invalid Token'}), 401
return f(*args, **kwargs)
return decoratedHeaders (token validation) - Practical Example
The client sends a Header with the value ("token") and key (secret token previous generated during a sucessful Administrator login), which the server processes to allow certain actions.
token = request.headers.get('token')
More information about token generation can be found in login endpoint.