目前我遇到了新的Spring反应堆栈,并希望在Spring Session 2.0中使用反应功能 .
在传统的Servlet方法中,Spring Session提供 HttpSessionStrategy
来检测cookie或请求头中的会话 . 对于RESTful API,很容易使用 HeaderHttpSessionStrategy
来实现身份验证(默认情况下,名称为 X-AUTH-TOKEN
)等令牌 .
Spring 5核心提供 WebSessionIdResolver
为Reactive环境做同样的事情 .
但是当它与Spring Security一起使用并希望它以传统方式工作时,我无法让它工作 .
SessionConfig文件 .
@EnableSpringWebSession
public class SessionConfig {
@Bean
public ReactorSessionRepository sessionRepository() {
return new MapReactorSessionRepository(new ConcurrentHashMap<>());
}
@Bean
public WebSessionIdResolver headerWebSessionIdResolver() {
HeaderWebSessionIdResolver resolver = new HeaderWebSessionIdResolver();
resolver.setHeaderName("X-SESSION-ID");
return resolver;
}
}
部分SecurityConfig .
@EnableWebFluxSecurity
class SecurityConfig {
@Bean
SecurityWebFilterChain springWebFilterChain(HttpSecurity http) throws Exception {
return http
.authorizeExchange()
.pathMatchers(HttpMethod.GET, "/posts/**").permitAll()
.pathMatchers(HttpMethod.DELETE, "/posts/**").hasRole("ADMIN")
//.pathMatchers("/users/{user}/**").access(this::currentUserMatchesPath)
.anyExchange().authenticated()
.and()
.build();
}
一个测试休息控制器文件,它返回当前的会话ID .
@RestController
public class SessionRestController {
@GetMapping("/sessionId")
public Map<String, String> sessionId(WebSession session){
Map<String, String> map = new HashMap<>();
map.put("id", session.getId());
return map ;
}
}
当我启动应用程序并使用curl访问/ sessionId时,响应头没有会话信息 .
curl -v -u "user:password" http://localhost:8080/sessionId
我在查询结果中获得了会话ID,并将其放入请求标头中以访问受保护资源并获得401 .
curl -v -X POST -H "X-SESSION-ID:xxxx" http://localhost:8080/posts
Update :可以找到工作样本here .
1 回答
Spring Framework的spring-web模块默认使用它的CookieWebSessionIdResolver,它基于cookie . 如果您创建一个类型为HeaderWebSessionIdResolver的替代Bean,它将被Spring Session自动拾取并切换到基于头的策略 .
在任一策略中,它都适合读取传入的ServerExchange标头,并查找会话ID,无论是读取Cookie标头还是SESSION http标头 .
这些策略还会创建响应标头,无论是客户端(Web浏览器或您的代码)的set-cookie指令来填充Cookie,还是为您提供SESSION标头(HeaderWebSessionIdResolver的标头名称的默认名称) .