Home > database >  Basic Authentication on REST service with Spring Boot
Basic Authentication on REST service with Spring Boot

Time:12-20

Developed a simple REST end point , using Spring boot, ( latest version) . used :

<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
</dependency>

and changed user name and password in applicaion.properties file.

spring.security.user.name=user
spring.security.user.password=password

That is all. Able to communicate to GET end point that returns a simple "hello" string.I received expected result.

 @GetMapping (value = "/all")
    @ResponseStatus(HttpStatus.CREATED)
    @ResponseBody
    ResponseEntity<String> all() {
    return  ResponseEntity.ok("customer") ;
    }

I make a call using POSTMAN, in settings , added ( Basic Auth, and added user name and password as per my application settings. Here is an example from postman:


curl --location --request GET 'http://localhost:8080/all' \
--header 'Authorization: Basic dXNlcjpwYXNzd29yZA==' \
--header 'Cookie: JSESSIONID=F6311C2062385978CE173C4A11E0D74D'

RESPONSE: OK, 200.

Now I am making a call to a post method:

    @ResponseStatus(HttpStatus.CREATED)
    @ResponseBody
    ResponseEntity<Customer> addCustomer(@Valid @RequestBody CustomerDTO customerDTO) {
        Customer customer = mapper.toCustomer(customerDTO);
        customerRepository.save(customer);
        return ResponseEntity.ok(customer);
    }

So the call to the post method fails, attached a call from postman:

curl --location --request POST 'http://localhost:8080/addAccount' \
--header 'If-None-Match: "version1"' \
--header 'Content-Type: application/json' \
--header 'Cookie: JSESSIONID=9AE7806055797DF85021C70951AD826B' \
--data-raw '{
    "accountNumber":1,
    "customer":
     {
    "id": 1,
    "forename": "mynam",
    "surname": "surname",
    "dateOfBirth": "2011-11-11T00:00:00.000 00:00",
    "accounts": null
}
}'

Receive 401 error.

All works fine if I remove Basic Authentication and make a plain call, to POST method. What is that I am doing wrong ? where shall I start digging?

--

CodePudding user response:

The problem is that when you use spring spring-boot-starter-security it enables crsf protection by default. To solve the issue temporary you can use this configuration. Note that csrf is enabled for POST.

If you want to learn more about csrf you can check https://docs.spring.io/spring-security/site/docs/5.0.x/reference/html/csrf.html .

public class SecurityConfig {

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity request) throws Exception{
         request.csrf().disable();
                 return request.build();
    }
}
  • Related