从react js应用程序中认证和访问spring安全保护的API



我的目标是在认证后从react js应用程序访问spring安全保护的API。

  • Spring引导程序托管在http://myserver:8080
  • React JS应用程序托管在http://myserver:3000

我可以使用curl验证和访问api,如下所示:

  1. 使用凭据访问登录url。从响应头中提取jsessionid令牌
  2. jsessionid token的访问端url
$ curl -i -X POST login_url --data 'username=myusername&password=mypassword'
$ curl end_url -H 'Cookie: JSESSIONID=session_token'

我正试图通过React JS应用程序复制相同的

  • 即使JSESSIONID Cookie存在于响应头中(通过curl和浏览器开发工具验证),但axios响应头无法捕获它

  • 我明白"Set-Cookie"默认情况下,JavaScript代码中的header不起作用。正如这个问题所讨论的React Axios,不能读取Axios响应的Set-Cookie头

  • 请帮助修改所需的代码来实现相同的。或建议其他方法来达到目标。谢谢。

客户端代码如下:

const onSubmitAuthenticateButton = (e) => {
e.preventDefault();
const loginUrl = 'http://myserver:8080/login';
axios.defaults.withCredentials = true;
axios.post(loginUrl, { username, password})
.then(res => console.log(res.headers))
.catch(err => console.log(err.message));
}

在Spring security配置中,csrf被禁用,并为"http://myserver:3000"设置允许的origin。

<<p>WebSecurityConfig类/strong>
@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter{
private CustomAuthenticationProvider customAuthProvider;
public WebSecurityConfig(CustomAuthenticationProvider customAuthProvider) {
super();
this.customAuthProvider = customAuthProvider;
}

@Override
protected void configure(HttpSecurity http) throws Exception {
http
.cors()
.and()
.csrf().disable()
.authorizeRequests()
.anyRequest().fullyAuthenticated()
.and()
.formLogin();           
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.authenticationProvider(customAuthProvider);
}
}
<<p>WebMvcConfig类/strong>
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
private final long MAX_AGE_SECS = 3600;
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("http://myserver:3000")
.allowedMethods("GET", "POST")
.exposedHeaders("Set-Cookie")
.maxAge(MAX_AGE_SECS)
.allowCredentials(true);       
}
}

我通过另一种方式达到了目的。代替基于会话的身份验证,我现在使用无状态身份验证。身份验证成功后,将返回一个jwt令牌作为响应。随后的API调用,jwt令牌作为有效负载附加。应用程序在处理API调用请求之前检查令牌的有效性。

最新更新