Table of contents
In today's linked digital environment, securing safe access to apps, services, and resources is critical. This is where the notion of tokens comes into play, playing a critical part in authentication and authorization operations. Tokens are digital keys or credentials that indicate the authorization to access specified resources, and they are critical to improving security and optimizing user experiences in online and mobile apps.
What are Tokens?
Tokens are digital keys used in authentication and authorization processes, enhancing security and streamlining user experiences in web and mobile applications by proving identity and permissions.
Authentication
Authorization
Authentication
Tokens are used to validate a user's identity. When you log in to a website or app, you normally enter a username and password. When you are authorized, the system creates a token that acts as confirmation of your identity.
Authorization
Tokens also contain information about the permissions or access privileges associated with a certain user. They decide the activities or resources the user has access to.
How Tokens Work
Step 1: The server checks your credentials (username and password) when you log in to a web service. The server generates a token if they are correct.
illustrates how a server may validate user credentials and produce a token when a user signs in using the Flask web framework:
from flask import Flask, request, jsonify
import jwt # You'll need to install the PyJWT library as well
app = Flask(__name__)
# Secret key for encoding and decoding JWT tokens
SECRET_KEY = 'your-secret-key'
# Dummy database to store user information (username and password)
users_db = {
'user1': 'password1',
'user2': 'password2',
}
# Route for user login
@app.route('/login', methods=['POST'])
def login():
data = request.get_json()
username = data.get('username')
password = data.get('password')
# Check if the provided credentials are valid
if username in users_db and users_db[username] == password:
# Generate a JWT token
token = jwt.encode({'username': username}, SECRET_KEY, algorithm='HS256')
return jsonify({'token': token, 'message': 'Login successful'})
return jsonify({'message': 'Invalid credentials'}), 401
if __name__ == '__main__':
app.run(debug=True)
Step 2: This token is then delivered to your device (often as a cookie or in the response body) and kept locally. It can also be put in the response headers.
Token-based authentication involves delivering a server-generated token to the client's device, which can be stored locally using methods like cookies, response body, or headers, using Python and Flask.
Sending Token in a Cookie
In this strategy, the server includes a cookie with the token in the response, which the client's browser keeps locally.
from flask import Flask, request, jsonify, make_response
app = Flask(__name__)
# ...
@app.route('/login', methods=['POST'])
def login():
data = request.get_json()
username = data.get('username')
password = data.get('password')
if username in users_db and users_db[username] == password:
token = jwt.encode({'username': username}, SECRET_KEY, algorithm='HS256')
response = make_response(jsonify({'message': 'Login successful'}))
response.set_cookie('token', token) # Set the token as a cookie
return response
return jsonify({'message': 'Invalid credentials'}), 401
Sending Token in the Response Body
The token is included in the response body by the server, which the client can extract and keep locally.
@app.route('/login', methods=['POST'])
def login():
data = request.get_json()
username = data.get('username')
password = data.get('password')
if username in users_db and users_db[username] == password:
token = jwt.encode({'username': username}, SECRET_KEY, algorithm='HS256')
return jsonify({'token': token, 'message': 'Login successful'})
return jsonify({'message': 'Invalid credentials'}), 401
Sending Token in the Response Headers
The token appears in the response headers, notably the Authorization header.
@app.route('/login', methods=['POST'])
def login():
data = request.get_json()
username = data.get('username')
password = data.get('password')
if username in users_db and users_db[username] == password:
token = jwt.encode({'username': username}, SECRET_KEY, algorithm='HS256')
response = jsonify({'message': 'Login successful'})
response.headers['Authorization'] = 'Bearer ' + token # Set token in the Authorization header
return response
return jsonify({'message': 'Invalid credentials'}), 401
Step 3: This token is then given to your device and stored locally (typically as a cookie or in the response body). It is also possible to include it in the response headers.
Storing the Token as a Cookie
Including the Token in the Response Body
Including the Token in the Response Headers
Storing the Token as a Cookie
The response to the client, the server delivers the token as an HTTP cookie. The cookie is automatically stored by the client's browser and is transmitted with each subsequent HTTP request to the server.
# Flask example
from flask import Flask, request, jsonify, make_response
app = Flask(__name__)
@app.route('/login', methods=['POST'])
def login():
data = request.get_json()
username = data.get('username')
password = data.get('password')
if username in users_db and users_db[username] == password:
token = jwt.encode({'username': username}, SECRET_KEY, algorithm='HS256')
response = make_response(jsonify({'message': 'Login successful'}))
response.set_cookie('token', token) # Set the token as a cookie
return response
return jsonify({'message': 'Invalid credentials'}), 401
Including the Token in the Response Body
The token is immediately included in the response body as a JSON object by the server. The token can be extracted from the response body and saved locally for future usage by the client.
# Flask example
@app.route('/login', methods=['POST'])
def login():
data = request.get_json()
username = data.get('username')
password = data.get('password')
if username in users_db and users_db[username] == password:
token = jwt.encode({'username': username}, SECRET_KEY, algorithm='HS256')
return jsonify({'token': token, 'message': 'Login successful'})
return jsonify({'message': 'Invalid credentials'}), 401
Sending Token in the Response Headers
The token is provided in the response headers, notably the Authorization header, in this technique. The token can be obtained from the response headers and stored locally by the client.
# Flask example
@app.route('/login', methods=['POST'])
def login():
data = request.get_json()
username = data.get('username')
password = data.get('password')
if username in users_db and users_db[username] == password:
token = jwt.encode({'username': username}, SECRET_KEY, algorithm='HS256')
response = jsonify({'message': 'Login successful'})
response.headers['Authorization'] = 'Bearer ' + token # Set token in the Authorization header
return response
return jsonify({'message': 'Invalid credentials'}), 401
Types of Tokens
Let's look at three different forms of tokens: access tokens, refresh tokens, and session tokens.
Access Tokens
Purpose: The primary tokens used to access protected resources in an application are access tokens. They indicate the user's identification as well as their authorization to execute specified activities or access specific data.
How They Work:
The authentication server generates an access token once a user successfully logs in or authorizes an application.
This token provides user information such as identification, rights, and an expiration time.
The access token is then provided to the server with each request, allowing the server to rapidly check the user's identity and access credentials.
Expiry: To improve security, access tokens normally have a somewhat short lifespan. When they expire, the client must re-authenticate with the server to receive a new one.
Example: When you join a social media app, the server sends you an access token that allows you to read your feed, share updates, and engage with other users. The token will expire after a certain length of time or when you log out.
Refresh Tokens
Purpose: Refresh tokens are used to receive new access tokens without forcing the user to log in again. They are especially beneficial when access tokens have short lifespans since they extend the user's session.
How They Work:
When an access token expires, the client can use a refresh token to request a new one.
Refresh tokens are normally long-lived and securely saved on the client's device.
If the refresh token is genuine, the server will issue a new access token.
Expiry: Refresh tokens have a longer lifetime than access tokens. They should be stored safely and used sparingly.
Example: Mobile banking apps provide users with an access token and a refresh token, which expire quickly, allowing continuous account access without frequent logins. The refresh token remains valid for longer.
Session Tokens
Purpose: Session tokens are used to keep a user's session after they log in. In online applications, they are frequently used to identify and authenticate users across several requests.
How They Work:
When a user signs in, a session token is produced and connected with their server session.
The session token is frequently saved in the user's browser as a cookie.
The server validates the session token with each subsequent request to identify and authenticate the user.
Expiry: Session tokens generally have a lifespan of as long as the user's session is active or until they log out. When the user logs out or after a period of inactivity, they are frequently invalidated.
Example: A session token is created during a visit to an e-commerce website, allowing users to view and purchase items without logging out, and being invalidated when the browser is closed.
Summary
Thank you for reading our blog. Our top priority is your success and satisfaction. We are ready to assist with any questions or additional help.
Warm regards,
Content Editor