使用http.csrf()时,Principal在控制器中为空.disable()

时间:2018-03-26 01:03:53

标签: spring spring-boot spring-security

我有一个我想测试的控制器和POJO。 REST接口的GET强制登录并返回主体对象,因此一切都很好。我能够将WebSecurityConfigurerAdapter扩展为启用以及用于测试的用户名和密码。

但是,在测试期间,Spring框架需要一个POST请求的CSRF令牌。由于我没有UI,我只测试REST接口,我想暂时禁用它。

所以我根据文档扩展了WebSecurityConfigurerAdapter

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

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

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable();    
    }
}

但是这会禁用身份验证。我的控制器收到Principal null对象。这是我的控制器:

import java.security.Principal;

import org.springframework.context.annotation.Scope;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.neutech.model.ShoppingCart;

@Scope("session")
@RestController
@RequestMapping("/cart/api/v1")
public class SomeController {

    @RequestMapping(value = "/thing", method = RequestMethod.POST)
    public void create(@RequestBody String stuff,@AuthenticationPrincipal Principal user) {

         // do stuff
}

我尝试过为特定URL或HTTP谓词设置CSRF的各种方法。都具有相同的结果。交付给控制器的委托人是null

在网上搜索某种解决方法之后我就什么也得不到了。有很多例子告诉我要做我正在做的事情。但是我只发现其他类似的问题。

有人可以向我解释我做错了吗?

2 个答案:

答案 0 :(得分:1)

要启用身份验证更改配置方法,请尝试以下操作:

       http
            .csrf().disable()
            .authorizeRequests()
            .anyRequest()
            .fullyAuthenticated();

答案 1 :(得分:0)

如果您使用Spring Boot 1.5,则可以按属性禁用CSRF,请参阅 Spring Boot Reference Guide

security.enable-csrf=false # Enable Cross Site Request Forgery support.

如果您使用Spring Boot 2.0,则必须编写完整的Spring Security配置,请参阅Spring Boot Security 2.0

  

自定义安全性

     

如果要为应用程序配置自定义安全性,则需要添加WebSecurityConfigurerAdapter,以添加要配置的所有位。为了避免WebSecurityConfigurerAdapter的排序问题,Spring Boot自动配置将完全退回。

示例:

@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
                .anyRequest().authenticated()
                .and()
            .formLogin()
                .and()
            .csrf().disable()
    }
}
相关问题