我正在尝试使用JWT保护REST API,并且在登录期间遇到问题。
UserService.java
private final UserRepository repository;
private final PasswordEncoder passwordEncoder;
private final JwtTokenProvider jwtTokenProvider;
private final AuthenticationManager authenticationManager;
@Autowired
public UserService(UserRepository repository, PasswordEncoder passwordEncoder,
JwtTokenProvider jwtTokenProvider, AuthenticationManager authenticationManager) {
this.repository = repository;
this.passwordEncoder = passwordEncoder;
this.jwtTokenProvider = jwtTokenProvider;
this.authenticationManager = authenticationManager;
}
public String signin(String email, String password) {
try {
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(email, password);
authenticationManager.authenticate(token);
return jwtTokenProvider.createToken(email, Collections.singletonList(ROLE_CLIENT));
} catch (AuthenticationException e) {
throw new CustomException("Invalid email/password supplied", HttpStatus.UNPROCESSABLE_ENTITY);
}
}
public String signup(UsersEntity user) {
if (!repository.existsByEmail(user.getEmail())) {
user.setPassword(passwordEncoder.encode(user.getPassword()));
repository.save(user);
return jwtTokenProvider.createToken(user.getEmail(), Collections.singletonList(ROLE_CLIENT));
} else {
throw new CustomException("Email is already in use", HttpStatus.UNPROCESSABLE_ENTITY);
}
}
它成功注册了用户,但是当我尝试登录时,它总是在AuthenticationException
上抛出authenticationManager.authenticate(token);
。
我做错了什么