introduction
In contemporary web application and API development, user authentication and authorization are undoubtedly extremely critical links. As a lightweight authentication mechanism, JSON Web Token (JWT) has been widely used in many front-end and back-end separation projects with its significant advantages such as simplicity, scalability and cross-domain support. This article will comprehensively and in-depth discussion of the principles and workflow of JWT, and combine Java code examples to show how to use JWT for authentication in a simple login system.
1. JWT Overview
1. What is JWT
JWT is an open standard for safe delivery of claims between network applications (RFC 7519). It is usually composed of three parts: the header, the payload and the signature, and.
Separate, form similarstring.
2. The structure of JWT
Header: Usually contains two parts of information, the type of the token (usually JWT) and the signature algorithm used, such as HMAC SHA256 or RSA. It is a JSON object that forms the first part of the JWT after Base64Url encoding.
{ "alg": "HS256", "typ": "JWT" }
Payload: Contains claims (claims), statements are statements about entities (usually users) and other data. There are three types of declarations: registration statements, public statements and private statements. Registration statements are predefined statements such asiss
(Issuer),sub
(theme),aud
(Audience), etc. The load is also a JSON object, which is encoded by Base64Url to form the second part of the JWT.
{ "sub": "1234567890", "name": "John Doe", "iat": 1516239022 }
Signature: In order to create a signature part, the encoded header, the encoded payload, a secret key and the signature algorithm specified in the header are required. The signature is used to verify that the message has not been changed during delivery, and in the case of using the private key signature, the identity of the sender of the JWT can also be verified.
3. Advantages of JWT
- Stateless: JWT is stateless, and the server does not need to store session information, so it can be easily extended to multiple servers or microservice architectures.
- Cross-domain support: Since JWT can be passed through HTTP headers or URL parameters, it can be used safely between different domains.
- Scalability: Custom statements can be added to the load to meet different business needs.
2. JWT workflow
1. User login
The user sends a login request to the server, providing the user name and password.
2. Server Verification
The server verifies the user's user name and password. If the verification is successful, the server generates a JWT based on the user information.
3. Return to JWT
The server returns the generated JWT to the client.
4. Client storage
After the client receives the JWT, it stores it locally, usually in the browser.localStorage
orsessionStorage
middle.
5. Follow-up request
In subsequent requests, the client includes the JWT at the request header (usuallyAuthorization
send to the server in the header.
6. Server Verification JWT
After the server receives the request, verify the signature and validity period of the JWT. If the verification is successful, the server considers the user to be legitimate and processes the request.
3. Code example: Use JWT to implement login authentication
1. Project environment
We use Java and Spring Boot frameworks to implement a simple login system and uselibrary to handle JWT.
2. Introduce dependencies
existAdd the following dependencies to:
<dependencies> <dependency> <groupId></groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId></groupId> <artifactId>jjwt-api</artifactId> <version>0.11.5</version> </dependency> <dependency> <groupId></groupId> <artifactId>jjwt-impl</artifactId> <version>0.11.5</version> <scope>runtime</scope> </dependency> <dependency> <groupId></groupId> <artifactId>jjwt-jackson</artifactId> <version>0.11.5</version> <scope>runtime</scope> </dependency> </dependencies>
3. Code implementation
import ; import ; import ; import .*; import ; import ; import ; @RestController @RequestMapping("/api") public class AuthController { // Key, used for signing and verifying JWT private static final String SECRET_KEY = "your_secret_key"; // Validity period, set to 30 minutes private static final long EXPIRATION_TIME = 30 * 60 * 1000; // Simulate user database private static final Map<String, String> users = new HashMap<>(); static { ("user1", "password1"); ("user2", "password2"); } // Generate JWT private String generateToken(String username) { Date now = new Date(); Date expiration = new Date(() + EXPIRATION_TIME); return () .setSubject(username) .setIssuedAt(now) .setExpiration(expiration) .signWith(SignatureAlgorithm.HS256, SECRET_KEY) .compact(); } // Verify JWT private Claims validateToken(String token) { try { return () .setSigningKey(SECRET_KEY) .parseClaimsJws(token) .getBody(); } catch (Exception e) { return null; } } // Login interface @PostMapping("/login") public String login(@RequestBody Map<String, String> credentials) { String username = ("username"); String password = ("password"); if ((username) && (username).equals(password)) { return generateToken(username); } return "Invalid credentials"; } // Protected interface @GetMapping("/protected") public String protectedResource(@RequestHeader("Authorization") String token) { if (token == null ||!("Bearer ")) { return "Token is missing"; } token = (7); Claims claims = validateToken(token); if (claims != null) { return "Welcome, " + (); } return "Invalid token"; } }
4. Code explanation
-
generateToken
Method: Generate a JWT based on the user's user name, including the user name, issuance time and validity period. -
validateToken
Method: Verify the signature and validity period of JWT, and if the verification is successful, return the load information. -
/login
Interface: Process the user's login request, verify the user name and password, and if the verification is successful, generate and return the JWT. -
/protected
Interface: A protected interface that requires a valid JWT to be accessed.
5. Test
You can use Postman or other tools to test the interface:
- Login Request:
Send a POST request tohttp://localhost:8080/api/login
, the request body is{"username": "user1", "password": "password1"}
。
- Protected request:
Send a GET request tohttp://localhost:8080/api/protected
and add in the request headerAuthorization: Bearer <your_token>
。
4. JWT safety precautions
- Key security: The key is the key to JWT signature and verification and must be kept properly to avoid leakage.
- Validity period setting: Rationally set the validity period of JWT to avoid security risks caused by excessive validity period.
- Prevent replay attacks: You can use a one-time token or adding a timestamp to prevent replay attacks.
5. Summary
JWT is a simple and powerful authentication mechanism suitable for various front-end and back-end separate projects. Through this article, you should have a deeper understanding of the principles, workflow and usage of JWT. In actual development, pay attention to JWT security issues and ensure the security of the system. Hope this article helps you successfully apply JWT to log in and authenticate in your project.
This is the end of this article about Java JWT's detailed explanation. For more related Java JWT content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!