Mud.Feishu.Authentication
飞书用户认证中间件,提供用户上下文管理功能。
功能特性
- 基于
AsyncLocal实现线程安全的用户信息存储 - 从 JWT Claims 中自动提取飞书用户信息
- 支持分布式追踪 (ActivitySource)
- 请求结束后自动清理用户上下文
- 支持配置绑定与自定义 Claim 类型映射
- 原生 AOT 支持(net8.0+,源生成配置绑定)
安装
bash
dotnet add package Mud.Feishu.Authentication快速开始
1. 注册服务
csharp
// Program.cs
// 方式一:从 IConfiguration 绑定(推荐,与下方 appsettings.json 配合使用)
builder.Services.AddFeishuApp(builder.Configuration, "FeishuApps");
builder.Services.AddFeishuUserContext(builder.Configuration);
// 方式二:代码配置
builder.Services.AddFeishuUserContext(options =>
{
options.OpenIdClaimType = "custom_open_id";
options.EnableSensitiveLog = false;
});
// 方式三:使用默认配置
services.AddFeishuUserContext();2. 配置中间件
csharp
app.UseAuthentication();
app.UseFeishuUserAuthentication(); // 添加此中间件
app.UseAuthorization();3. 使用用户上下文
csharp
public class MyService
{
private readonly ICurrentUserContext _userContext;
public MyService(ICurrentUserContext userContext)
{
_userContext = userContext;
}
public void DoSomething()
{
var openId = _userContext.OpenId; // 飞书用户 OpenId
var unionId = _userContext.UnionId; // 飞书用户 UnionId
var userId = _userContext.UserId; // 业务系统用户ID
var name = _userContext.Name; // 用户名称
if (_userContext.IsAuthenticated)
{
// 用户已认证
}
}
}支持的 Claims
| Claim 类型 | 用途 |
|---|---|
open_id | 飞书用户 OpenId |
union_id | 飞书用户 UnionId |
user_id | 业务系统用户ID |
ClaimTypes.Name | 用户名称 |
ClaimTypes.NameIdentifier | 备用 OpenId 来源 |
💡 以上 Claim 类型名称均可通过
FeishuUserAuthenticationOptions自定义(见下方配置选项)。
配置选项
FeishuUserAuthenticationOptions 配置项
引用
Mud.Feishu.Authentication包并启用用户认证中间件时,以下配置在FeishuUserAuthentication节点下生效。
| 配置项 | 类型 | 默认值 | 说明 |
|---|---|---|---|
OpenIdClaimType | string | "open_id" | OpenId 的 Claim 类型名称 |
OpenIdFallbackClaimType | string | ClaimTypes.NameIdentifier | OpenId 的备用 Claim 类型名称 |
UnionIdClaimType | string | "union_id" | UnionId 的 Claim 类型名称 |
UserIdClaimType | string | "user_id" | UserId 的 Claim 类型名称 |
NameClaimType | string | ClaimTypes.Name | 用户名称的 Claim 类型名称 |
EnableDistributedTracing | bool | true | 是否启用分布式追踪(创建 Activity 并设置用户相关标签) |
EnableSensitiveLog | bool | false | 是否在日志中记录敏感信息(如 OpenId),生产环境应保持 false |
配置示例
json
{
"FeishuUserAuthentication": {
"OpenIdClaimType": "open_id",
"UnionIdClaimType": "union_id",
"UserIdClaimType": "user_id",
"EnableDistributedTracing": true,
"EnableSensitiveLog": false
}
}🔒 生产环境强烈建议保持
EnableSensitiveLog=false,避免在日志中泄露用户 OpenId/UnionId 等敏感信息。
多租户 / 多应用场景
用户上下文与多应用基础设施相互独立:用户令牌的获取与多应用切换请参考 飞书多应用管理及认证授权指南。Mud.Feishu.Authentication 只负责 从当前请求的 Claims 中提取用户身份,不负责租户级授权,业务层需自行实现授权校验。
许可证
MIT License