Last active
May 1, 2018 19:40
-
-
Save lusabo/8ceea040482219f618209602b2eb405f to your computer and use it in GitHub Desktop.
JwtTokenUtils
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
package com.eco.security; | |
import java.util.Date; | |
import java.util.HashMap; | |
import java.util.Map; | |
import org.springframework.beans.factory.annotation.Value; | |
import org.springframework.security.core.userdetails.UserDetails; | |
import org.springframework.stereotype.Component; | |
import io.jsonwebtoken.Claims; | |
import io.jsonwebtoken.Jwts; | |
import io.jsonwebtoken.SignatureAlgorithm; | |
@Component | |
public class JwtTokenUtils { | |
static final String CLAIM_KEY_USERNAME = "sub"; | |
static final String CLAIM_KEY_ROLE = "role"; | |
static final String CLAIM_KEY_CREATED = "created"; | |
@Value("${jwt.secret}") | |
private String secret; | |
@Value("${jwt.expiration}") | |
private Long expiration; | |
// Obtém o username contido no token JWT. | |
public String getUsernameFromToken(String token) { | |
String username; | |
try { | |
Claims claims = getClaimsFromToken(token); | |
username = claims.getSubject(); | |
} catch (Exception e) { | |
username = null; | |
} | |
return username; | |
} | |
// Retorna a data de expiração de um token JWT. | |
public Date getExpirationDateFromToken(String token) { | |
Date expiration; | |
try { | |
Claims claims = getClaimsFromToken(token); | |
expiration = claims.getExpiration(); | |
} catch (Exception e) { | |
expiration = null; | |
} | |
return expiration; | |
} | |
// Verifica e retorna se um token JWT é válido. | |
public boolean isTokenValid(String token) { | |
return !isTokenExpired(token); | |
} | |
// Retorna um novo token JWT com base nos dados do usuários. | |
public String getToken(UserDetails userDetails) { | |
Map<String, Object> claims = new HashMap<>(); | |
claims.put(CLAIM_KEY_USERNAME, userDetails.getUsername()); | |
userDetails.getAuthorities().forEach(authority -> claims.put(CLAIM_KEY_ROLE, authority.getAuthority())); | |
claims.put(CLAIM_KEY_CREATED, new Date()); | |
return generateToken(claims); | |
} | |
// Realiza o parse do token JWT para extrair as informações contidas no corpo. | |
private Claims getClaimsFromToken(String token) { | |
Claims claims; | |
try { | |
claims = Jwts.parser().setSigningKey(secret).parseClaimsJws(token).getBody(); | |
} catch (Exception e) { | |
claims = null; | |
} | |
return claims; | |
} | |
// Retorna a data de expiração com base na data atual. | |
private Date generateExpirationDate() { | |
return new Date(System.currentTimeMillis() + expiration * 1000); | |
} | |
// Verifica se um token JTW está expirado. | |
private boolean isTokenExpired(String token) { | |
Date expirationDate = this.getExpirationDateFromToken(token); | |
if (expirationDate == null) { | |
return false; | |
} | |
return expirationDate.before(new Date()); | |
} | |
// Gera um novo token JWT contendo os dados (claims) fornecidos. | |
private String generateToken(Map<String, Object> claims) { | |
return Jwts.builder().setClaims(claims).setExpiration(generateExpirationDate()) | |
.signWith(SignatureAlgorithm.HS512, secret).compact(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment