Skip to content

Instantly share code, notes, and snippets.

@andreybleme
Created April 1, 2017 17:01
Show Gist options
  • Save andreybleme/036ce00169c70e12d3032d45390705dc to your computer and use it in GitHub Desktop.
Save andreybleme/036ce00169c70e12d3032d45390705dc to your computer and use it in GitHub Desktop.
andreybleme.com | JWT com Springboot
package com.jwtme.security;
import java.util.Collections;
import java.util.Date;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
public 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