【发布时间】:2020-12-28 02:50:45
【问题描述】:
我不熟悉将 jwt 身份验证与 spring 一起用于 rest api。 我改编了一个身份验证示例,但我完全不确定我实现它的方式是否正确。
@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);
}
}
}
所以我问他们是否知道有什么方法可以通过访问数据库来验证用户身份并验证密码和用户是否存在,然后生成令牌。
【问题讨论】:
-
您应该使用 spring security 而不是构建自己的解决方案。构建自己的安全解决方案是不好的做法。
标签: spring-boot jwt