public AuthenticationResponse authenticate(AuthenticationRequest request) {
authenticationManager.authenticate(
new UsernamePasswordAuthenticationToken(
request.getEmail(),
request.getPassword()
)
);
var user = repository.findByEmail(request.getEmail())
.orElseThrow(() -> new UsernameNotFoundException("User not found"));
var jwtToken = jwtService.generateToken(new HashMap<>(),user);
return AuthenticationResponse.builder()
.token(jwtToken)
.build();
}
它总是返回 403 错误并允许用户登录如何解决这个问题
在这种情况下,调试是个好主意。如果您查看正在调用的构造函数,您将看到以下代码:
public UsernamePasswordAuthenticationToken(Object principal, Object credentials) {
super(null);
this.principal = principal;
this.credentials = credentials;
setAuthenticated(false);
}
正如您所看到的,您正在调用的构造函数设置身份验证为 false。
您想调用不同的构造函数,其中
new UsernamePasswordAuthenticationToken(request.getEmail(), request.getPassword(), List.of())
将调用以下重载
public UsernamePasswordAuthenticationToken(Object principal, Object credentials,
Collection<? extends GrantedAuthority> authorities) {
super(authorities);
this.principal = principal;
this.credentials = credentials;
super.setAuthenticated(true); // must use super, as we override
}
老实说,我认为 Spring Security 在这里做出了一个错误的决定,这些重载让许多程序员感到困惑,并且应该使用具有描述性名称的静态方法,但他们肯定有自己的理由。