首页 > 解决方案 > 从 React 向 Spring REST 发送授权请求

问题描述

我正在尝试使用使用 spring boot 构建并配置了 spring security 的 rest api 来验证 react 应用程序。

目前,即使使用正确的用户凭据,我也会收到 302 错误。

“/login”是发布请求身份验证信息的正确默认 URL 吗?
此外,我是否只需将 csrf 令牌添加到标头并将用户名/密码添加到发布请求正文?

安全配置如下所示:

@Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth
            .userDetailsService(this.userDetailsService)
            .passwordEncoder(User.PASSWORD_ENCODER);

    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        final CookieCsrfTokenRepository tokenRepository = new CookieCsrfTokenRepository();

        http
            .authorizeRequests()
            .antMatchers("/")
            .permitAll()
            .antMatchers("/api/**").authenticated()
            .and()
            .formLogin()
            .permitAll()
            .and()
            .httpBasic()
            .and()
            .logout()
            .logoutSuccessUrl("/")
            .and()
            .csrf()
            .csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse());
    }

我的帖子是这样的:

...
const data = { 
            userName: this.state.userName,
            password: this.state.password
        };

        fetch('http://localhost:8080/login', {
            method: 'POST',
            headers: {
                'X-XSRF-TOKEN': cookies.get("XSRF-TOKEN")},
            body: JSON.stringify(data),
        }).then(response => {
...

提前致谢

标签: reactjsspringrest

解决方案


您必须像这样在配置方法中提供 login.html 页面。

.formLogin()
    .loginPage("/login.html").permitAll();

参考这个链接

希望这能解决你的问题:)


推荐阅读