简体   繁体   中英

Spring security - Basic auth

I'm trying to insert data using a POST request but I'm getting a 403 error. When I use GET, basic authentication works. For testing I use Fiddler.

What's the problem?

Security config:

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
                .antMatchers("/**").hasRole("USER").and()
                .httpBasic();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth)
            throws Exception {
        auth
            .inMemoryAuthentication()
                .withUser("user")
                    .password("password")
                    .roles("USER");
    }
}

Request - POST:

User-Agent: Fiddler
Host: localhost:8080
Content-Length: 200
Content-Type: application/json
Authorization: Basic dXNlcjpwYXNzd29yZA==

Request body:

{"name" : "name1",
"description" : "desc1"}

It's probably CSRF, which spring security enables by default. Look for a X-XSRF-TOKEN header in your GET request, and use that header and value in your POST.

Think twice before you do this, but you can disable csrf with

http.csrf().disable()

https://docs.spring.io/spring-security/site/docs/current/reference/html/web-app-security.html#csrf

Try this:

@Configuration
@EnableWebSecurity
public class HelloWebSecurityConfiguration
   extends WebSecurityConfigurerAdapter {

  @Autowired
  public void configureGlobal(AuthenticationManagerBuilder auth) {
    auth
      .inMemoryAuthentication()
        .withUser("user").password("password").roles("USER");
  }
}

Source: http://spring.io/blog/2013/07/03/spring-security-java-config-preview-web-security/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM