use of com.auth0.jwt.Algorithm in project UPE_2021_2_Propague by netrometro.
the class TipoParaUsuarioForm method refreshToken.
@GetMapping("/token/refresh")
public void refreshToken(HttpServletRequest request, HttpServletResponse response) throws IOException {
String authorizationHeader = request.getHeader("Authorization");
if (authorizationHeader != null && authorizationHeader.startsWith("Bearer ")) {
try {
String refresh_token = authorizationHeader.substring(7);
Algorithm algorithm = Algorithm.HMAC256("secret".getBytes());
JWTVerifier verifier = JWT.require(algorithm).build();
DecodedJWT decodedJWT = verifier.verify(refresh_token);
String username = decodedJWT.getSubject();
Usuario usuario = servico.getUsuario(username);
String acces_token = com.auth0.jwt.JWT.create().withSubject(usuario.getEmail()).withExpiresAt(new Date(System.currentTimeMillis() + 10 * 60 * 1000)).withIssuer(request.getRequestURL().toString()).withClaim("tipo", usuario.getTipos().stream().map(TipoUsuario::getNome).collect(Collectors.joining())).sign(algorithm);
// response.setHeader("acces_token", token);
// response.setHeader("refresh_token", refresh_token);
Map<String, String> map = new HashMap<>();
map.put("token", acces_token);
map.put("refresh_token", refresh_token);
response.setContentType(APPLICATION_JSON_VALUE);
new ObjectMapper().writeValue(response.getOutputStream(), map);
} catch (Exception e) {
response.setHeader("error", e.getMessage());
response.setStatus(403);
Map<String, String> map = new HashMap<>();
map.put("error", e.getMessage());
response.setContentType(MimeTypeUtils.APPLICATION_JSON_VALUE);
new ObjectMapper().writeValue(response.getOutputStream(), map);
}
} else {
throw new RuntimeException("Refresh token is missing");
}
}
use of com.auth0.jwt.Algorithm in project UPE_2021_2_Propague by netrometro.
the class AuthenticationCustomFilter method successfulAuthentication.
@Override
protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain, Authentication autenticacao) throws IOException, ServletException {
User user = (User) autenticacao.getPrincipal();
Algorithm algoritmo = Algorithm.HMAC256("secret".getBytes());
String tokenAcesso = JWT.create().withSubject(user.getUsername()).withExpiresAt(new Date(System.currentTimeMillis() + 10 * 60 * 1000)).withIssuer(request.getRequestURL().toString()).withClaim("tipos", user.getAuthorities().stream().map(GrantedAuthority::getAuthority).collect(Collectors.toList())).sign(algoritmo);
String tokenRefresh = JWT.create().withSubject(user.getUsername()).withExpiresAt(new Date(System.currentTimeMillis() + 30 * 60 * 1000)).withIssuer(request.getRequestURL().toString()).sign(algoritmo);
Map<String, String> tokens = new HashMap<>();
tokens.put("token_acesso", tokenAcesso);
tokens.put("token_refresh", tokenRefresh);
tokens.put("email_usuario", user.getUsername());
response.setContentType(MediaType.APPLICATION_JSON_VALUE);
new ObjectMapper().writeValue(response.getOutputStream(), tokens);
}
use of com.auth0.jwt.Algorithm in project Team_BbungCles_Devnity_BE by prgrms-web-devcourse.
the class Jwt method sign.
public String sign(Claims claims) {
Date now = new Date();
JWTCreator.Builder builder = com.auth0.jwt.JWT.create();
builder.withIssuer(issuer);
builder.withIssuedAt(now);
if (expirySeconds > 0) {
builder.withExpiresAt(new Date(now.getTime() + expirySeconds * 1_000L));
}
builder.withClaim("userId", claims.userId);
builder.withClaim("email", claims.email);
builder.withClaim("role", claims.role);
return builder.sign(algorithm);
}
use of com.auth0.jwt.Algorithm in project yyl_example by Relucent.
the class JwtDemo method main.
public static void main(String[] args) throws Exception {
long currentMillis = System.currentTimeMillis();
// JWT 生存时间(5秒)
long ttl = 5000;
// 生成JWT的时间
Date iat = new Date(currentMillis);
// 生成JWT失效时间
Date exp = new Date(currentMillis + ttl);
// 签名秘钥
String secret = "key";
// 签发人
String issuer = "root";
// 算法
Algorithm algorithm = Algorithm.HMAC256(secret);
// 本地的密码解码
JWTCreator.Builder builder = JWT.create();
// 签发时间
builder.withIssuedAt(iat);
// 签发人
builder.withIssuer(issuer);
// 过期时间
builder.withExpiresAt(exp);
// 主题
builder.withClaim("subject", "MySubject");
String token = builder.sign(algorithm);
System.out.println(token);
// 解密
JWTVerifier verifier = JWT.require(algorithm).withIssuer(issuer).build();
DecodedJWT jwt = verifier.verify(token);
Map<String, Claim> claims = jwt.getClaims();
NullClaim nullClaim = new NullClaim();
System.out.println(claims.getOrDefault("subject", nullClaim).asString());
// 等待5秒
System.out.println("Wait 5 seconds!");
Thread.sleep(5000);
try {
// 这时候Token已经超时了,会抛出异常
verifier.verify(token);
} catch (JWTVerificationException e) {
System.err.println(e);
}
}
use of com.auth0.jwt.Algorithm in project cryptography by norkator.
the class JWT method createECDSA256Jwt.
/**
* Create elliptic curve based JWT
*
* @param privatePem of EC keypair
* @param issuer party name
* @return json web token
* @throws JWTCreationException if jwt creation fails
*/
public static String createECDSA256Jwt(String privatePem, String issuer) throws InvalidKeySpecException, NoSuchAlgorithmException {
ECKey privateKey = (ECKey) PEMToKey.getPemPrivateKey(privatePem, "ECDSA");
Algorithm algorithm = Algorithm.ECDSA256(privateKey);
return com.auth0.jwt.JWT.create().withIssuer(issuer).withClaim("test claim", "test claim value").sign(algorithm);
}
Aggregations