【发布时间】: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")