Actual combat: front-end user authentication and authorization

Table of contents

1. Introduction to front-end user authentication and authorization

2. User registration and login

2.1 User Registration

2.2 User login

3. JWT token generation and verification

3.1 Token Generation

3.2 Token Verification

4. Access control and rights management

4.1 User roles

4.2 Access Control

5. Summary


User authentication and authorization are very important functions in modern web applications. User authentication is used to verify the user's identity and ensure that the user is legitimate, while user authorization is used to control the user's access to resources. In this blog, we will demonstrate how to use front-end technology to implement user authentication and authorization, including user registration, login, access control, etc., and demonstrate the implementation of each step through actual code examples.

1. Introduction to front-end user authentication and authorization

User authentication is the process of confirming a user's identity, usually through username and password. Once the user is successfully authenticated, the system will issue a token (Token) as the user's credential. When the user accesses resources that need to be logged in, he only needs to carry the token for verification.

User authorization is the control of user access to resources. Through user authorization, the system can restrict users' access to certain resources, such as allowing only administrator role users to access certain sensitive data.

When implementing user authentication and authorization on the front end, we usually use JSON Web Token (JWT) as the token standard. JWT is a lightweight security token that can be easily passed and verified on the front-end and back-end.

2. User registration and login

2.1 User Registration

First, we need to implement the user registration function. When users register, they need to fill in the user name, password and other information, and submit the registration information to the backend for processing.

 
 
<!-- register.html -->

<!DOCTYPE html>
<html>
<head>
  <title>User Registration</title>
</head>
<body>
  <h1>User Registration</h1>
  <form id="registerForm">
    <div>
      <label for="username">Username:</label>
      <input type="text" id="username" name="username" required>
    </div>
    <div>
      <label for="password">Password:</label>
      <input type="password" id="password" name="password" required>
    </div>
    <button type="submit">Register</button>
  </form>
  <script src="register.js"></script>
</body>
</html>
 
 
// register.js

document.getElementById('registerForm').addEventListener('submit', async (event) => {
  event.preventDefault();

  const form = event.target;
  const formData = new FormData(form);

  const response = await fetch('/api/register', {
    method: 'POST',
    body: formData
  });

  if (response.ok) {
    alert('Registration successful!');
    window.location.href = '/login.html';
  } else {
    const data = await response.json();
    alert('Registration failed: ' + data.error);
  }
});

In the above code, we create a user registration page with username, password input box and registration button. After the user fills in the information, clicking the registration button will initiate a registration request to the backend and process the response returned by the backend.

2.2 User login

After the user registration is complete, next we implement the user login function. When users log in, they need to fill in the user name and password, and submit the login information to the backend for verification.

 
 
<!-- login.html -->

<!DOCTYPE html>
<html>
<head>
  <title>User Login</title>
</head>
<body>
  <h1>User Login</h1>
  <form id="loginForm">
    <div>
      <label for="username">Username:</label>
      <input type="text" id="username" name="username" required>
    </div>
    <div>
      <label for="password">Password:</label>
      <input type="password" id="password" name="password" required>
    </div>
    <button type="submit">Login</button>
  </form>
  <script src="login.js"></script>
</body>
</html>
 
 
// login.js

document.getElementById('loginForm').addEventListener('submit', async (event) => {
  event.preventDefault();

  const form = event.target;
  const formData = new FormData(form);

  const response = await fetch('/api/login', {
    method: 'POST',
    body: formData
  });

  if (response.ok) {
    const data = await response.json();
    localStorage.setItem('token', data.token);
    alert('Login successful!');
    window.location.href = '/dashboard.html';
  } else {
    const data = await response.json();
    alert('Login failed: ' + data.error);
  }
});

In the above code, we create a user login page with username, password input box and login button. After the user fills in the information, clicking the login button will initiate a login request to the backend and process the response returned by the backend. If the login is successful, we save the token returned by the backend in local storage for later use.

3. JWT token generation and verification

After the user logs in successfully, the backend will issue a JWT token to the frontend. The token contains the user's information and expiration time, and is used to verify the user's identity and authority.

3.1 Token Generation

The backend needs to implement the token generation function. In Node.js, we can use jsonwebtokena library to generate JWT tokens.

 
 
// server.js

const express = require('express');
const jwt = require('jsonwebtoken');
const app = express();

const secretKey = 'my-secret-key';

app.use(express.json());

app.post('/api/login', (req, res) => {
  // 获取用户输入的用户名和密码
  const { username, password } = req.body;

  // TODO: 根据用户名和密码验证用户身份

  // 如果验证通过,生成JWT令牌并返回给前端
  const token = jwt.sign({ username }, secretKey, { expiresIn: '1h' });
  res.json({ token });
});

app.listen(3000, () => {
  console.log('Server started on http://localhost:3000');
});

In the above code, we use jwt.signthe method to generate a JWT token, use the username as the payload, and set the expiration time to 1 hour. Then return the token to the frontend.

3.2 Token Verification

The front end needs to implement the verification function of the token. We can use jsonwebtokenlibrary to validate JWT token.

 
 
// dashboard.js

const token = localStorage.getItem('token');

if (token) {
  jwt.verify(token, 'my-secret-key', (err, decoded) => {
    if (err) {
      // 令牌验证失败,跳转到登录页面
      window.location.href = '/login.html';
    } else {
      // 令牌验证成功,显示用户信息和授权内容
      document.getElementById('username').innerText = decoded.username;
      // TODO: 根据用户角色显示不同的功能按钮
    }
  });
} else {
  // 没有令牌,跳转到登录页面
  window.location.href = '/login.html';
}

In the above code, we first get the JWT token from local storage and use jwt.verifythe method to verify the validity of the token. If the token validation fails, meaning the user is not logged in or the login has expired, we redirect the user to the login page. If the token verification is successful, we can display user information on the front end and display different function buttons according to user roles.

4. Access control and rights management

After the user logs in successfully, we can restrict the user's access to resources according to the user's role or authority. In this section, we demonstrate how to implement access control and permission management using the frontend.

4.1 User roles

We first need to define user roles. In practical applications, user roles are usually managed by the backend, and the frontend only needs to perform display and access control based on the user information returned by the backend.

 
 
// server.js

// 假设用户角色由后端管理,这里只是演示
const users = [
  { username: 'admin', password: 'admin123', role: 'admin' },
  { username: 'user', password: 'user123', role: 'user' }
];

app.post('/api/login', (req, res) => {
  const { username, password } = req.body;

  // 根据用户名和密码查找用户
  const user = users.find(u => u.username === username && u.password === password);

  if (user) {
    const token = jwt.sign({ username, role: user.role }, secretKey, { expiresIn: '1h' });
    res.json({ token });
  } else {
    res.status(401).json({ error: 'Invalid credentials' });
  }
});

In the above code, we defined two users by hard coding, one of which is an administrator (admin) and the other is a normal user (user). In practical applications, user information should be stored in a database or other persistent storage and managed by the backend.

4.2 Access Control

On the front end, we can restrict user access to certain features based on user roles. Below is a simple example.

 
 
<!-- dashboard.html -->

<!DOCTYPE html>
<html>
<head>
  <title>User Dashboard</title>
</head>
<body>
  <h1>Welcome, <span id="username"></span>!</h1>
  <div id="actions">
    <button id="viewDataBtn">View Data</button>
    <button id="editDataBtn">Edit Data</button>
    <button id="adminActionBtn">Admin Action</button>
  </div>
  <script src="dashboard.js"></script>
</body>
</html>
 
 
// dashboard.js

const token = localStorage.getItem('token');

if (token) {
  jwt.verify(token, 'my-secret-key', (err, decoded) => {
    if (err) {
      window.location.href = '/login.html';
    } else {
      document.getElementById('username').innerText = decoded.username;

      const actionsDiv = document.getElementById('actions');
      if (decoded.role === 'admin') {
        // 如果是管理员,显示管理员功能按钮
        actionsDiv.style.display = 'block';
      } else {
        // 否则,隐藏管理员功能按钮
        actionsDiv.style.display = 'none';
      }
    }
  });
} else {
  window.location.href = '/login.html';
}

In the above code, we show or hide different function buttons according to the user role after the user logs in successfully. If the user is an administrator, the "Admin Action" button will be shown, otherwise it will be hidden.

Through access control, we can flexibly control the user's access to resources and improve application security and user experience.

5. Summary

This blog has practiced the front-end process of user authentication and authorization, including user registration, login, JWT token generation and verification, access control and authority management, etc. Using real code examples, we demonstrate the implementation of each step and show how to restrict user access to resources based on user roles.

User authentication and authorization are indispensable functions in modern web applications, they can protect user privacy and provide better user experience. By studying this blog, I hope you have a deeper understanding of the front-end implementation of user authentication and authorization, and can apply it in actual projects. Thanks for reading!

Guess you like

Origin blog.csdn.net/m0_68036862/article/details/132041222