User authentication is a crucial feature in any application that handles sensitive data, such as a payment app. It ensures that only authorized users can access the app and perform actions.
In our payment app, we will implement user authentication using JSON Web Tokens (JWT). JWT is an open standard for securely transmitting information between parties as a JSON object. It consists of three parts: a header, a payload, and a signature.
Here is an example of how we can use JWT for user authentication in our app:
1const express = require('express');
2const jwt = require('jsonwebtoken');
3
4const app = express();
5
6// Generate a JWT token for a given user
7function generateToken(user) {
8 const payload = {
9 id: user.id,
10 username: user.username
11 };
12
13 const options = {
14 expiresIn: '1h'
15 };
16
17 return jwt.sign(payload, process.env.JWT_SECRET, options);
18}
19
20// Authenticate user with JWT token
21function authenticateToken(req, res, next) {
22 const token = req.headers.authorization;
23
24 if (!token) {
25 return res.status(401).json({ message: 'Authorization token not provided' });
26 }
27
28 jwt.verify(token, process.env.JWT_SECRET, (error, user) => {
29 if (error) {
30 return res.status(403).json({ message: 'Invalid token' });
31 }
32
33 req.user = user;
34 next();
35 });
36}
37
38// Register a new user
39app.post('/register', (req, res) => {
40 // ... registration logic
41
42 const user = {
43 id: 1,
44 username: 'john.doe'
45 };
46
47 const token = generateToken(user);
48
49 res.json({ token });
50});
51
52// Protected route
53app.get('/protected', authenticateToken, (req, res) => {
54 res.json({ message: 'Protected route' });
55});
56
57app.listen(3000, () => {
58 console.log('Server started on port 3000');
59});
In this example, we have an Express.js server that exposes two endpoints: /register
for user registration and /protected
which is a protected route that requires authentication.
The generateToken
function generates a JWT token for a given user. It includes the user's ID and username in the payload and signs it using a secret key. The token is then returned to the client.
The authenticateToken
function is a middleware that checks for the presence of a valid JWT token in the request's Authorization
header. If the token is valid, the user object is added to the request object and the next middleware is called. If the token is invalid or not provided, an error response is sent.
When a user registers, a token is generated and returned in the response. This token can be used to authenticate subsequent requests to the protected route by including it in the Authorization
header.
Feel free to customize this example to fit your specific authentication requirements. Next, we will learn about integrating payment gateways in our app.