Spring websocket jwt身份验证
Posted
技术标签:
【中文标题】Spring websocket jwt身份验证【英文标题】:Spring websocket jwt authentication 【发布时间】:2021-08-22 21:39:19 【问题描述】:我需要添加 jwt 身份验证。我有 jwt 生成和验证类。我不知道如何在 websocket 中添加它。我认为 spring 必须在连接开始时检查 jwt 令牌
服务器端点类
@Component
@ServerEndpoint(value = "/user",
encoders = MessageEncoder.class ,
decoders = MessageDecoder.class
)
public class ChatEndpoint implements Serializable
@OnOpen
public void OnOpen (Session session) throws IOException
@OnMessage
public void onMessage(Session session, Message message) throws IOException, EncodeException
@OnClose
public void onClose(Session session) throws IOException, EncodeException
@OnError
public void onError(Session session, Throwable throwable)
// Do error handling here
System.out.println(throwable);
public static void broadcast(Message message) throws IOException
private void sendMessage(Message message) throws IOException
入门类
@ServletComponentScan
@SpringBootApplication
public class WebsocketdemoApplication
public static void main(String[] args)
SpringApplication app = new SpringApplication(WebsocketdemoApplication.class);
app.run(args);
配置类
@Configuration
public class WebSocketConfig
@Bean
public ServerEndpointExporter endpointExporter()
return new ServerEndpointExporter();
我的 pom.xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
<version>2.4.3</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>2.4.3</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
<version>2.4.3</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-core -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>5.3.4</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot</artifactId>
<version>2.4.3</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-autoconfigure</artifactId>
<version>2.4.3</version>
</dependency>
我希望有人可以帮助我。我不能考虑。每个人都在使用 stomp,但我没有使用它,所以这很奇怪
【问题讨论】:
【参考方案1】:问题是添加过滤器后过滤我可以安排jwt安全
@WebFilter("/user")
public class AccessTokenFilter implements Filter
@Override
public void init(FilterConfig filterConfig) throws ServletException
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse,
FilterChain filterChain) throws IOException, ServletException
// jwt auth
【讨论】:
以上是关于Spring websocket jwt身份验证的主要内容,如果未能解决你的问题,请参考以下文章
带有 JWT 令牌的 Spring Security 和 Websocket
通过 spring websocket、sockJs 和 STOMP 向经过身份验证的用户发送通知
用于通道 websocket 身份验证的 Django jwt 中间件