Junior — Middle
Какая роль JWT-токенов в обеспечении безопасности и авторизации приложений?
sobes.tech AI
Answer from AI
JWT (JSON Web Token) is a compact, URL-safe way to transmit information between parties as a JSON object. In application security and authorization, JWT is used to verify user identity and transmit access rights.
Main roles of JWT:
- Authentication: after a user successfully logs in, the server creates a JWT with user information and permissions.
- Authorization: the client sends the JWT with each request, the server verifies the token and grants access to resources based on the data in it.
JWT consists of three parts: header, payload, and signature. The signature ensures that the token has not been altered.
Example of using JWT in Python with the PyJWT library:
import jwt
import datetime
secret_key = 'secret'
# Creating a token
payload = {
'user_id': 123,
'exp': datetime.datetime.utcnow() + datetime.timedelta(hours=1) # expiration time
}
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')
Thus, JWT provides a secure and convenient way to manage sessions and access rights in web applications.