ZBLOG

spring security 接入 websocket + stomp 的范例

以下是使用Spring Security接入WebSocket和STOMP的一个简单示例。

  1. 添加依赖项

在Maven中添加以下依赖项:

  1. <dependency>
  2. <groupId>org.springframework.boot</groupId>
  3. <artifactId>spring-boot-starter-websocket</artifactId>
  4. </dependency>
  5. <dependency>
  6. <groupId>org.webjars</groupId>
  7. <artifactId>stomp-websocket</artifactId>
  8. <version>${stomp-websocket.version}</version>
  9. </dependency>
  10. <dependency>
  11. <groupId>org.springframework.security</groupId>
  12. <artifactId>spring-security-messaging</artifactId>
  13. </dependency>
  14. <dependency>
  15. <groupId>org.springframework.security</groupId>
  16. <artifactId>spring-security-config</artifactId>
  17. </dependency>
  18. <dependency>
  19. <groupId>org.springframework.security.oauth.boot</groupId>
  20. <artifactId>spring-security-oauth2-autoconfigure</artifactId>
  21. <version>${spring-security-oauth2.version}</version>
  22. </dependency>

其中${stomp-websocket.version}${spring-security-oauth2.version}需要根据具体版本进行替换。

  1. 配置WebSocket

在Spring Boot应用程序中,可以使用@EnableWebSocketMessageBroker注释启用WebSocket消息代理。这将创建一个基于SockJS协议的WebSocket连接,并为其提供一个端点。

  1. @Configuration
  2. @EnableWebSocketMessageBroker
  3. public class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer {
  4. @Override
  5. public void configureMessageBroker(MessageBrokerRegistry config) {
  6. config.enableSimpleBroker("/topic");
  7. config.setApplicationDestinationPrefixes("/app");
  8. }
  9. @Override
  10. public void registerStompEndpoints(StompEndpointRegistry registry) {
  11. registry.addEndpoint("/ws").setAllowedOrigins("*").withSockJS();
  12. }
  13. }

在上面的示例中,我们配置了一个/ws端点,并启用了基于“/topic”前缀的简单代理。应用程序处理请求时使用“/app”前缀。

  1. 配置Spring Security

为了保护WebSocket和STOMP端点,需要定义安全规则。下面是一个示例:

  1. @Configuration
  2. @EnableWebSecurity
  3. public class WebSocketSecurityConfig extends WebSecurityConfigurerAdapter {
  4. @Override
  5. protected void configure(HttpSecurity http) throws Exception {
  6. http
  7. .csrf().disable()
  8. .authorizeRequests()
  9. .antMatchers("/ws/**").authenticated()
  10. .anyRequest().permitAll()
  11. .and()
  12. .formLogin();
  13. }
  14. @Autowired
  15. public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
  16. auth.inMemoryAuthentication()
  17. .withUser("user").password("{noop}password").roles("USER");
  18. }
  19. }

在这个例子中,我们禁用CSRF保护并定义了针对/ws/**路径的安全规则。只有经过身份验证的用户才能访问此路径。我们还配置了一个内存中的用户,用户名为”user”,密码为”password”。

  1. 创建STOMP控制器
  1. @Controller
  2. public class WebSocketController {
  3. @MessageMapping("/hello")
  4. @SendTo("/topic/greetings")
  5. public Greeting greeting(HelloMessage message) throws Exception {
  6. Thread.sleep(1000);
  7. return new Greeting("Hello, " + message.getName() + "!");
  8. }
  9. }
  10. class HelloMessage {
  11. private String name;
  12. public String getName() {
  13. return name;
  14. }
  15. public void setName(String name) {
  16. this.name = name;
  17. }
  18. }
  19. class Greeting {
  20. private String content;
  21. public Greeting(String content) {
  22. this.content = content;
  23. }
  24. public String getContent() {
  25. return content;
  26. }
  27. }

在上述示例中,我们定义了一个@MessageMapping注释的方法来接收客户端发送的消息。然后,我们使用@SendTo注释将响应发送到所有已订阅“/topic/greetings”的客户端。

  1. 创建WebSocket客户端
  1. var stompClient = null;
  2. function connect() {
  3. var socket = new SockJS('/ws');
  4. stompClient = Stomp.over(socket);
  5. stompClient.connect({}, function(frame) {
  6. console.log('Connected: ' + frame);
  7. stompClient.subscribe('/topic/greetings', function(greeting){
  8. showGreeting(JSON.parse(greeting.body).content);
  9. });
  10. });
  11. }
  12. function sendName() {
  13. var name = document.getElementById('name').value;
  14. stompClient.send("/app/hello", {}, JSON.stringify({ 'name': name }));
  15. }
  16. function showGreeting(message) {
  17. var response = document.getElementById('response');
  18. var p = document.createElement('p');
  19. p.style.wordWrap = 'break-word';
  20. p.appendChild(document.createTextNode(message));
  21. response.appendChild(p);
  22. }

在这个例子中,我们创建了一个WebSocket客户端并连接到服务器。当连接成功时,我们订阅“/topic/greetings”主题以接收服务端发送的消息。同时,我们还定义了一个用于向服务器发送消息的方法。

以上就是Spring Security接入WebSocket和STOMP的一个简单示例。

本站部分文章来源于网络,版权归原作者所有,如有侵权请联系站长删除。
转载请注明出处:https://golang.0voice.com/?id=4809

分享:
扫描分享到社交APP
上一篇
下一篇
发表列表
游客 游客
此处应有掌声~
评论列表

还没有评论,快来说点什么吧~

联系我们

在线咨询: 点击这里给我发消息

微信号:3007537140

上班时间: 10:30-22:30

关注我们
x

注册

已经有帐号?