【问题标题】:Send authorization request from React to Spring REST从 React 向 Spring REST 发送授权请求
【发布时间】:2020-03-29 23:37:02
【问题描述】:

我正在尝试使用使用 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 => {
...

提前致谢

【问题讨论】:

  • Remove httpBasic 与 formLogin 相矛盾,那么我建议使用简单的 html 表单帖子进行登录,因为 Spring Security 的行为,它有一个登录后重定向的配置:.loginPage("/login") .permitAll().loginProcessingUrl("/loginCheck").usernameParameter("username").passwordParameter("password").defaultSuccessUrl("/welcome")

标签: reactjs spring rest


【解决方案1】:

你必须像这样在configure方法中给出login.html页面。

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

参考这个link

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

【讨论】:

    猜你喜欢
    • 2023-03-11
    • 2020-08-16
    • 2020-07-05
    • 2020-03-13
    • 1970-01-01
    • 1970-01-01
    • 2021-07-24
    • 1970-01-01
    • 2019-11-18
    相关资源
    最近更新 更多