How to create a "Main" in an application that consumes a REST service that has all the entities in the system?

Asked

Viewed 644 times

8

I am with the following web application created initially for and web using Spring Boot, Spring Security and Thymeleaf (authentication and authorization).

I did a REST job and separated the front-end in another application that consumes services through RestTemplate. Every application is using JWT and Spring Security for authentication and authorization. I did several tests with Postman and everything is ok.

The problem is I can’t ride the login in the client application for not knowing how to create Main, because it is in the same application and not in a remote server.

  • How to create my controller for login specifically?

    • Before I could use the Userdetail and the Userdetailservice and it was very simple

    • But now I’m gonna need credentials on all the requisitions

  • How can I capture the logged-in user in the client application to handle their permissions to access the pages and their contents that are already configured with Thymeleleaf and Spring Security?

  • Where to find an example of a Spring Boot application consuming a REST API by logging in to access other features?

In the client project I am doing so to get the token:

@SpringBootApplication
public class DemoApplication implements CommandLineRunner {

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }

    @Override
    public void run(String... args) throws Exception {
        String token = fazerLogin();
        RestTemplate restTemplate = new RestTemplate();
        String url = "http://localhost:8080/usuario/perfil/155";
        Map<String, String> param2 = new HashMap();
        param2.put("Authorization", "Bearer " + token);
        HttpHeaders headers = new HttpHeaders();
        headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));
        headers.set("Authorization", "Bearer " + token);
        HttpEntity<String> entity = new HttpEntity<>(null, headers);
        ResponseEntity<String> usuarioLogado;
        usuarioLogado = restTemplate.exchange(url, HttpMethod.GET, entity, String.class);
        System.out.println("Usuario Logado =>" + usuarioLogado);
    }

    private String fazerLogin() throws RestClientException {
        Map<String, String> param = new HashMap();
        param.put("email", "[email protected]");
        param.put("senha", "123");
        RestTemplate restTemplate = new RestTemplate();
        String url = "http://localhost:8080/login";
        ResponseEntity<String> response;
        response = restTemplate.postForEntity(url, param, String.class);
        String leitura = response.toString().substring(21, 195);
        System.out.println("Leitura  =>" + leitura);
        String token = leitura.substring(7, 174);
        System.out.println("Token  =>" + token);
        return token;
    }
}

I read that one article interesting, but does not have the whole application, only small snippets.

3 answers

0

I didn’t quite understand about which application you used on the front, that front is what?

Web page, application page?

I will assume that you have a web front-end application (HTML, CSS and Javascript), a client of your main service that is in Java and the Java service that you use Spring Security, blz, if I’m wrong mentions there with more details for me try to help.

Login

After logging in, you will receive JWT.

On the JWT payload, you can store some information you will need from the logged in user.

Example:

  {
    "aud": [
    "restservice"
    ],
    "updatePassword": false,
    "user_name": "[email protected]",
    "scope": [
      "all"
    ],
    "name": "Andre",
    "id": "{id}",
    "exp": 1622294739,
    "authorities": [
      "ROLE_CRIAR_USUARIOS",
      "ROLE_EDITAR_USUARIOS",
      "ROLE_INATIVAR_USUARIOS",
      "ROLE_VISUALIZAR_USUARIOS"
    ],
    "jti": "22b37833-238d-46c0-9429-36cdb8c39341",
    "client_id": "client"
  }

Parse JWT to Payload

If you want to parse the payload and read the data just implement the following function:

 sys.parseJwt = function (token) {
    var base64Url = token.split('.')[1];
    var base64 = base64Url.replace(/-/g, '+').replace(/_/g, '/');
    var jsonPayload = decodeURIComponent(atob(base64).split('').map(function (c) {
        return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);
    }).join(''));

    return JSON.parse(jsonPayload);
};

and then call using

  var payload = sys.parseJwt(jwt);

Save and use for later requests

To do this change the login structure in the back end, creating a method that logs in and if successful returns JWT.

On the front, after the return of JWT save it to the local Storage

 sessionStorage.setItem('token', res.jwt);

and in later requests, add to header.

const jwt = sessionStorage.getItem('token');
xhr.setRequestHeader('Authorization', 'Bearer ' + jwt);

0

Hello. If I didn’t get it wrong, you are simply trying to create the authentication layer in your frontend and thus generate a valid token to consume the API. The main one is a single user created on the server side responsible for the session. When authenticating it should be created. A good example I can give you is to have a Single Sign-on service. An entry point that controls who and what you access. One example feature I’ve used and recommend is Keycloak. With it you create user, profiles and other access characteristics to your application. Here you can find a good example using a spring boot application https://www.baeldung.com/spring-boot-keycloak

I hope I’ve helped.

-1

Supplemented by what was answered, along the lines of the above technologies - and with the standard Oauth2 configuration (without dependency on a specific IDP library) - you can, in Websecurityconfigureradapter, define extractors for Principal and Authorities, who can handle data forwarded by Keycloak or your favorite IDP.

Behold here an explanation, and at this link an example.

Browser other questions tagged

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