【问题标题】:Any example of jwt authenticating with mysql in spring boot?在 Spring Boot 中使用 mysql 进行 jwt 身份验证的任何示例?
【发布时间】: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


【解决方案1】:

这是在 Spring Boot 中使用 JWT 的最佳且简单的示例。 从 git 下载代码并尝试在本地机器上运行。

Spring Boot Jwt Example

Spring Boot Jwt example

【讨论】:

    猜你喜欢
    • 2018-08-29
    • 1970-01-01
    • 2018-07-04
    • 2021-06-24
    • 2018-03-12
    • 2018-02-27
    • 2021-05-21
    • 2022-10-05
    • 2017-11-02
    相关资源
    最近更新 更多