Spring Security with default security gives 401 for PUT and 200 for GET

thatgirlwhocodes :

I developed a spring boot application with basic security. I have two endpoints with same path and different http methods. When I include basic security with default password/with password given in application.yml, the GET api/products/{id} is authenticated and PUT api/products/{id} gives 401 unauthorized.

What is the issue with my code? Did I miss anything understanding the Spring security? Any links which I may have missed for spring security will be helpful?

My code snippets are as below,

My controller

@RestController
@RequestMapping(value = "api")
public class ProductController {

    @RequestMapping(value = "/products/{id}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<Object> getById(@PathVariable(value = "id") Integer id) {
           //Implementation

    }

    @RequestMapping(value = "/products/{id}", method = RequestMethod.PUT, consumes = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity updateById(@PathVariable(value = "id") Integer id,
                                                                   @RequestBody UpdateProductRequest updateProductRequest) {
        //Implementation
    }
}

application.yml

spring:
  security:
    user:
      name: admin
      password: admin

build.gradle dependencies

dependencies {
    implementation 'org.springframework.boot:spring-boot-starter-web'
    implementation 'org.springframework.boot:spring-boot-starter-security'
    compile group: 'org.springframework.cloud', name: 'spring-cloud-starter-openfeign', version: '2.2.0.RELEASE'
    implementation 'org.springframework.boot:spring-boot-starter-data-mongodb'

    compileOnly 'org.projectlombok:lombok'
    developmentOnly 'org.springframework.boot:spring-boot-devtools'
    annotationProcessor 'org.projectlombok:lombok'
    testImplementation('org.springframework.boot:spring-boot-starter-test') {
        exclude group: 'org.junit.vintage', module: 'junit-vintage-engine'
    }
    implementation 'junit:junit:4.12'
}

Thanks in advance

Updated with the postman screenshots: enter image description hereenter image description here

CodeWalter :

This might be a Csrf configuration issue.

You have to override WebSecurityConfigurerAdapter

Try this..

@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

  @Override
  protected void configure(HttpSecurity http) throws Exception {
    http.csrf().disable();
    http.cors();
    http.authorizeRequests().anyRequest().fullyAuthenticated();
    http.httpBasic();
  }
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=355720&siteId=1