使用Spring Boot(VueJS和Axios前端)时,出现了“Post 403 Forbidden”错误。

13

我一直遇到CORS问题,尝试了Stack Overflow上所有的方法以及在谷歌上找到的任何东西,但都没有运气。

因此,我在后端进行了用户身份验证,并在前端拥有登录页面。我使用Axios连接了登录页面,以便我可以进行POST请求并尝试登录,但是我一直收到“Preflight request”等错误,所以我修复了这个问题,但之后又开始出现“Post 403 Forbidden”错误。

错误信息如下:

POST http://localhost:8080/api/v1/login/ 403 (Forbidden)

尝试使用Postman登录也无法正常工作,因此显然出了些问题。以下将发布类文件

在我的后端中,我有一个名为WebSecurityConfig的类处理所有CORS相关的内容:

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private UserDetailsServiceImpl userDetailsService;

    @Bean
    public WebMvcConfigurer corsConfigurer() {
        return new WebMvcConfigurerAdapter() {
            @Override
            public void addCorsMappings(CorsRegistry registry) {
                registry.addMapping("/**")
                        .allowedMethods("GET", "POST", "HEAD", "PUT", "DELETE", "OPTIONS");
            }
        };
    }

    @Bean
    public CorsFilter corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        CorsConfiguration config = new CorsConfiguration();
        config.setAllowCredentials(true);
        config.addAllowedOrigin("*");  // TODO: lock down before deploying
        config.addAllowedHeader("*");
        config.addExposedHeader(HttpHeaders.AUTHORIZATION);
        config.addAllowedMethod("*");
        source.registerCorsConfiguration("/**", config);
        return new CorsFilter(source);
    }


    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.headers().frameOptions().disable();
        http
                .cors()
                .and()
                .csrf().disable().authorizeRequests()
                .antMatchers("/").permitAll()
                .antMatchers("/h2/**").permitAll()
                .antMatchers(HttpMethod.POST, "/api/v1/login").permitAll()
                .anyRequest().authenticated()
                .and()
                // We filter the api/login requests
                .addFilterBefore(new JWTLoginFilter("/api/v1/login", authenticationManager()),
                        UsernamePasswordAuthenticationFilter.class);
        // And filter other requests to check the presence of JWT in header
        //.addFilterBefore(new JWTAuthenticationFilter(),
        //       UsernamePasswordAuthenticationFilter.class);
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        // Create a default account
        auth.userDetailsService(userDetailsService);
//        auth.inMemoryAuthentication()
//                .withUser("admin")
//                .password("password")
//                .roles("ADMIN");
    }
}

我们的前端使用VueJS编写,使用Axios进行调用。

<script>
    import { mapActions } from 'vuex';
    import { required, username, minLength } from 'vuelidate/lib/validators';

    export default {
        data() {
            return {
                form: {
                    username: '',
                    password: ''
                },
                e1: true,
                response: ''
            }
        },
        validations: {
            form: {
                username: {
                    required
                },
                password: {
                    required
                }
            }
        },
        methods: {
            ...mapActions({
                setToken: 'setToken',
                setUser: 'setUser'
            }),
            login() {
                this.response = '';
                let req = {
                    "username": this.form.username,
                    "password": this.form.password
                };

                this.$http.post('/api/v1/login/', req)
                .then(response => {
                    if (response.status === 200) {
                        this.setToken(response.data.token);
                        this.setUser(response.data.user);

                        this.$router.push('/dashboard');
                    } else {
                        this.response = response.data.error.message;
                    }
                }, error => {
                    console.log(error);
                    this.response = 'Unable to connect to server.';
                });
            }
        }
    }
</script>

当我通过Chrome工具(网络)进行调试时,我注意到OPTIONS请求如下所示:

OPTIONS请求通过

这是POST错误的图片:

POST请求错误

这是另一个处理OPTIONS请求的类(在WebSecurityConfig中引用的JWTLoginFilter):

public class JWTLoginFilter extends AbstractAuthenticationProcessingFilter {

    public JWTLoginFilter(String url, AuthenticationManager authManager) {
        super(new AntPathRequestMatcher(url));
        setAuthenticationManager(authManager);

    }

    @Override
    public Authentication attemptAuthentication(
            HttpServletRequest req, HttpServletResponse res)
            throws AuthenticationException, IOException, ServletException {
        AccountCredentials creds = new ObjectMapper()
                .readValue(req.getInputStream(), AccountCredentials.class);
        if (CorsUtils.isPreFlightRequest(req)) {
            res.setStatus(HttpServletResponse.SC_OK);
            return null;

        }
        return getAuthenticationManager().authenticate(
                new UsernamePasswordAuthenticationToken(
                        creds.getUsername(),
                        creds.getPassword(),
                        Collections.emptyList()

                )
        );
    }

    @Override
    protected void successfulAuthentication(
            HttpServletRequest req,
            HttpServletResponse res, FilterChain chain,
            Authentication auth) throws IOException, ServletException {
        TokenAuthenticationService
                .addAuthentication(res, auth.getName());
    }
}
4个回答

10
当你配置 Axios 时,只需一次指定头部即可:
import axios from "axios";

const CSRF_TOKEN = document.cookie.match(new RegExp(`XSRF-TOKEN=([^;]+)`))[1];
const instance = axios.create({
  headers: { "X-XSRF-TOKEN": CSRF_TOKEN }
});
export const AXIOS = instance;

假设您使用SpringBoot 2.0.0,而在SpringBoot 1.4.x之后也可以工作,那么在您的Spring Boot应用程序中,您应该添加以下安全配置。

@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            // CSRF Token
            .csrf()
                .csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse());
           // you can chain other configs here
    }

}

以这种方式,Spring 将返回响应中的令牌作为 cookie(我假设您首先进行 GET)并在 AXIOS 配置文件中读取它。

1
我正在使用.csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse()),但问题是这只适用于GET操作...为什么它不能用于PUT、POST和DELETE? - Andre

2

根据Spring Security文档,除非特殊情况,否则不应禁用CSRF。此代码将在VUE中设置CSRF头信息。我使用了vue-resource。

//This token is from Thymeleaf JS generation.
var csrftoken = [[${_csrf.token}]]; 

console.log('csrf - ' + csrftoken) ;

Vue.http.headers.common['X-CSRF-TOKEN'] = csrftoken;

希望这能帮到您。

1
默认情况下,Axios会正确处理X-XSRF-TOKEN。因此,唯一需要的操作是配置服务器,就像JeanValjean所解释的那样:
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            // CSRF Token
            .csrf()
                .csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse());
           // you can chain other configs here
    }

}

Axios会自动在请求头中发送正确的令牌,因此无需更改前端。

-1

我曾经遇到过同样的问题,即 GET 请求可以正常工作,但 POST 请求却返回状态码 403。

我发现这是因为默认启用了 CSRF 保护。

确认此情况的一种快速方法是禁用 CSRF:

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    // …

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

    // …

}

更多关于 Spring-Security 的信息,请访问官方网站。

请注意,禁用CSRF并不总是正确的答案,因为它存在于安全目的中。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接