Search in sources :

Example 86 with Algorithm

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");
    }
}
Also used : TipoUsuario(br.com.propague.api.model.TipoUsuario) Usuario(br.com.propague.api.model.Usuario) HashMap(java.util.HashMap) Algorithm(com.auth0.jwt.algorithms.Algorithm) Date(java.util.Date) IOException(java.io.IOException) JWTVerifier(com.auth0.jwt.JWTVerifier) DecodedJWT(com.auth0.jwt.interfaces.DecodedJWT) HashMap(java.util.HashMap) Map(java.util.Map) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper)

Example 87 with Algorithm

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);
}
Also used : User(org.springframework.security.core.userdetails.User) HashMap(java.util.HashMap) Algorithm(com.auth0.jwt.algorithms.Algorithm) Date(java.util.Date) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper)

Example 88 with Algorithm

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);
}
Also used : JWTCreator(com.auth0.jwt.JWTCreator) Date(java.util.Date)

Example 89 with 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);
    }
}
Also used : JWTVerificationException(com.auth0.jwt.exceptions.JWTVerificationException) JWTCreator(com.auth0.jwt.JWTCreator) NullClaim(com.auth0.jwt.impl.NullClaim) Algorithm(com.auth0.jwt.algorithms.Algorithm) JWTVerifier(com.auth0.jwt.JWTVerifier) DecodedJWT(com.auth0.jwt.interfaces.DecodedJWT) Date(java.util.Date) NullClaim(com.auth0.jwt.impl.NullClaim) Claim(com.auth0.jwt.interfaces.Claim)

Example 90 with Algorithm

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);
}
Also used : ECKey(java.security.interfaces.ECKey) Algorithm(com.auth0.jwt.algorithms.Algorithm)

Aggregations

Algorithm (com.auth0.jwt.algorithms.Algorithm)206 Test (org.junit.Test)160 DecodedJWT (com.auth0.jwt.interfaces.DecodedJWT)90 JWTVerifier (com.auth0.jwt.JWTVerifier)79 ArgumentMatchers.anyString (org.mockito.ArgumentMatchers.anyString)79 ECDSAAlgorithmTest (com.auth0.jwt.algorithms.ECDSAAlgorithmTest)61 Date (java.util.Date)57 ECDSAKeyProvider (com.auth0.jwt.interfaces.ECDSAKeyProvider)51 RSAPublicKey (java.security.interfaces.RSAPublicKey)36 ECPublicKey (java.security.interfaces.ECPublicKey)34 RSAKeyProvider (com.auth0.jwt.interfaces.RSAKeyProvider)31 IOException (java.io.IOException)30 JWTCreator (com.auth0.jwt.JWTCreator)28 JWTVerificationException (com.auth0.jwt.exceptions.JWTVerificationException)25 ECPrivateKey (java.security.interfaces.ECPrivateKey)23 RSAPrivateKey (java.security.interfaces.RSAPrivateKey)21 HashMap (java.util.HashMap)17 UnsupportedEncodingException (java.io.UnsupportedEncodingException)16 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)15 JsonObject (com.google.gson.JsonObject)15