import org.springframework.beans.factory.annotation.Autowired;import org.springframework.http.ResponseEntity;import org.springframework.security.authentication.AuthenticationManager;import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;import org.springframework.security.core.Authentication;import org.springframework.security.core.userdetails.UserDetails;import org.springframework.web.bind.annotation.PostMapping;import org.springframework.web.bind.annotation.RequestBody;import org.springframework.web.bind.annotation.RestController;@RestControllerpublic class AuthController { @Autowired private AuthenticationManager authenticationManager; @Autowired private JwtTokenUtil jwtTokenUtil; @Autowired private UserDetailsService userDetailsService; @PostMapping("/login") public ResponseEntity<?> login(@RequestBody AuthRequest authRequest) throws Exception { try { Authentication authentication = authenticationManager.authenticate( new UsernamePasswordAuthenticationToken(authRequest.getUsername(), authRequest.getPassword()) ); UserDetails userDetails = userDetailsService.loadUserByUsername(authRequest.getUsername()); String token = jwtTokenUtil.generateToken(userDetails); return ResponseEntity.ok(new AuthResponse(token)); } catch (Exception e) { throw new Exception("Incorrect username or password", e); } }}中AuthRequest
时间: 2024-01-08 21:02:28 浏览: 117
org.springframework.test-3.0.2.RELEASE.jar
是一个自定义类,用于接收用户登录请求中的用户名和密码。它可能长这样:
```
public class AuthRequest {
private String username;
private String password;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
```
在上面的代码中,我们定义了一个包含用户名和密码的类,可以通过setter和getter方法访问它们。这个类将被用作请求体来接收用户的登录请求。
阅读全文