Last active
November 13, 2018 03:02
-
-
Save codinko/714e34650510cb4506d15af05c62f469 to your computer and use it in GitHub Desktop.
JWT creation in Rest Controller after validating user
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
import io.jsonwebtoken.Jwts; | |
import io.jsonwebtoken.SignatureAlgorithm; | |
@RestController | |
public class AuthenticationController { ... | |
@ApiOperation(value = "Validate the user login") | |
@PostMapping("/api/authentication/login") | |
public ResponseEntity<?> userLogin(@RequestBody User user) { | |
String jwtToken = ""; | |
try { | |
jwtToken = getToken(user.getUserId(), user.getUserPassword()); | |
map.clear(); | |
map.put("message", "user successfully logged in"); | |
map.put("token", jwtToken); | |
} catch (Exception e) { | |
String exceptionMessage = e.getMessage(); | |
map.clear(); | |
map.put("token", null); | |
map.put("message", exceptionMessage); | |
return new ResponseEntity<>(map, HttpStatus.UNAUTHORIZED); | |
} | |
return new ResponseEntity<>(map, HttpStatus.OK); | |
} | |
// Generate JWT token | |
public String getToken(String username, String password) throws Exception { | |
if (username == null || password == null) { | |
throw new ServletException("username and password is required"); | |
} | |
User user = userAuthenticationService.findByUserIdAndPassword(username, password); | |
if (user == null) { | |
throw new UserNotFoundException("Invalid credentials."); | |
} | |
String jwtToken = Jwts.builder().setSubject(username).setIssuedAt(new Date()) | |
.setExpiration(new Date(System.currentTimeMillis() + EXPIRATIONTIME)) | |
.signWith(SignatureAlgorithm.HS256, "secretkey").compact(); | |
return jwtToken; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment