java实现用户登录
时间: 2023-11-29 15:04:00 浏览: 72
Java可以通过使用Token和JWT来实现用户登录功能。Token是一种身份验证机制,它是由服务器生成的一串字符串,用于标识用户身份。JWT是一种基于Token的认证机制,它将用户信息加密在Token中,以确保安全性。下面是Java基于JWT实现登录功能的步骤:
1. 引入pom依赖,例如:io.jsonwebtoken:jjwt:0.9.1
2. 编写JWT工具类,例如:
```
public class JwtUtils {
private static final String SECRET_KEY = "your_secret_key";
private static final long EXPIRATION_TIME = 86400000L; // 24 hours
public static String generateToken(User user) {
Date now = new Date();
Date expiration = new Date(now.getTime() + EXPIRATION_TIME);
return Jwts.builder()
.setSubject(user.getUsername())
.setIssuedAt(now)
.setExpiration(expiration)
.signWith(SignatureAlgorithm.HS512, SECRET_KEY)
.compact();
}
public static boolean validateToken(String token) {
try {
Jwts.parser().setSigningKey(SECRET_KEY).parseClaimsJws(token);
return true;
} catch (JwtException | IllegalArgumentException e) {
return false;
}
}
public static String getUsernameFromToken(String token) {
Claims claims = Jwts.parser().setSigningKey(SECRET_KEY).parseClaimsJws(token).getBody();
return claims.getSubject();
}
}
```
3. 编写登录接口,例如:
```
@PostMapping("/login")
public ResponseEntity<?> login(@RequestBody LoginRequest loginRequest) {
Authentication authentication = authenticationManager.authenticate(
new UsernamePasswordAuthenticationToken(loginRequest.getUsername(), loginRequest.getPassword()));
SecurityContextHolder.getContext().setAuthentication(authentication);
String token = JwtUtils.generateToken((User) authentication.getPrincipal());
return ResponseEntity.ok(new JwtResponse(token));
}
```
4. Java后端校验Token,例如:
```
@GetMapping("/user")
public ResponseEntity<?> getUser(@RequestHeader("Authorization") String authorizationHeader) {
String token = authorizationHeader.substring(7);
if (JwtUtils.validateToken(token)) {
String username = JwtUtils.getUsernameFromToken(token);
User user = userService.findByUsername(username);
return ResponseEntity.ok(user);
} else {
return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build();
}
}
```
5. Vue登录页面中的存储Token方法,例如:
```
login() {
axios.post('/login', {
username: this.username,
password: this.password
}).then(response => {
localStorage.setItem('token', response.data.token);
this.$router.push('/home');
}).catch(error => {
console.log(error);
});
}
```
6. Vue前端每次请求资源携带Token方法,例如:
```
axios.get('/user', {
headers: {
Authorization: 'Bearer ' + localStorage.getItem('token')
}
}).then(response => {
console.log(response.data);
}).catch(error => {
console.log(error);
});
```
阅读全文