// 在Spring Boot的Controller中添加登录接口
@RestController
public class AuthController {
@Autowired
private AuthenticationManager authenticationManager;
@PostMapping("/login")
public ResponseEntity<?> login(@RequestBody LoginRequest loginRequest) {
try {
// 使用Spring Security提供的AuthenticationManager进行认证
Authentication authentication = authenticationManager.authenticate(
new UsernamePasswordAuthenticationToken(
loginRequest.getUsername(),
loginRequest.getPassword()
)
);
SecurityContextHolder.getContext().setAuthentication(authentication);
// 生成并返回JWT令牌
String token = Jwts.builder()
.setSubject(loginRequest.getUsername())
.setExpiration(new Date(System.currentTimeMillis() + 864000000))
.signWith(SignatureAlgorithm.HS512, "YourSecretKey")
.compact();
return ResponseEntity.ok(new JwtResponse(token));
} catch (AuthenticationException e) {
return new ResponseEntity<>(Collections.singletonMap("error", e.getMessage()), HttpStatus.UNAUTHORIZED);
}
}
}
// Vue.js中发送登录请求并处理响应
export default {
data() {
return {
username: '',
password: ''
};
},
methods: {
login() {
axios.post('http://localhost:8080/login', {
username: this.username,
password: this.password
})
.then(response => {
localStorage.setItem('token', response.data.token);
// 登录成功后的操作,例如跳转到主页
this.$router.push('/');
})
.catch(error => {
console.error('登录失败', error);
// 登录失败的操作,例如显示错误信息
});
}
}
}
这个简易的例子展示了如何在Spring Boot后端使用AuthenticationManager进行用户认证,并在成功认证后生成JWT令牌。在Vue.js前端,用户提交登录信息,后端返回JWT令牌后,将其保存在localStorage中,并且可以根据实际需求进行页面跳转或错误处理。