【发布时间】:2019-12-26 11:19:54
【问题描述】:
我有一个在单独的端口 (localhost:3000) 上运行的 react 应用程序,我想用它来验证用户身份,目前我有一个代理设置到我的 Spring 后端 (localhost:8080)。
我是否可以通过向我的后端发送 POST 请求并取回会话 cookie 然后在每个请求中包含该 cookie 以某种方式手动验证而不是 http.httpBasic()?它还将简化 iOS 端的身份验证过程(使用此过程,我只能将会话 cookie 值存储在钥匙串中,并将其与对我的 api 的每个请求一起传递)
如何为非浏览器请求禁用 csrf?
有没有更好的方法来解决这个问题?浏览器和移动身份验证的不同路径?
{
"username": "user",
"password": "12345678"
}
在spring控制器中处理请求
@PostMapping(path = "/web")
public String authenticateUser() {
//Receive the auth data here... and perform auth
//Send back session cookie
return "Success?";
}
我的 WebSecurityConfigurerAdapter.java
@Configuration
@EnableWebSecurity
public class WebsecurityConfig extends WebSecurityConfigurerAdapter {
private final DetailService detailService;
public WebsecurityConfig(DetailService detailService) {
this.detailService = detailService;
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(detailService).passwordEncoder(passwordEncoder());
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.httpBasic().disable()
.authorizeRequests()
.antMatchers(HttpMethod.POST,"/api/v1/authenticate/new").permitAll()
.antMatchers(HttpMethod.POST,"/api/v1/authenticate/web").permitAll()
.anyRequest().authenticated();
}
@Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurer() {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**").allowedMethods("GET", "POST").allowedOrigins("http://localhost:8080");
}
};
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder(14);
}
}
【问题讨论】:
-
我认为对于非浏览器客户端,您可以实现基于 Spring 安全令牌的身份验证机制。 stackoverflow.com/questions/17126201/…
-
您可以通过 JWT 使用基于令牌的机制。 stackoverflow.com/questions/49325692/…
-
@ShanmugaSundaramN JWT 不适用于会话
标签: java spring spring-security