Last active
January 23, 2020 14:01
-
-
Save sophea/7b5f525f472162c917862f93604812a0 to your computer and use it in GitHub Desktop.
JwtTokenController
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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