所以我们在编程方面还很陌生,我们正在做一个项目,其中后端使用 Spring Security,前端将使用 React。我一直在尝试将带有用户名和密码的 POST 发送到 Spring Security,但我被卡住了,我得到的唯一返回是 401 和 404。
我不希望 Spring Security 呈现登录页面,我只想能够 POST 和接收 Session,最后返回 Csrf 和 userId。
@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)
Postman 将返回整个 html 表单。
如果我们查看您的配置,它会告诉我们以下内容:
.antMatchers( "/api/user/login", "/login").permitAll()
我们已允许对端点 /api/user/login
和 /login
的所有请求。
我不知道你在这里做什么,因为你没有发布 restAuthEntryPoint
的代码。
.exceptionHandling().authenticationEntryPoint(restAuthEntryPoint)
这里:
.loginProcessingUrl("/api/user/login")
您正在定义您使用的任何登录表单,如果它是 spring 默认表单,或者您在 react 中自定义编写的表单,都将 FORM POST
登录信息到这个定义的端点。
如果您不想让 spring 为您提供登录页面,我建议您不要在 permittAll
页面上/login
。我不知道您将如何托管您的应用程序,如果 Spring 服务器将在同一主机上为您的 React 应用程序提供服务,或者您是否要在不同的服务器上托管应用程序和后端。
在您的 React 应用程序中,如果您想使用默认值登录,您可以向 FORM POST
和 /api/user/login
一个 json 帖子发出 NOT
请求。包含两个字段 username
和 password
。如果成功,您将获得一个 SESSION
cookie。
我建议您阅读 official spring security documentation on form login 以了解流程的工作原理。实际上还有更多内容,然后我已经在这里解释了。