Reactjs 从Postman登录到Spring Security

Reactjs 从Postman登录到Spring Security,reactjs,authentication,post,spring-security,postman,Reactjs,Authentication,Post,Spring Security,Postman,因此,我们在编程方面是非常新的,我们正在做一个项目,在这个项目中,我们的后端使用SpringSecurity,前端将使用React。我一直试图用用户名和密码向Spring Security发送帖子,但我被卡住了,我得到的唯一回报是401和404 我不希望SpringSecurity呈现一个登录页面,我只希望能够发布和接收一个会话,并最终返回Csrf和用户ID @Configuration @EnableWebSecurity @EnableGlobalMethodSecurity(prePost

因此,我们在编程方面是非常新的,我们正在做一个项目,在这个项目中,我们的后端使用SpringSecurity,前端将使用React。我一直试图用用户名和密码向Spring Security发送帖子,但我被卡住了,我得到的唯一回报是401和404

我不希望SpringSecurity呈现一个登录页面,我只希望能够发布和接收一个会话,并最终返回Csrf和用户ID

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

    private final PasswordEncoder passwordEncoder;
    private final UserDetailsService userDetailsService;
    private final RestAuthEntryPoint restAuthEntryPoint;

    @Autowired
    public SecurityConfig(PasswordEncoder passwordEncoder, UserDetailsService userDetailsService, RestAuthEntryPoint restAuthEntryPoint) {
        this.passwordEncoder = passwordEncoder;
        this.userDetailsService = userDetailsService;
        this.restAuthEntryPoint = restAuthEntryPoint;
    }

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

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .csrf().disable()
                .authorizeRequests()
                .antMatchers( "/api/user/login", "/login").permitAll()
                .anyRequest()
                .authenticated()
                .and()
                .exceptionHandling().authenticationEntryPoint(restAuthEntryPoint).and()
                .formLogin()
                .loginProcessingUrl("/api/user/login");

    }
我注意到,如果我删除:

.exceptionHandling().authenticationEntryPoint(restAuthEntryPoint)
邮递员将返回整个html表单


如果我们查看您的配置,它会告诉我们以下信息:

.antMatchers( "/api/user/login", "/login").permitAll()
我们已允许对端点
/api/user/login
/login
的所有请求

我不知道你在这里做什么,因为你没有发布
restAuthEntryPoint
的代码

.exceptionHandling().authenticationEntryPoint(restAuthEntryPoint)
在这里:

.loginProcessingUrl("/api/user/login")
您正在定义您使用的任何登录表单,如果是spring默认表单,或者您在react中自定义编写的表单,都将
form POST
将登录信息发送到此定义的端点

如果您不想让spring为您提供登录页面,我建议您不要在
/login
页面上使用
许可证。我不知道您将如何托管应用程序,spring服务器是否将在同一台主机上为您的react应用程序提供服务,或者您是否将在不同的服务器上托管应用程序和后端

在react应用程序中,如果您想使用默认值登录,您可以向
/api/user/login
发出
表单POST
请求,而不是
json POST。包含两个字段:用户名和密码。如果成功,您将获得一个
会话
cookie

我建议您阅读中的,以了解流是如何工作的。事实上,我在这里解释的还有更多