❓ How to use SSE with Spring Security and JWT authentication? #43
Replies: 1 comment
Concrete example for Option 1: JWT via query parameterTo add a concrete example for Option 1 (query parameter), since that's usually the path of least resistance when using the browser's native The tricky part is that Spring Security's normal JWT filter expects the token in the A possible approach is to support a query-string token only on the SSE endpoint, rather than changing authentication behavior repo-wide: public class SseTokenAuthFilter extends OncePerRequestFilter {
private final JwtDecoder jwtDecoder;
@Override
protected void doFilterInternal(
HttpServletRequest request,
HttpServletResponse response,
FilterChain chain
) throws ServletException, IOException {
if (request.getRequestURI().startsWith("/sse/")
&& request.getHeader("Authorization") == null) {
String token = request.getParameter("token");
if (token != null) {
try {
Jwt jwt = jwtDecoder.decode(token);
var auth = new JwtAuthenticationToken(jwt);
SecurityContextHolder.getContext().setAuthentication(auth);
} catch (JwtException ex) {
response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
return;
}
}
}
chain.doFilter(request, response);
}
}Then register the filter before http.addFilterBefore(
new SseTokenAuthFilter(jwtDecoder),
BearerTokenAuthenticationFilter.class
);Ideally, this should be scoped specifically to Security considerationsThere are two important things worth flagging here because this is security-sensitive:
If Option 3 ( The query-parameter approach is best treated as a fallback for cases where cookie-based authentication isn't practical, such as certain cross-origin SSE configurations. |
Uh oh!
There was an error while loading. Please reload this page.
Question
How do I secure my SSE endpoints with Spring Security and JWT tokens?
Since the browser's
EventSourceAPI doesn't support custom headers, how should I pass the JWT token?Recommended Approaches
Option 1: Query parameter (EventSource transport)
Option 2: Custom headers (fetch transport)
Option 3: Cookie-based (withCredentials)
See issue #32 for the roadmap on built-in auth support.
This is a pinned FAQ — add your own auth patterns below!
All reactions