Search in sources :

Example 71 with JWT

use of com.auth0.android.jwt.JWT in project notes by menhuan.

the class JwtUtil method verify.

/**
 * 校验token是否正确
 *
 * @param token  密钥
 * @param secret 用户的密码
 * @return 是否正确
 */
public static boolean verify(String token, Map<String, Object> userToken, String secret) {
    Algorithm algorithm = Algorithm.HMAC256(secret);
    JWTVerifier verifier = JWT.require(algorithm).withClaim("userId", userToken.get("userId").toString()).withClaim("userName", userToken.get("userName").toString()).withClaim("timestamp", Long.parseLong(userToken.get("timestamp").toString())).build();
    DecodedJWT jwt = verifier.verify(token);
    return true;
}
Also used : Algorithm(com.auth0.jwt.algorithms.Algorithm) JWTVerifier(com.auth0.jwt.JWTVerifier) DecodedJWT(com.auth0.jwt.interfaces.DecodedJWT)

Example 72 with JWT

use of com.auth0.android.jwt.JWT in project springboot by LiJinHongPassion.

the class JWTUtil method verify.

/**
 * 校验token是否正确
 * @param token token
 * @param secret 用户的密码
 * @return 是否正确
 */
public static boolean verify(String token, String username, String secret) {
    try {
        // 指定加密算法
        Algorithm algorithm = Algorithm.HMAC256(secret);
        JWTVerifier verifier = JWT.require(algorithm).withClaim("username", username).build();
        DecodedJWT jwt = verifier.verify(token);
        return true;
    } catch (Exception exception) {
        return false;
    }
}
Also used : Algorithm(com.auth0.jwt.algorithms.Algorithm) JWTVerifier(com.auth0.jwt.JWTVerifier) DecodedJWT(com.auth0.jwt.interfaces.DecodedJWT) UnsupportedEncodingException(java.io.UnsupportedEncodingException) JWTDecodeException(com.auth0.jwt.exceptions.JWTDecodeException)

Example 73 with JWT

use of com.auth0.android.jwt.JWT in project learn-center-rest by elbar-org.

the class AuthTokenServiceImpl method refreshToken.

@Override
public void refreshToken(HttpServletRequest request, HttpServletResponse response) throws IOException {
    String authorizationHeader = request.getHeader(HttpHeaders.AUTHORIZATION);
    if (authorizationHeader != null && authorizationHeader.startsWith("Bearer ")) {
        try {
            String refreshToken = authorizationHeader.substring("Bearer ".length());
            DecodedJWT jwt = JWTUtils.getVerifier().verify(refreshToken);
            String userCode = jwt.getSubject();
            AuthUser user = authUserRepository.findByCode(UUID.fromString(userCode));
            Date accessDate = JWTUtils.getExpiry();
            String accessToken = JWT.create().withSubject(user.getCode().toString()).withExpiresAt(accessDate).withIssuer(request.getRequestURL().toString()).withClaim("roles", authUserRepository.getRolesByCode(UUID.fromString(userCode))).sign(JWTUtils.getAlgorithm());
            AuthTokenCreateDTO tokenCreateDTO = new AuthTokenCreateDTO(UUID.fromString(userCode), accessToken, accessDate, AuthTokenTypeEnum.ACCESS_TOKEN.name());
            create(tokenCreateDTO);
            AuthTokenGetDTO tokenGetDTO1 = new AuthTokenGetDTO(AuthTokenTypeEnum.ACCESS_TOKEN.name(), accessToken);
            AuthTokenGetDTO tokenGetDTO2 = new AuthTokenGetDTO(AuthTokenTypeEnum.REFRESH_TOKEN.name(), refreshToken);
            List<AuthTokenGetDTO> tokenGetDTOList = new ArrayList<>();
            tokenGetDTOList.add(tokenGetDTO1);
            tokenGetDTOList.add(tokenGetDTO2);
            response.setContentType(MediaType.APPLICATION_JSON_VALUE);
            new ObjectMapper().writeValue(response.getOutputStream(), tokenGetDTOList);
        } catch (Exception e) {
            response.setHeader("error", e.getMessage());
            response.setStatus(HttpStatus.FORBIDDEN.value());
            Map<String, String> error = new HashMap<>();
            error.put("error_message", e.getMessage());
            response.setContentType(MediaType.APPLICATION_JSON_VALUE);
            new ObjectMapper().writeValue(response.getOutputStream(), error);
        }
    } else {
        throw new RuntimeException("Refresh token is missing");
    }
}
Also used : AuthUser(elbar.company.learn_center_rest.entity.auth.user.AuthUser) IOException(java.io.IOException) AuthTokenCreateDTO(elbar.company.learn_center_rest.dto.auth.token.AuthTokenCreateDTO) AuthTokenGetDTO(elbar.company.learn_center_rest.dto.auth.token.AuthTokenGetDTO) DecodedJWT(com.auth0.jwt.interfaces.DecodedJWT) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper)

Example 74 with JWT

use of com.auth0.android.jwt.JWT in project ccd-case-document-am-api by hmcts.

the class DynamicS2sDetailsResponseTransformer method dynamicResponse.

@Override
protected String dynamicResponse(Request request, Response response, Parameters parameters) {
    String serviceName = null;
    String s2sToken = removeBearerFromToken(request.getHeader(AUTHORIZATION));
    if (s2sToken != null) {
        DecodedJWT jwt = JWT.decode(s2sToken);
        if (jwt.getExpiresAt().before(new Date())) {
            throw new SecurityException();
        }
        serviceName = jwt.getSubject();
    }
    return serviceName;
}
Also used : DecodedJWT(com.auth0.jwt.interfaces.DecodedJWT) Date(java.util.Date)

Example 75 with JWT

use of com.auth0.android.jwt.JWT in project balcaovirtual by trf2-jus-br.

the class ProcessoValidarGet method run.

@Override
public void run(Request req, Response resp, BalcaojusContext ctx) throws Exception {
    boolean fPorCaptcha = false;
    if (req.captcha != null) {
        if (!Utils.verifyCaptcha(req.captcha))
            throw new PresentableUnloggedException("Token de reCaptcha inválido");
        fPorCaptcha = true;
    } else if (isValidToken(req.token, req.numero)) {
        resp.token = req.token;
    } else
        AutenticarPost.assertAuthorization();
    String usuario = null;
    try {
        Usuario u = AutenticarPost.assertUsuario();
        usuario = u.usuario;
    } catch (Exception e) {
        usuario = BalcaojusServlet.INSTANCE.getProperty("public.username");
    }
    String[] numeros = (req.numero != null && req.numero.trim() != "") ? req.numero.split(",") : null;
    if (numeros != null && numeros.length > 100)
        throw new PresentableException("Não é permitido validar mais de 100 números de processos em uma única operação");
    validar(usuario, numeros, req.nome, req.tipodedocumento, req.documento, req.oab, resp);
    if (fPorCaptcha && resp.list != null && resp.list.size() > 0) {
        StringBuilder sb = new StringBuilder();
        for (ProcessoValido p : resp.list) {
            if (sb.length() > 0)
                sb.append(",");
            sb.append(p.numero);
        }
        resp.token = jwt(sb.toString());
    }
}
Also used : Usuario(br.jus.trf2.balcaojus.AutenticarPost.Usuario) PresentableUnloggedException(com.crivano.swaggerservlet.PresentableUnloggedException) PresentableException(com.crivano.swaggerservlet.PresentableException) JWTVerifyException(com.auth0.jwt.JWTVerifyException) PresentableException(com.crivano.swaggerservlet.PresentableException) SignatureException(java.security.SignatureException) IOException(java.io.IOException) PresentableUnloggedException(com.crivano.swaggerservlet.PresentableUnloggedException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) InvalidKeyException(java.security.InvalidKeyException) ProcessoValido(br.jus.trf2.balcaojus.IBalcaojus.ProcessoValido)

Aggregations

DecodedJWT (com.auth0.jwt.interfaces.DecodedJWT)305 Test (org.junit.Test)217 Algorithm (com.auth0.jwt.algorithms.Algorithm)110 ArgumentMatchers.anyString (org.mockito.ArgumentMatchers.anyString)82 JWTVerifier (com.auth0.jwt.JWTVerifier)79 IOException (java.io.IOException)60 JWTVerificationException (com.auth0.jwt.exceptions.JWTVerificationException)54 ECDSAAlgorithmTest (com.auth0.jwt.algorithms.ECDSAAlgorithmTest)53 Date (java.util.Date)50 Claim (com.auth0.jwt.interfaces.Claim)36 RSAPublicKey (java.security.interfaces.RSAPublicKey)34 ECPublicKey (java.security.interfaces.ECPublicKey)27 ECDSAKeyProvider (com.auth0.jwt.interfaces.ECDSAKeyProvider)26 HashMap (java.util.HashMap)25 JWTDecodeException (com.auth0.jwt.exceptions.JWTDecodeException)20 Instant (java.time.Instant)20 JsonObject (com.google.gson.JsonObject)19 ServletException (javax.servlet.ServletException)19 JWT (com.auth0.jwt.JWT)18 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)18