Skip to content

Instantly share code, notes, and snippets.

Created February 16, 2018 00:43
Show Gist options
  • Save anonymous/c94877fa545f7a2ac915f2765952c768 to your computer and use it in GitHub Desktop.
Save anonymous/c94877fa545f7a2ac915f2765952c768 to your computer and use it in GitHub Desktop.
ublic class TokenAuthenticationService {
// EXPIRATION_TIME = 10 dias
static final long EXPIRATION_TIME = 860_000_000;
static final String SECRET = "MySecret";
static final String TOKEN_PREFIX = "Bearer";
static final String HEADER_STRING = "Authorization";
static void addAuthentication(HttpServletResponse response, String username) {
String JWT = Jwts.builder()
.setSubject(username)
.setExpiration(new Date(System.currentTimeMillis() + EXPIRATION_TIME))
.signWith(SignatureAlgorithm.HS512, SECRET)
.compact();
response.addHeader(HEADER_STRING, TOKEN_PREFIX + " " + JWT);
}
static Authentication getAuthentication(HttpServletRequest request) {
String token = request.getHeader(HEADER_STRING);
if (token != null) {
// faz parse do token
String user = Jwts.parser()
.setSigningKey(SECRET)
.parseClaimsJws(token.replace(TOKEN_PREFIX, ""))
.getBody()
.getSubject();
if (user != null) {
return new UsernamePasswordAuthenticationToken(user, null, Collections.emptyList());
}
}
return null;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment