Skip to content

Instantly share code, notes, and snippets.

@sophea
Last active January 23, 2020 14:01
Show Gist options
  • Save sophea/7b5f525f472162c917862f93604812a0 to your computer and use it in GitHub Desktop.
Save sophea/7b5f525f472162c917862f93604812a0 to your computer and use it in GitHub Desktop.
JwtTokenController
package com.sma.security.controller;
@RestController
@CrossOrigin
public class JwtTokenController {
@Autowired
private AuthenticationManager authenticationManager;
@Autowired
private JwtTokenService jwtTokenUtil;
@Autowired
private JwtUserDetailsService userDetailsService;
@RequestMapping(value = "/auth/token", method = RequestMethod.POST)
public ResponseEntity<?> createAuthenticationToken(@RequestBody UserDTO authenticationRequest) throws Exception {
final Authentication auth = authenticate(authenticationRequest.getUsername(), authenticationRequest.getPassword());
SecurityContextHolder.getContext().setAuthentication(auth);
return ResponseEntity.ok(new JwtResponse(jwtTokenUtil.generateToken(auth)));
}
@RequestMapping(value = "/register", method = RequestMethod.POST)
public ResponseEntity<?> saveUser(@RequestBody UserDTO user) throws Exception {
return ResponseEntity.ok(userDetailsService.save(user));
}
private Authentication authenticate(String username, String password) throws Exception {
try {
return authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(username, password));
} catch (DisabledException e) {
throw new Exception("USER_DISABLED", e);
} catch (BadCredentialsException e) {
throw new Exception("INVALID_CREDENTIALS", e);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment