【问题标题】:Spring MVC REST JSON HTTP 403Spring MVC REST JSON HTTP 403
【发布时间】:2016-08-23 13:41:12
【问题描述】:

根据文档

http://docs.spring.io/autorepo/docs/spring/4.0.x/spring-framework-reference/html/mvc.html

有十六进制方法

@Controller
@RequestMapping(value = "/pets", method = RequestMethod.POST, consumes="application/json")
public void addPet(@RequestBody Pet pet, Model model) {
    // implementation omitted
}

还有一个弹簧秒与下一个

protected void configure(HttpSecurity http) throws Exception {
        http
                .authorizeRequests()
                .antMatchers("/pets").permitAll()
                .anyRequest().authenticated()
                .and()
                .formLogin()
                .and()
                .httpBasic();
    }

通过POST插件发送请求,如

Content-Type: application/json
{"email":"test@gamil.com","pass":"testpass"}

有错误

**Status:
403: Forbidden**


Server: Apache-Coyote/1.1
X-Content-Type-Options: nosniff
X-Xss-Protection: 1; mode=block

Cache-Control: no-cache, no-store, max-age=0, must-revalidate
Pragma: no-cache
Expires: 0
X-Frame-Options: DENY

怎么了?

【问题讨论】:

  • {"email":"test@gamil.com","pass":"testpass"} 是否是用户凭据?
  • 根据spring security antMatchers("/pets").permitAll()的规则我可以​​在没有用户凭证的情况下使用这个url。是吗?
  • 是的..但默认情况下,CSRF ProtectionPOST 请求启用。因此,您应该提供一个或禁用CSRF Protection。见stackoverflow.com/a/34703521/1393484

标签: json spring spring-mvc spring-security


【解决方案1】:

以下配置仅禁用身份验证而不是 csrf 保护您的应用程序,为了解决这个问题,就像其他人在 cmets 中建议的那样,您必须为指定的端点禁用 csrf 或完全禁用 csrf保护:

// Disable for pets endpoint only
http
    .csrf()
    .ignoringAntMatchers("/pets");

// Disable everywhere
http
    .csrf()
    .disable();

或者,如果您在某些端点上确实需要csrf 保护,则必须添加一个额外的方法来获取实际的令牌值:

@RequestMapping(value = "/token", method = RequestMethod.GET)
public String getToken(HttpServletRequest request) {
    return ((CsrfToken) request.getAttribute("_csrf")).getToken();
}

获得实际令牌值后,您必须使用 X-CSRF-TOKEN 标头将其附加到所有请求中。

【讨论】:

    【解决方案2】:

    谢谢。尝试了两种选择。有用 1. http .authorizeRequests() .antMatchers("/reg").permitAll() .anyRequest().authenticated() .and() .formLogin() .and().csrf().ignoringAntMatchers("/pets") .and() .httpBasic();

    1. http.csrf().disable() .authorizeRequests() .antMatchers("/reg").permitAll() .anyRequest().authenticated() .and() .formLogin() .and() .httpBasic();

    在我看来,第一种方法更合适,因为它没有禁用 csrf。你认为什么可以 - 禁用 csrf ?

    【讨论】:

      猜你喜欢
      • 2023-04-04
      • 1970-01-01
      • 2014-08-24
      • 2015-09-19
      • 1970-01-01
      • 2016-11-13
      • 1970-01-01
      • 1970-01-01
      • 2023-03-11
      相关资源
      最近更新 更多