首页 > 解决方案 > 在返回 SseEmitter 的方法中使用 @PreAuthorize 会返回 HTTP 406

问题描述

我正在使用 jwt 进行身份验证,我怀疑它与具有令牌的请求标头有关。

在不添加 @PreAuthorize 的情况下接收服务器发送的事件就可以了:

@GetMapping("/sse")
public SseEmitter serverSentEvent() throws IOException
{
   SseEmitter emitter = new SseEmitter(2592000000L);
   emitter.send("OK");

   return emitter;
}

但是,当我添加 @PreAuthorize 以检查使用角色时,我得到 406 响应(无法在http://localhost:8080/sse建立与服务器的连接)

@GetMapping("/sse")
@PreAuthorize("hasRole('ADMIN')")
public SseEmitter serverSentEvent() throws IOException
{
   SseEmitter emitter = new SseEmitter(2592000000L);
   emitter.send("OK");

   return emitter;
}

标签: springspring-bootspring-security

解决方案


显然,JWT 拦截器没有在 EventSource 请求的授权标头中添加令牌,因此我使用了允许在 EventSource 中自定义 HTTP 标头的ng-event-source 。


推荐阅读