大屏监控 Metabase 集成到 C# 项目
集成 Metabase 的方法与实践
随着数据驱动决策的普遍性,数据可视化平台如 Metabase 变得越来越重要。Metabase 是一个开源的商业智能工具,可以轻松地帮助用户分析和可视化数据。本文将详细介绍如何在 C# 项目中集成 Metabase,并提供详细的代码示例。
集成概述
Metabase 比较适合的场景包括:
1、基于SSO的完整集成(支持下钻),在打开报表时完成用户在主系统跟报表系统的单点登录,需付费实现JWT集成;
2、基于embed报表发布的设定,实现基于密钥的集成,此方案较公开分享方式更加安全,但由于为实现单点登录,无法使用下钻功能。
集成代码
以下是针对embed封装的console代码,需要添加Newtonsoft.Json、System.IdentityModel.Tokens.Jwt两个Nuget包。
1 using System; 2 using System.IdentityModel.Tokens.Jwt; 3 using System.Security.Claims; 4 using System.Text; 5 using Microsoft.IdentityModel.Tokens; 6 using Newtonsoft.Json.Linq; 7 8 class JwtGenerator 9 { 10 private const string MetabaseSiteUrl = "http://127.0.0.1:8080"; 11 private const string MetabaseSecretKey = "15c2ed06f625d42a24369ba7840ee77da5891d853c654787af998de41ec0f10b"; 12 13 static void Main(string[] args) 14 { 15 int dashboardId = 1; 16 try 17 { 18 Console.WriteLine(GenerateDashboardUrl(dashboardId)); 19 } 20 catch (Exception ex) 21 { 22 Console.WriteLine(ex.ToString()); 23 } 24 } 25 26 public static string GenerateDashboardUrl(int dashboardId) 27 { 28 // 生成HMAC-SHA256密钥 29 var keyBytes = Encoding.UTF8.GetBytes(MetabaseSecretKey); 30 var securityKey = new SymmetricSecurityKey(keyBytes); 31 var signingCredentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256); 32 33 // 构建JWT声明 34 var claims = new[] 35 { 36 // 嵌套resource声明(转换为JSON对象) 37 new Claim("resource", 38 JObject.FromObject(new { dashboard = dashboardId }).ToString(), 39 JsonClaimValueTypes.Json), 40 // 空参数声明 41 new Claim("params", "{}", JsonClaimValueTypes.Json) 42 }; 43 44 // 配置Token参数 45 var tokenDescriptor = new JwtSecurityToken( 46 claims: claims, 47 expires: DateTime.UtcNow.AddMinutes(60), // 60分钟有效期,可按需调整 48 signingCredentials: signingCredentials 49 ); 50 51 // 生成Token字符串 52 var tokenHandler = new JwtSecurityTokenHandler(); 53 string token = tokenHandler.WriteToken(tokenDescriptor); 54 55 // 拼接Metabase嵌入式URL 56 return $"{MetabaseSiteUrl}/embed/dashboard/{token}?bordered=true&titled=false"; 57 } 58 }
