【问题标题】:Spring security request bodySpring 安全请求正文
【发布时间】:2020-07-16 13:28:44
【问题描述】:

我正在使用带有弹簧安全性的弹簧靴

我有休息控制器

    @RequestMapping("/foo")
    public String foo(@RequestBody Foo foo) {
        return foo.getBar();
    }

我已经为这个端点添加了 Spring 安全性

.mvcMatchers("/foo").access("@securityChecker.check(#foo)")

现在我有了这个安全检查器

@Service
public class SecurityChecker {
    public boolean check(Foo foo) {
        return foo != null;
    }
}

问题是 Foo 总是为空。

我猜这是因为 Jackson 的过滤器在 Security one 之后。有没有办法在不将 HttpRequest 对象注入“检查”方法和解析请求正文的情况下获取请求正文对象?从请求的正文中解析 JSON 后,我可能希望进行安全检查。

这是我正在尝试做的快速示例: https://github.com/kedrigen/spring-security-request-body

【问题讨论】:

    标签: spring-boot spring-security jackson


    【解决方案1】:

    你错过了@RequestBody (docs):

    @PostMapping("/foo") // has to be post mapping
    public String foo(@RequestBody Foo foo) {
        return foo.getBar();
    }
    

    此注解用于通过HttpMessageConverter 读取请求正文并将其反序列化为对象。

    你也少了@EnableWebSecurity:

    @Configuration
    @EnableWebSecurity
    public class SecurityConfig extends WebSecurityConfigurerAdapter { ... }
    

    但总的来说,问题是你不能简单地做你想做的事。

    您期望在控制器中出现的foo 与安全和安全上下文无关,所以这个"@securityChecker.check(#foo)" 不起作用。

    考虑熟悉Referring to Beans in Web Security Expressions 文档。

    文档中的示例:

    public class WebSecurity {
      public boolean check(Authentication authentication, HttpServletRequest request) {
           ...
      }
    }
    
    
    http
    .authorizeRequests(authorize -> authorize
        .antMatchers("/user/**").access("@webSecurity.check(authentication,request)")
        ...
    )
    

    简而言之:这是可行的,因为 Spring 知道 authentication 和 request 是什么,并且它们存在于上下文中。但是foo 对 Spring 没有任何意义:)

    【讨论】:

    • 在示例中忘记了这一点。我在真正的应用程序上有这个,没有帮助。
    • @GrzegorzKapcia 在查看您在 GitHub 上的代码后,我更新了我的答案。
    • 好吧,我想知道我是否可以在不自己解析来自 http 请求的请求正文的情况下做到这一点。正如我之前所说,注入请求的示例完美运行。无论如何感谢您的帮助:)
    猜你喜欢
    • 2016-01-15
    • 1970-01-01
    • 2021-06-23
    • 2012-09-10
    • 2018-07-18
    • 1970-01-01
    • 2020-10-18
    • 1970-01-01
    • 2013-05-25
    相关资源
    最近更新 更多