使用spring security写一个登陆接口
时间: 2023-11-18 19:11:15 浏览: 47
下面是一个使用Spring Security写的登陆接口示例:
```
@RestController
public class LoginController {
@Autowired
private AuthenticationManager authenticationManager;
@Autowired
private JwtUtil jwtUtil;
@PostMapping("/login")
public ResponseEntity<?> login(@RequestBody LoginRequest loginRequest) {
try {
authenticationManager.authenticate(
new UsernamePasswordAuthenticationToken(loginRequest.getUsername(), loginRequest.getPassword())
);
} catch (BadCredentialsException e) {
return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("Invalid username or password");
}
UserDetails userDetails = userDetailsService.loadUserByUsername(loginRequest.getUsername());
String jwt = jwtUtil.generateToken(userDetails);
return ResponseEntity.ok(new LoginResponse(jwt));
}
}
```
在这个示例中,我们使用了`@RestController`注解来标记这是一个RESTful接口。
`@Autowired`注解用于自动装配`AuthenticationManager`和`JwtUtil`实例。
`@PostMapping`注解用于将该接口映射到HTTP POST请求的`/login`路径上。
接收到HTTP POST请求后,我们首先使用`AuthenticationManager`来验证用户名和密码是否正确。如果验证失败,我们返回一个HTTP状态码为401的响应。
如果验证通过,我们使用`UserDetailsService`来获取用户详细信息,并使用`JwtUtil`生成一个JWT令牌。最后,我们将JWT令牌包装在一个`LoginResponse`对象中,并返回一个HTTP状态码为200的响应。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)