首页 > 解决方案 > 使用 Spring Security 后 $http 请求给出 403?

问题描述

下面是我正在使用的 SecurityConfiguration 类。

@SpringBootApplication
@RestController
public class WebMvcConfig {
@Configuration
protected static class SecurityConfiguration extends 
WebSecurityConfigurerAdapter {

  @Override
  protected void configure(HttpSecurity http) throws Exception {


  http.authorizeRequests()
  .antMatchers("/login").permitAll()
  .antMatchers("/**").authenticated()
  .anyRequest().authenticated()
  .and()
  .formLogin().permitAll();
  }
}

启动后,只要我点击我的 URL(http://localhost:8080/TestApp/),它就会带我进入默认登录页面,当我输入默认用户 ID(用户)和密码(打印在控制台上) ,它通过我的 AngularJS 路由将我带到由“/” URL 映射的 index.html 页面。我可以浏览 UI,但是只要我提交任何 $http 请求(我正在尝试使用 POST 请求),它就会在浏览器控制台上使用我的 $http 请求 URL 给我 403。

有人可以帮忙吗?

标签: javaangularjsspring-securityhttp-headershttp-post

解决方案


错误 403表示您被禁止访问所有资源。

如果您检查错误详细信息,您很可能会收到一条消息,例如Expected CSRF token not found.

从 v4 开始,spring security默认启用csrf保护。这是一种很好的做法,因为csrf攻击会迫使最终用户在当前经过身份验证的 Web 应用程序上执行不需要的操作。

因此,在开发环境中,添加http.csrf().disable();将解决您的问题。csrf但是当你想移动到 prod 环境时, 你应该考虑添加一个令牌。


推荐阅读