【发布时间】:2019-03-10 07:56:32
【问题描述】:
为了快速开发前端(React)在端口 3000 上工作。
CORS 请求运行良好。
我遇到了来自前端的身份验证问题:
- 小问题1是8080端口重定向
- 大问题2,认证成功但在8080端口
我只是在运行 react frontend.localhost:3000 时无法成功验证。
不使用 Spring-mvc。
服务器成功的 wenn 前端也在 8080 端口上。
HTTP/1.1 302
Set-Cookie: JSESSIONID=8AA9C90B5599372059183C6D94798609; Path=/; HttpOnly
X-Content-Type-Options: nosniff
X-XSS-Protection: 1; mode=block
Cache-Control: no-cache, no-store, max-age=0, must-revalidate
Pragma: no-cache
Expires: 0
X-Frame-Options: DENY
Location: http://localhost:8080/
Content-Length: 0
Date: Fri, 05 Oct 2018 17:26:41 GMT
3000 端口上的服务器失败响应 wenn 前端。
HTTP/1.1 302
X-Content-Type-Options: nosniff
X-XSS-Protection: 1; mode=block
Cache-Control: no-cache, no-store, max-age=0, must-revalidate
Pragma: no-cache
Expires: 0
X-Frame-Options: DENY
Set-Cookie: JSESSIONID=6AE3EA77D7786281DE5F2E9FE2EC2A31; Path=/; HttpOnly
Location: http://localhost:8080/
Content-Length: 0
Date: Fri, 05 Oct 2018 17:30:53 GMT
###附加: 所以自己找解决办法。 3天5行代码*( 修复重定向问题:
<code>
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
//allow not authenticated user access to login page
.antMatchers("/login").permitAll()
//give access all users to React resources
.antMatchers("/static/**").permitAll()
.anyRequest().authenticated()
//enable redirect to login if user not authenticated
.and().formLogin().successHandler(corsAuthSuccessHandler()).loginPage("/login")
.and().csrf().disable();
}
@Bean
public AuthenticationSuccessHandler corsAuthSuccessHandler() {
return new SimpleUrlAuthenticationSuccessHandler() {
@Override
protected String determineTargetUrl(HttpServletRequest request,HttpServletResponse response) {
if (request.getHeader("Origin").equals(frontEndDevDomain))
return request.getHeader("Origin");
return super.determineTargetUrl(request, response);
}
};
//Cors header allover:
@Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurer() {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins(frontEndDevDomain)
.allowCredentials(true);
}
};
}
</code>
从前端登录后,每个请求都将是 CORS,如果您使用 fetch,只需添加行凭据:'include'
例如: fetch(URL + '/api/company/add/?name=' + name, {method: 'POST', credentials: 'include'})
【问题讨论】:
-
您能更具体地谈谈您面临的问题吗?你在使用 Spring MVC 和 Spring Boot 吗?您如何进行身份验证以及您的后端如何响应?
-
当然。我刚刚添加了规范。
-
这里有什么问题?
-
@HasanCanSaral 如果后端不能与其他端口上的前端一起工作(即身份验证),如何设置项目开发?构建前端重新启动后端非常耗时。
-
@HasanCanSaral 除了身份验证之外它运行良好。
标签: spring spring-boot authentication spring-security development-environment