Home > Blockchain >  Provide security in Spring
Provide security in Spring

Time:01-23

I am developing a basic crud web app in react and spring. I am Testing with postman, as frontend is not ready yet. I have this method, but i just discovered that anybody knows the id can send a HTTP request and get all data.

@PostMapping("/utente")
public ResponseEntity<Object> getDatiProfiloUtente(@RequestBody final Long idUtente){
        HashMap<String, Object> map = new HashMap<>();

        Paziente paziente = service.findPazienteById(idUtente);
        map.put("nome", paziente.getNome());
        map.put("cognome", paziente.getCognome());
        map.put("email", paziente.getEmail());
        map.put("nTelefono", paziente.getNumeroTelefono());
        map.put("emailCaregiver", paziente.getEmailCaregiver());
        map.put("nomeCaregiver", paziente.getNomeCaregiver());
        map.put("cognomeCaregiver", paziente.getCognomeCaregiver());
            
        return new ResponseEntity<>(map, HttpStatus.OK);
    }

How can I provide security? I want that only the logged user can see his data.

CodePudding user response:

You want to use the @Secured annotation provided by spring security, this article by baeldung is a great resource and explains exactly how to set up the method security you need.

CodePudding user response:

You must use @EnableWebSecurity annotation. Spring boot provides great support for security. Spring can integrate with various third-party security applications as well as provide simple in-memory security.

Here in the original documentation there is a security implementation for a simple memory. I highly recommend you review it. https://docs.spring.io/spring-security/site/docs/4.0.x/apidocs/org/springframework/security/config/annotation/web/configuration/EnableWebSecurity.html

However, in-memory management is often not useful. Instead, you may want to keep your user information in a database or in a different application.

Other than that, the best practice for Rest is to use jwt tokens. You might want to take a look at this example of how you can use it with Spring Boot. https://www.javainuse.com/spring/boot-jwt

  • Related