Search in sources :

Example 76 with JWT

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

the class ProcessoValidarGet method verify.

public static Map<String, Object> verify(String jwt) throws InvalidKeyException, NoSuchAlgorithmException, IllegalStateException, SignatureException, IOException, JWTVerifyException {
    final JWTVerifier verifier = new JWTVerifier(Utils.getApiPassword());
    Map<String, Object> map;
    map = verifier.verify(jwt);
    return map;
}
Also used : JWTVerifier(com.auth0.jwt.JWTVerifier)

Example 77 with JWT

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

the class CertidaoObterTokenGet method verify.

public static Map<String, Object> verify(String jwt) throws InvalidKeyException, NoSuchAlgorithmException, IllegalStateException, SignatureException, IOException, JWTVerifyException {
    final JWTVerifier verifier = new JWTVerifier(Utils.getApiPassword());
    Map<String, Object> map;
    map = verifier.verify(jwt);
    return map;
}
Also used : JWTVerifier(com.auth0.jwt.JWTVerifier)

Example 78 with JWT

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

the class CertidaoObterTokenGet method jwt.

public static String jwt(String certidao, String requisitante, String cpfcnpj) throws Exception {
    final String issuer = Utils.getJwtIssuer();
    // issued at claim
    final long iat = System.currentTimeMillis() / 1000L;
    // token expires in 12h
    final long exp = iat + 12 * 60 * 60L;
    final JWTSigner signer = new JWTSigner(Utils.getApiPassword());
    final HashMap<String, Object> claims = new HashMap<String, Object>();
    if (issuer != null)
        claims.put("iss", issuer);
    claims.put("exp", exp);
    claims.put("iat", iat);
    claims.put("certidao", certidao);
    claims.put("requisitante", requisitante);
    claims.put("cpfcnpj", cpfcnpj);
    claims.put("typ", "consulta-certidao");
    final String jwt = signer.sign(claims);
    return jwt;
}
Also used : JWTSigner(com.auth0.jwt.JWTSigner) HashMap(java.util.HashMap)

Example 79 with JWT

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

the class DownloadJwtFilenameGet method run.

@Override
public void run(Request req, Response resp, BalcaojusContext ctx) throws Exception {
    Map<String, Object> map = verify(req.jwt);
    String username = (String) map.get("username");
    String origin = (String) map.get("origin");
    String password;
    if (username != null && !"pub".equals(origin))
        password = AutenticarPost.Usuario.getSenha(username);
    else {
        username = BalcaojusServlet.INSTANCE.getProperty("public.username");
        password = BalcaojusServlet.INSTANCE.getProperty("public.password");
    }
    String name = (String) map.get("name");
    String file = (String) map.get("file");
    String numProc = (String) map.get("proc");
    String numDoc = (String) map.get("doc");
    String orgao = (String) map.get("orgao");
    String type = (String) map.get("typ");
    String text = (String) map.get("text");
    String cargo = (String) map.get("cargo");
    String empresa = (String) map.get("empresa");
    String unidade = (String) map.get("unidade");
    String uuid = (String) map.get("uuid");
    String disposition = "attachment".equals(req.disposition) ? "attachment" : "inline";
    if (!"download".equals(type))
        throw new Exception("Tipo de token JWT inválido");
    if (text != null) {
        byte[] pdf = ProcessoNumeroCotaPrevisaoPdfPost.criarPDF(name, numProc, text, cargo, empresa, unidade);
        resp.contentdisposition = "inline";
        resp.contentlength = (long) pdf.length;
        resp.contenttype = "application/pdf";
        resp.inputstream = new ByteArrayInputStream(pdf);
    } else if (file != null && file.equals("avisos-pendentes.xml")) {
    // TODO: IMPLEMENTAR
    // // Processo completo
    // Future<SwaggerAsyncResponse<UsuarioWebUsernameAvisoPendenteExportarGetResponse>>
    // future = SwaggerCall
    // .callAsync("obter XML de avisos", "Bearer " + req.jwt, "GET",
    // Utils.getWsProcessualUrl() + "/usuario-web/" +
    // map.get("username")
    // + "/aviso-pendente/exportar",
    // null, UsuarioWebUsernameAvisoPendenteExportarGetResponse.class);
    // SwaggerAsyncResponse<UsuarioWebUsernameAvisoPendenteExportarGetResponse>
    // sar = future.get();
    // if (sar.getException() != null)
    // throw sar.getException();
    // UsuarioWebUsernameAvisoPendenteExportarGetResponse r =
    // (UsuarioWebUsernameAvisoPendenteExportarGetResponse) sar
    // .getResp();
    // resp.contentdisposition = "attachment;filename=" +
    // map.get("username") + "-avisos-pendentes.xml";
    // resp.contentlength = r.contentlength;
    // resp.contenttype = r.contenttype;
    // resp.inputstream = r.inputstream;
    } else if (file != null && file.equals("avisos-confirmados.xml")) {
    // TODO: IMPLEMENTAR
    // Future<SwaggerAsyncResponse<UsuarioWebUsernameAvisoConfirmadoExportarGetResponse>>
    // future = SwaggerCall
    // .callAsync("obter XML de avisos confirmados", "Bearer " +
    // req.jwt, "GET",
    // Utils.getWsProcessualUrl() + "/usuario-web/" +
    // map.get("username")
    // + "/aviso-confirmado/exportar",
    // null,
    // UsuarioWebUsernameAvisoConfirmadoExportarGetResponse.class);
    // SwaggerAsyncResponse<UsuarioWebUsernameAvisoConfirmadoExportarGetResponse>
    // sar = future.get();
    // if (sar.getException() != null)
    // throw sar.getException();
    // UsuarioWebUsernameAvisoConfirmadoExportarGetResponse r =
    // (UsuarioWebUsernameAvisoConfirmadoExportarGetResponse) sar
    // .getResp();
    // resp.contentdisposition = "attachment;filename=" +
    // map.get("username") + "-avisos-confirmados.xml";
    // resp.contentlength = r.contentlength;
    // resp.contenttype = r.contenttype;
    // resp.inputstream = r.inputstream;
    } else {
        ContentInfoUtil contentInfoUtil = new ContentInfoUtil();
        if (numDoc != null) {
            byte[] ab = null;
            // Peça Processual
            username = Utils.preprocessarId(username, password, orgao, origin);
            password = Utils.preprocessarSenha(username, password, orgao, origin);
            ab = SoapMNI.obterPecaProcessual(username, password, orgao, numProc, numDoc);
            ContentInfo info = contentInfoUtil.findMatch(ab);
            resp.contenttype = info.getMimeType();
            if (info.getMimeType().startsWith("application/xml")) {
                final XMLStreamReader xmlStreamReader = XMLInputFactory.newInstance().createXMLStreamReader(new ByteArrayInputStream(ab));
                String fileEncoding = xmlStreamReader.getEncoding();
                boolean fHtml = false;
                while (xmlStreamReader.hasNext()) {
                    int eventType = xmlStreamReader.next();
                    if (eventType == XMLStreamConstants.START_ELEMENT) {
                        if (xmlStreamReader.getLocalName().equals("html"))
                            fHtml = true;
                        break;
                    }
                }
                xmlStreamReader.close();
                if (fHtml) {
                    info = contentInfoUtil.findMimeTypeMatch("text/html");
                    resp.contenttype = info.getMimeType() + "; charset=" + fileEncoding;
                }
            }
            resp.contentdisposition = disposition + ";filename=" + numProc + "-peca-" + numDoc + "." + info.getFileExtensions()[0];
            resp.contentlength = (long) ab.length;
            resp.inputstream = new ByteArrayInputStream(ab);
        } else if (uuid != null) {
            String dirTemp = Utils.getDirTemp();
            String bufName = dirTemp + "/" + numProc + "-completo-" + uuid + ".pdf";
            resp.contentdisposition = disposition + ";filename=" + numProc + "-completo.pdf";
            resp.contentlength = (long) new File(bufName).length();
            resp.contenttype = "application/pdf";
            resp.inputstream = new FileInputStream(bufName);
        } else {
            // Processo completo
            // Consulta o processo para saber quais são os documentos a serem
            // concatenados
            String json = SoapMNI.consultarProcesso(username, password, orgao, numProc, false, false, true);
            JSONObject proc = new JSONObject(json).getJSONObject("value");
            JSONArray docs = proc.getJSONArray("documento");
            // Cria um documento em diretório temporário para agregar os
            // diversos PDFs
            String dirTemp = Utils.getDirTemp();
            String bufName = dirTemp + "/" + numProc + "-completo-" + UUID.randomUUID().toString() + ".pdf";
            FileOutputStream buf = new FileOutputStream(bufName);
            Document document = new Document();
            PdfCopy copy = new PdfSmartCopy(document, buf);
            document.open();
            PdfReader reader;
            for (int i = 0; i < docs.length(); i++) {
                String idDocumento = docs.getJSONObject(i).getString("idDocumento");
                byte[] ab = SoapMNI.obterPecaProcessual(username, password, orgao, numProc, idDocumento);
                ContentInfo info = contentInfoUtil.findMatch(ab);
                if (info.getMimeType().startsWith("application/xml")) {
                    final XMLStreamReader xmlStreamReader = XMLInputFactory.newInstance().createXMLStreamReader(new ByteArrayInputStream(ab));
                    String fileEncoding = xmlStreamReader.getEncoding();
                    boolean fHtml = false;
                    while (xmlStreamReader.hasNext()) {
                        int eventType = xmlStreamReader.next();
                        if (eventType == XMLStreamConstants.START_ELEMENT) {
                            if (xmlStreamReader.getLocalName().equals("html"))
                                fHtml = true;
                            break;
                        }
                    }
                    xmlStreamReader.close();
                    if (fHtml) {
                        String html = new String(ab, fileEncoding);
                        // System.out.println(html);
                        ab = new Html2Pdf().converter(html, false);
                        info = contentInfoUtil.findMimeTypeMatch("application/pdf");
                    }
                }
                if (info.getMimeType().startsWith("text/html")) {
                    String html = new String(ab, StandardCharsets.UTF_8);
                    if (html.toLowerCase().contains("charset=windows-1252") || html.toLowerCase().contains("iso-8859-1"))
                        html = new String(ab, StandardCharsets.ISO_8859_1);
                    // System.out.println(html);
                    ab = new Html2Pdf().converter(html, false);
                    info = contentInfoUtil.findMimeTypeMatch("application/pdf");
                }
                if (!"application/pdf".equals(info.getMimeType()))
                    throw new PresentableException("Não foi possível obter um PDF. (" + info.getMimeType() + ")");
                reader = new PdfReader(ab);
                copy.addDocument(reader);
                reader.close();
            }
            document.close();
            resp.contentdisposition = disposition + ";filename=" + numProc + "-completo.pdf";
            resp.contentlength = (long) new File(bufName).length();
            resp.contenttype = "application/pdf";
            resp.inputstream = new FileInputStream(bufName);
        }
    }
}
Also used : XMLStreamReader(javax.xml.stream.XMLStreamReader) JSONArray(org.json.JSONArray) PdfReader(com.itextpdf.text.pdf.PdfReader) Document(com.itextpdf.text.Document) ContentInfoUtil(com.j256.simplemagic.ContentInfoUtil) JWTVerifyException(com.auth0.jwt.JWTVerifyException) PresentableException(com.crivano.swaggerservlet.PresentableException) SignatureException(java.security.SignatureException) IOException(java.io.IOException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) InvalidKeyException(java.security.InvalidKeyException) FileInputStream(java.io.FileInputStream) PdfCopy(com.itextpdf.text.pdf.PdfCopy) JSONObject(org.json.JSONObject) ByteArrayInputStream(java.io.ByteArrayInputStream) ContentInfo(com.j256.simplemagic.ContentInfo) FileOutputStream(java.io.FileOutputStream) PdfSmartCopy(com.itextpdf.text.pdf.PdfSmartCopy) JSONObject(org.json.JSONObject) PresentableException(com.crivano.swaggerservlet.PresentableException) File(java.io.File)

Example 80 with JWT

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

the class BalcaojusServlet method invoke.

@Override
public void invoke(SwaggerContext context) throws Exception {
    try {
        if (!context.getAction().getClass().isAnnotationPresent(AcessoPublico.class)) {
            try {
                principal.set(AutenticarPost.assertUsuario());
            } catch (Exception e) {
                if (!context.getAction().getClass().isAnnotationPresent(AcessoPublicoEPrivado.class))
                    throw e;
            }
            if (principal.get() != null) {
                Map<String, Object> decodedToken = AutenticarPost.assertUsuarioAutorizado();
                final long now = System.currentTimeMillis() / 1000L;
                if ((Integer) decodedToken.get("exp") < now + JWT_AUTH_COOKIE_TIME_TO_RENEW_IN_S) {
                    // Seria bom incluir o attributo HttpOnly
                    String tokenNew = AutenticarPost.renew();
                    Cookie cookie = AutenticarPost.buildCookie(tokenNew);
                    context.getResponse().addCookie(cookie);
                }
            }
        }
        super.invoke(context);
    } catch (AcessoProibidoException e) {
        AutenticarPost.informarProibido(context.getResponse(), e);
        return;
    } catch (JWTVerifyException e) {
        if ("jwt expired".equals(e.getMessage()))
            AutenticarPost.informarNaoAutenticado(context.getResponse(), e);
        else
            throw new RuntimeException(e);
    } catch (AcessoInvalidoException e) {
        AutenticarPost.informarNaoAutenticado(context.getResponse(), e);
        return;
    } finally {
        principal.remove();
    }
}
Also used : Cookie(javax.servlet.http.Cookie) AcessoProibidoException(br.jus.trf2.balcaojus.util.AcessoProibidoException) AcessoInvalidoException(br.jus.trf2.balcaojus.util.AcessoInvalidoException) JWTVerifyException(com.auth0.jwt.JWTVerifyException) AcessoPublico(br.jus.trf2.balcaojus.util.AcessoPublico) ServletException(javax.servlet.ServletException) AcessoInvalidoException(br.jus.trf2.balcaojus.util.AcessoInvalidoException) JWTVerifyException(com.auth0.jwt.JWTVerifyException) AcessoProibidoException(br.jus.trf2.balcaojus.util.AcessoProibidoException)

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