【发布时间】:2021-11-09 13:21:13
【问题描述】:
我的目标是在身份验证后从 React js 应用程序访问受 Spring Security 保护的 API。
- Spring Boot 应用程序托管在 http://myserver:8080
- React JS 应用程序托管在 http://myserver:3000
我能够使用 curl 进行身份验证和访问 API,如下所示:
- 使用凭据访问登录 URL。从响应头中提取 jsessionid 令牌。
- 使用 jsessionid 令牌访问结束 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 响应头无法捕获它。
-
我了解 JavaScript 代码中的“Set-Cookie”标头在默认情况下不起作用。正如这个问题所讨论的React Axios, Can't read the Set-Cookie header on axios response
-
请帮助修改代码以实现相同的目的。或建议实现目标的替代方法。 谢谢。
客户端代码如下:
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 Secuirty 配置中,csrf 被禁用,并且 cors 允许“http://myserver:3000”的来源。
WebSecurityConfig 类
@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);
}
}
WebMvcConfig 类
@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);
}
}
【问题讨论】:
标签: reactjs cookies spring-security axios