JWT(JSON Web Token)是一种开放标准(RFC 7519),用于在网络应用环境间安全地将信息作为JSON对象传输。在后端Spring Boot应用中,JWT常用于用户身份验证和信息传递。
以下是一个简单的Spring Boot应用中使用JWT进行身份验证的示例:
在pom.xml
中添加以下依赖:
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
<version>0.9.1</version>
</dependency>
创建一个JwtUtil
类用于生成和验证JWT:
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.security.core.userdetails.UserDetails;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
public class JwtUtil {
private static final String SECRET_KEY = "yourSecretKey";
public String generateToken(UserDetails userDetails) {
Map<String, Object> claims = new HashMap<>();
return createToken(claims, userDetails.getUsername());
}
private String createToken(Map<String, Object> claims, String subject) {
return Jwts.builder()
.setClaims(claims)
.setSubject(subject)
.setIssuedAt(new Date(System.currentTimeMillis()))
.setExpiration(new Date(System.currentTimeMillis() + 1000 * 60 * 60 * 10)) // 10小时过期
.signWith(SignatureAlgorithm.HS256, SECRET_KEY)
.compact();
}
public Boolean validateToken(String token, UserDetails userDetails) {
final String username = extractUsername(token);
return (username.equals(userDetails.getUsername()) && !isTokenExpired(token));
}
private String extractUsername(String token) {
return Jwts.parser().setSigningKey(SECRET_KEY).parseClaimsJws(token).getBody().getSubject();
}
private Boolean isTokenExpired(String token) {
return Jwts.parser().setSigningKey(SECRET => 'yourSecretKey').parseClaimsJws(token).getBody().getExpiration().before(new Date());
}
}
在控制器中使用JwtUtil
进行身份验证:
@RestController
@RequestMapping("/api")
public class UserController {
@Autowired
private JwtUtil jwtUtil;
@Autowired
private AuthenticationManager authenticationManager;
@PostMapping("/login")
public ResponseEntity<?> login(@RequestBody AuthenticationRequest authenticationRequest) throws Exception {
Authentication authentication = authenticationManager.authenticate(
new UsernamePasswordAuthenticationToken(authenticationRequest.getUsername(), authenticationRequest.getPassword())
);
SecurityContextHolder.getContext().setAuthentication(authentication);
String jwt = jwtUtil.generateToken((UserDetails) authentication.getPrincipal());
return ResponseEntity.ok(new AuthenticationResponse(jwt));
}
@GetMapping("/user")
public ResponseEntity<?> getCurrentUser(@RequestHeader("Authorization") String token) {
if (token != null && token.startsWith("Bearer ")) {
String jwtToken = token.substring(7);
if (jwtUtil.validateToken(jwtToken, getCurrentAuthenticatedUser())) {
String username = jwtUtil.extractUsername(jwtToken);
// 返回用户信息
return ResponseEntity.ok(new UserResponse(username));
}
}
return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build();
}
private UserDetails getCurrentAuthenticatedUser() {
// 获取当前认证的用户详情
}
}
领取专属 10元无门槛券
手把手带您无忧上云