Skip to content

Instantly share code, notes, and snippets.

@ugurcemozturk
Created December 6, 2017 10:06
Show Gist options
  • Save ugurcemozturk/42f94ffe061ea3c69c873509198c6d31 to your computer and use it in GitHub Desktop.
Save ugurcemozturk/42f94ffe061ea3c69c873509198c6d31 to your computer and use it in GitHub Desktop.
JWT
public class TokenAuthenticationService {
static final long EXPIRATIONTIME = 216_000_000; // 2.5 gün
static final String SECRET = "Emakina";
static final String TOKEN_PREFIX = "Bearer ";
static final String HEADER_STRING = "Authorization";
//Authenticate olmus user'a JWT yollamak icin
static void addAuth(HttpServletResponse response, String username) {
String JWT = Jwts.builder()
//Payload'daki sub degiskenini username ile set et
.setSubject(username)
// Payload'daki exp degiskeni yani Token'in gecerlilik suresini set et
.setExpiration(new Date(System.currentTimeMillis() + EXPIRATIONTIME))
//HMAC-SHA512 algoritmasi ile imzala
.signWith(SignatureAlgorithm.HS512, SECRET)
.compact();
response.addHeader(HEADER_STRING, TOKEN_PREFIX + JWT);
}
//User'in JWT'sini check etmek icin
static Authentication getAuth(HttpServletRequest request) {
String token = request.getHeader(HEADER_STRING);
if (token != null) {
String userJWT = Jwts.parser()
.setSigningKey(SECRET)
.parseClaimsJws(token.replace(TOKEN_PREFIX, ""))
.getBody()
.getSubject();
return userJWT != null ?
new UsernamePasswordAuthenticationToken(userJWT, null, emptyList())
: null;
}
return null;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment