Reputation: 13
I am new to using jwt authentication with spring for rest apis. I made an adaptation of an authentication example but I am not at all sure that the way I implement it is correct.
@RestController
@CrossOrigin public class 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);
}
}
}
so I ask them if they know of any way to be able to authenticate the user by accessing the database and verify that the password and the user exist and then generate the token.
Upvotes: 0
Views: 156
Reputation: 697
This is best and Simple example of using JWT with Spring boot. Download the code from git and try to run in your local machine.
Upvotes: 1