spring boot security 配置 WebSocket

  1. 导入依赖
 <dependency>
     <groupId>org.springframework.boot</groupId>
     <artifactId>spring-boot-starter-websocket</artifactId>
 </dependency>
  1. 创建socket处理类
    
@Component
@Slf4j
@ServerEndpoint("/websocket/{id}")
public class MyWebSocket implements SocketHandle {

    private static Map<String ,Session> onlineClientMap = new ConcurrentHashMap<>();

    @Override
    @OnOpen
    public void onOpen(Session session, @PathParam("id") String id) {
        onlineClientMap.put(session.getId(),session);//添加当前连接的session
        log.info("时间[{}]:与用户[{}]的连接成功,当前连接编号[{}]",
                new Date().toLocaleString(),
                id,
                session.getId());
        System.out.println("连接成功");
    }

    @Override
    @OnClose
    public void onClose(Session session,@PathParam("id") String id) {
        onlineClientMap.remove(session.getId());//移除当前连接的session
        log.info("时间[{}]:与用户[{}]的连接关闭,当前连接编号[{}]",
                new Date().toLocaleString(),
                id,
                session.getId());
    }

    @Override
    @OnError
    public void onError(Throwable error, Session session,@PathParam("id") String id) {
        error.printStackTrace();
    }

    @Override
    @OnMessage
    public void onMsg(Session session, String message, @PathParam("id") String id) throws IOException {
        log.info("时间[{}]:来自连接编号为[{}]的消息:[{}]",
                new Date().toLocaleString(),
                session.getId(),
                message);
    }

    public static void sendMessageById(String id,String message){
        Session session = onlineClientMap.get(id);
        session.getAsyncRemote().sendText(message);
    }
}

根据大多数网上的介绍到这一步已经可以了,谁能想到这些该天杀的掉了一个配置😤,我自己到这一步就死活连不上。
3. 创建socket的连接点配置

@Configuration
public class WebSocketConfiguration {
    /**
     * 	注入ServerEndpointExporter,
     * 	这个bean会自动注册使用了@ServerEndpoint注解声明的Websocket endpoint
     */
    @Bean
    public ServerEndpointExporter serverEndpointExporter() {
        return new ServerEndpointExporter();
    }
}

  1. 还有一个问题就是如果加入了安全组件,security或者shiro需要排除websocket的接入链接
@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private UserDetailsService userDetailsService;

    @Autowired
    private AdminAuthenticationProcessingFilter adminAuthenticationProcessingFilter;

    @Autowired
    private IPiPermissionService iPiPermissionService;

    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers("/login.html","/component/**","/admin/**","/file/**","/websocket/**");// 忽略websocket的链接
    }

    @Override
    protected void configure(HttpSecurity httpSecurity) throws Exception{

        httpSecurity.formLogin()
                .loginPage("/login.html").permitAll();
        httpSecurity.authorizeRequests()
                .mvcMatchers("/login","/piMenu/getAllMenu","/websocket/**").permitAll()// 忽略websocket的链接
                .anyRequest().authenticated();
        httpSecurity.csrf().disable();  // CRSF禁用,因为不使用session 可以预防CRSF攻击
        httpSecurity.cors().configurationSource(corsConfigurationSource());
        // 允许iframe访问
        httpSecurity.headers().frameOptions().disable();
        httpSecurity.userDetailsService(userDetailsService);
        httpSecurity.addFilterAt(adminAuthenticationProcessingFilter, UsernamePasswordAuthenticationFilter.class);
    }



    /**
     *  跨域支持
     * @return CorsConfigurationSource
     */
    @Bean
    protected CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration configuration = new CorsConfiguration();
        configuration.setAllowedOrigins(Arrays.asList("*"));
        configuration.setAllowedMethods(Arrays.asList("*"));
        configuration.setAllowedHeaders(Arrays.asList("*"));
        configuration.addExposedHeader("*");
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);
        return source;
    }
}

Spring Boot 是一个用于创建独立的、基于 Spring 的应用程序的开发框架。它提供了许多开箱即用的功能,使得开发人员可以快速构建和部署应用程序。而Spring SecuritySpring 生态系统中的一个强大的安全框架,可以用于保护 Web 应用程序免受各种安全威胁。 Vue 是一个用于构建用户界面的 JavaScript 框架,它提供了一套功能强大的工具和组件,使得开发人员可以轻松构建交互性的前端应用程序。 MySQL 是一个流行的关系型数据库管理系统,广泛用于存储和管理大量的数据。 在一个包含 Spring BootSpring Security、Vue 和 MySQL 的项目中,可以实现以下功能和特性: 1. 用户身份验证和授权:通过 Spring Security 可以实现用户的身份验证和授权的功能,保护后端 API 只允许授权的用户访问。 2. 前后端分离:使用 Vue 作为前端框架,通过 AJAX 或 WebSocket 与后端进行通信,实现前后端的解耦和独立开发。 3. RESTful API:使用 Spring Boot 提供的特性,可以轻松地实现 RESTful API,提供对数据的增删改查操作。 4. 数据库操作:通过集成 MySQL 数据库,可以进行数据的持久化存储和管理,使用 Spring Data JPA 简化数据库操作。 5. 安全配置:通过 Spring Security 可以对 Web 应用程序进行安全配置,例如限制某些 URL 的访问权限、防止 CSRF 攻击等。 6. 日志记录:使用 Spring Boot 自带的日志框架,可以对应用程序的运行情况进行日志记录和监控。 综上所述,结合 Spring BootSpring Security、Vue 和 MySQL,可以构建一个安全可靠的前后端分离项目,实现用户身份验证和授权、数据存储和管理等各种功能。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值