对于将api与spring一起使用jwt身份验证,我是新手。 我对身份验证示例进行了改编,但我完全不确定我实现它的方式是否正确。
@RestController
@CrossOrigin 公共类JwtAuthenticationController {
@Autowired
private AuthenticationManager authenticationManager;
@Autowired
private JwtTokenUtil jwtTokenUtil;
@Autowired
private JwtUserDetailsService userDetailsService;
@Autowired
private JwtRequestRepository jwtRequestRepository;
@RequestMapping(value = "/authenticate", method = RequestMethod.POST)
public ResponseEntity<?> createAuthenticationToken(@RequestBody JwtRequest authenticationRequest) throws Exception
{
String CREDENTIALS = "INVALID_CREDENTIALS";
if(jwtRequestRepository.findByUsernameAndPassword(authenticationRequest.getUsername(), authenticationRequest.getPassword())!=null) {
CREDENTIALS = authenticationRequest.getUsername();
}
//authenticate(authenticationRequest.getUsername(),authenticationRequest.getPassword());
final UserDetails userDetails =
userDetailsService.loadUserByUsername(CREDENTIALS);
//JwtUserDetails userDetails = new JwtUserDetails();
//userDetails.setUsername(authenticationRequest.getUsername());
final String token = jwtTokenUtil.generateToken(userDetails);
return ResponseEntity.ok(new JwtResponse(token));
}
private void authenticate(String username, String password) throws Exception {
try {
authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(username, password));
} catch (DisabledException e) {
throw new Exception("USER_DISABLED", e);
} catch (BadCredentialsException e) {
throw new Exception("INVALID_CREDENTIALS", e);
}
}
}
所以我问他们是否知道可以通过访问数据库来验证用户身份的任何方式,并验证密码和用户是否存在,然后生成令牌。
答案 0 :(得分:1)
这是在Spring Boot中使用JWT的最佳和简单示例。 从git下载代码,然后尝试在本地计算机上运行。