Build a Complete QR Code Login System with Spring Boot, WebSocket, and Redis
This guide walks you through creating a full-featured QR code login demo using Spring Boot, WebSocket, and Redis, covering backend services, frontend pages, project structure, code snippets, deployment steps, and security best practices for a seamless login experience.
QR Code Login Overview
In the mobile internet era, QR code login has become an essential authentication method for web applications. This article demonstrates a complete QR code login system built with Spring Boot.
1. QR Code Login Principle
The basic flow includes generating a unique QR code on the web side, scanning it with a mobile app, confirming the login, and notifying the web client via WebSocket.
2. Project Structure
qrcode-login/
├── src/main/java/com/example/qrcodelogin/
│ ├── QrcodeLoginApplication.java
│ ├── config/
│ │ ├── RedisConfig.java
│ │ └── WebSocketConfig.java
│ ├── controller/
│ │ ├── LoginController.java
│ │ └── QRCodeController.java
│ ├── model/
│ │ ├── QRCodeStatus.java
│ │ └── UserInfo.java
│ ├── service/
│ │ ├── QRCodeService.java
│ │ └── UserService.java
│ └── util/
│ ├── JsonUtil.java
│ └── QRCodeUtil.java
├── src/main/resources/
│ ├── application.yaml
│ └── static/
│ ├── css/
│ │ ├── login.css
│ │ └── mobile.css
│ ├── index.html
│ └── mobile.html
└── pom.xml3. Backend Implementation
3.1 Maven Dependencies
<?xml version="1.0" encoding="UTF-8"?>
<project ...>
<dependencies>
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency>
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-websocket</artifactId></dependency>
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-redis</artifactId></dependency>
<dependency><groupId>com.google.zxing</groupId><artifactId>core</artifactId><version>3.5.1</version></dependency>
<dependency><groupId>com.google.zxing</groupId><artifactId>javase</artifactId><version>3.5.1</version></dependency>
<dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><optional>true</optional></dependency>
</dependencies>
</project>3.2 Configuration Files
spring:
redis:
host: localhost
port: 6379
database: 0
timeout: 5000ms
lettuce:
pool:
max-active: 20
max-idle: 10
min-idle: 5
qrcode:
expire:
seconds: 300
width: 100
height: 1003.3 Core Classes
RedisConfig configures a RedisTemplate with JSON serialization. WebSocketConfig registers a handler at /ws/qrcode. QRCodeService provides methods to generate QR codes, store status in Redis, update status, confirm or cancel login, and periodically clean expired codes. UserService simulates a user database and token generation.
3.4 Controllers
QRCodeController exposes REST endpoints for generating QR codes, retrieving QR code images, scanning, confirming, cancelling, and checking status. LoginController validates tokens and returns test user data.
4. Frontend Implementation
4.1 Web Page (index.html)
The page displays a QR code, connects to the WebSocket, updates UI based on status changes, and shows user information after successful login.
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<title>QR Code Login Demo</title>
<link rel="stylesheet" href="css/login.css">
</head>
<body>
... (HTML structure with <code>div</code> elements for QR code, tips, login success) ...
<script>
// JavaScript to generate QR code, handle WebSocket messages, and manage UI
</script>
</body>
</html>4.2 Mobile Simulation Page (mobile.html)
A simple page that allows manual entry of the QR code ID, displays a list of test users, and sends scan/confirm/cancel requests to the backend.
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<title>Mobile QR Code Login</title>
<link rel="stylesheet" href="css/mobile.css">
</head>
<body>
... (HTML structure with sections for scanning, user selection, confirmation, and success) ...
<script>
// JavaScript to interact with backend APIs and update UI
</script>
</body>
</html>4.3 CSS Styles
Separate CSS files ( login.css and mobile.css) define responsive layouts, colors, and component styling for both web and mobile pages.
5. Running the Project
Start a Redis instance (e.g., docker run --name redis -p 6379:6379 -d redis).
Build the Spring Boot application with mvn clean package and run the jar.
Open http://localhost:8080 for the web page and http://localhost:8080/mobile.html for the mobile simulation.
6. QR Code Login Flow Details
6.1 Generation Phase
The web client requests a QR code ID, the server creates a record with status WAITING , stores it in Redis, generates a QR image, and returns it. The client opens a WebSocket connection and subscribes to the QR code ID.
6.2 Scan & Confirmation Phase
The mobile client scans the QR code, sends a SCAN request, the server updates status to SCANNED and pushes the update via WebSocket. The user selects an account, confirms login, and the server changes status to CONFIRMED with user info, notifying the web client.
6.3 Completion Phase
The web client receives the CONFIRMED message, displays the user’s avatar and name, and completes the login process.
7. Security Considerations
7.1 QR Code Security
Short expiration (e.g., 300 seconds).
One‑time use – QR code becomes invalid after successful login.
Strict state transitions and UUID randomness to prevent enumeration attacks.
7.2 Communication Security
Use HTTPS in production.
Secure WebSocket connections (wss) and consider authentication.
Implement replay‑attack protection with timestamps/nonces.
Enable CSRF protection for state‑changing endpoints.
7.3 User Data Protection
Encrypt sensitive data stored in Redis.
Robust token generation, validation, and expiration.
Send login notifications to users.
Monitor abnormal login patterns (e.g., rapid repeated scans).
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Su San Talks Tech
Su San, former staff at several leading tech companies, is a top creator on Juejin and a premium creator on CSDN, and runs the free coding practice site www.susan.net.cn.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
