JWT IN JAVA (SPRING BOOT)?

Asked

Viewed 175 times

2

I’m doing a project, where I have a login. Front-end use in Reactjs, and backend in Java. But I don’t know how to make a java JWT token so that the front end can be successfully logged in.

I read this tutorial https://developer.okta.com/blog/2018/10/31/jwts-with-java, I downloaded it and read it. But I’m still struggling to understand how to adapt to my code!

Here is my code that returns the login (company, user and password)

@RequestMapping(value = "/login", method = RequestMethod.POST)
public String Login(@ModelAttribute("empresa") String empresa, 
                    @ModelAttribute("usuario") String usuario,
                    @ModelAttribute("senha") String senha,ModelMap map) throws SQLException {

    ArrayList<String> list = new ArrayList<>();
    System.out.println("PRINTAR O USUARIO >>>"+usuario);
    System.out.println(senha);

    if (usuario.equals("veronica") && senha.equals("123456")) {
        list.add("Sucesso" + usuario);
    } else if (usuario.equals("camila") && senha.equals("123456")) {
        list.add("Sucesso" + usuario);
    } else if (usuario.equals("jose") && senha.equals("123456")) {
        list.add("Sucesso" + usuario);
    } else {
       list.add("Falha no login para a empresa " + empresa + " (usuario ou senha não conferem)");
    }

    Gson gson = new Gson();
    String jsonArray = gson.toJson(list);

    map.addAttribute("lists", jsonArray);
    return "main";
}

1 answer

1


First you must choose a lib for JWT token generation, you can find several to choose from here.

For this example I will use the jjwt, chose this version:

<dependency>
    <groupId>io.jsonwebtoken</groupId>
    <artifactId>jjwt</artifactId>
    <version>0.9.0</version>
</dependency>

You need 3 things to generate your token:

  1. Content to add in token
  2. A secret and an algorithm to sign and validate the token
  3. The expiry date of the token (actually this is optional but it does harm to put is not even?)

You can add some other details to the token as well specification of the JWT.

Talk is Cheap, show me the code!

public static void main(String[] args) {
    final String secret = "m3u_s3gr3d0_s3cr3t0"; // Secret para verificação da assinatura do JWT
    final String tokenContent = "[email protected]"; // Conteúdo a ser incluído no JWT
    final Long daysToExpire = 7L;
    final Date expirationDate = Date.from(LocalDateTime.now().plusDays(daysToExpire).atZone(ZoneOffset.systemDefault()).toInstant()); // O token irá expirar daqui 7 dias

    String token = Jwts.builder()
                        .setSubject(tokenContent)
                        .setExpiration(expirationDate)
                        .signWith(SignatureAlgorithm.HS512, secret)
                        .compact();

    System.out.println(token); // Imprime o token


    String user = Jwts.parser()
                        .setSigningKey(secret)
                        .parseClaimsJws(token)
                        .getBody()
                        .getSubject();

    System.out.println(user); // Imprime [email protected]
}

In this example the output on my console is this:

eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJtZXVlbWFpbEBlbWFpbC5jb20iLCJleHAiOjE1NjQwMDgxODB9.cAt3iTW8LdR2Mmz2KMhMSZwQVhfj9zi-JY29LPToWNXDbQC83IkW4rpXLS60Rs-qqbr-x5lFDpamxELRjblKtA
[email protected]

For JWT verification, you should always have the secret in hand, in this example we can validate until the jwt.io:

inserir a descrição da imagem aqui

There are a multitude of signature algorithms, even using public and private keys.

The idea then would be then your back-end always validate the token to each request, passing it via header for example (which is the idea of the bearer token)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.