Skip to content

Instantly share code, notes, and snippets.

@codinko
Last active November 13, 2018 03:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save codinko/714e34650510cb4506d15af05c62f469 to your computer and use it in GitHub Desktop.
Save codinko/714e34650510cb4506d15af05c62f469 to your computer and use it in GitHub Desktop.
JWT creation in Rest Controller after validating user
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