FreeKit Identity 模块开发者文档
概述
FreeKit Identity 是一个基于 ASP.NET Core Identity 和 FreeSql 的身份认证与授权模块,提供完整的用户管理、角色管理、权限管理、组织架构管理等功能。
核心功能
1. 用户管理
- 用户注册/登录
- 用户信息 CRUD
- 用户状态管理(激活/冻结)
- 用户密码管理
- 用户角色分配
- 用户组织/岗位分配
2. 角色管理
- 角色 CRUD
- 角色权限配置
- 默认角色设置
3. 权限管理
- 权限树形结构
- 权限分配(用户/角色/岗位)
- 权限验证
- 权限复制功能
4. 组织架构管理
- 部门管理
- 岗位管理
- 组织层级关系
5. 账户功能
- 登录/注册
- 邮箱验证
- 密码重置
- 验证码生成
- Token 刷新
项目结构
FreeKit.Identity/
├── Application/ # 应用服务层
│ ├── Account/ # 账户相关服务
│ ├── Users/ # 用户服务
│ ├── Roles/ # 角色服务
│ ├── Permissions/ # 权限服务
│ └── ...
├── Controllers/ # API 控制器
├── Domain/ # 领域层
├── Models/ # 实体模型
├── Contracts/ # DTO 和常量
└── Infrastructure/ # 基础设施层
快速开始
1. 环境要求
- .NET 10.0
- FreeSql 支持的数据库(MySQL/PostgreSQL/SQL Server 等)
- Redis(用于缓存)
2. 配置
appsettings.json 配置
{
"ConnectionStrings": {
"Default": "Server=localhost;Database=freekit_identity;User=root;Password=password;"
},
"Redis": {
"ConnectionString": "localhost:6379"
},
"Auth": {
"Authority": "https://localhost:5001",
"EmailConfirmationUrl": "https://yourdomain.com/confirm-email?uid={uid}&token={token}",
"PasswordResetUrl": "https://yourdomain.com/reset-password?uid={uid}&token={token}"
},
"Captcha": {
"Enabled": true,
"Salt": "your-captcha-salt",
"Expired": 300
}
}
3. 启动服务
cd src/Services/Identity/FreeKit.Identity.Host
dotnet run
服务启动后,可以通过以下地址访问:
- Swagger UI:
https://localhost:5001/swagger - RapiDoc UI:
https://localhost:5001/r
API 接口说明
账户接口 (/api/identity/account)
| 接口 | 方法 | 描述 | 是否需要认证 |
|---|---|---|---|
/login | POST | 用户登录 | 否 |
/register | POST | 用户注册 | 否 |
/send_email_code | POST | 发送注册验证码 | 否 |
/refresh_token | POST | 刷新 Token | 否 |
/logout | POST | 退出登录 | 是 |
/captcha | GET | 生成验证码 | 否 |
/set_password | POST | 修改密码 | 是 |
/reset_password_email | POST | 发送重置密码邮件 | 否 |
/verify_email | POST | 发送激活邮件 | 是 |
用户接口 (/api/identity/user)
| 接口 | 方法 | 描述 | 所需权限 |
|---|---|---|---|
/ | GET | 获取用户列表 | Identity.Users.GetList |
/{id} | GET | 获取用户详情 | Identity.Users.Get |
/ | POST | 创建用户 | Identity.Users.Create |
/{id} | PUT | 更新用户 | Identity.Users.Update |
/{id} | DELETE | 删除用户 | Identity.Users.Delete |
/lockout_user | PUT | 禁用/启用用户 | Identity.Users.LockoutUser |
/reset_password | PUT | 重置用户密码 | Identity.Users.ResetPassword |
角色接口 (/api/identity/role)
| 接口 | 方法 | 描述 | 所需权限 |
|---|---|---|---|
/ | GET | 获取角色列表 | Identity.Roles.GetList |
/{id} | GET | 获取角色详情 | Identity.Roles.Get |
/ | POST | 创建角色 | Identity.Roles.Create |
/{id} | PUT | 更新角色 | Identity.Roles.Update |
/{id} | DELETE | 删除角色 | Identity.Roles.Delete |
/grant_role_permission | PUT | 配置角色权限 | Identity.Roles.Update |
权限接口 (/api/identity/permission)
| 接口 | 方法 | 描述 | 所需权限 |
|---|---|---|---|
/tree | GET | 获取权限树 | 无 |
/ | GET | 获取权限列表 | Identity.Permissions.GetList |
/grant_permission | POST | 配置权限 | Identity.Permissions.Grant |
/get_current_grant_permission | GET | 获取当前用户权限 | 无 |
/check_permission | POST | 检查权限 | 无 |
使用示例
1. 用户登录
curl -X POST "https://localhost:5001/api/identity/account/login" \
-H "Content-Type: application/json" \
-d '{
"userNameOrEmail": "admin@example.com",
"password": "1q2w3E*",
"rememberMe": true
}'
响应示例:
{
"accessToken": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
"refreshToken": "abc123def456...",
"expiresIn": 3600,
"tokenType": "Bearer"
}
2. 使用 Token 访问受保护接口
curl -X GET "https://localhost:5001/api/identity/user" \
-H "Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."
3. 创建用户
curl -X POST "https://localhost:5001/api/identity/user" \
-H "Content-Type: application/json" \
-H "Authorization: Bearer <your-token>" \
-d '{
"userName": "newuser",
"email": "newuser@example.com",
"password": "1q2w3E*",
"name": "新用户",
"nickName": "小新",
"roleNames": ["User"],
"orgUnitIds": ["guid-of-org-unit"],
"positionIds": ["guid-of-position"]
}'
4. 获取权限树
curl -X GET "https://localhost:5001/api/identity/permission/tree" \
-H "Authorization: Bearer <your-token>"
权限系统
权限定义
权限在 IdentityPermissions 类中定义:
public static class IdentityPermissions
{
public const string GroupName = "Identity";
public static class Users
{
public const string Default = GroupName + ".Users";
public const string Create = Default + ".Create";
public const string GetList = Default + ".GetList";
public const string Get = Default + ".Get";
public const string Update = Default + ".Update";
public const string Delete = Default + ".Delete";
public const string LockoutUser = Default + ".LockoutUser";
public const string ResetPassword = Default + ".ResetPassword";
}
// 其他权限定义...
}
权限使用
在控制器中使用 [Authorize] 特性:
[Authorize(IdentityPermissions.Users.GetList)]
[HttpGet]
public Task<PagedResultDto<UserDto>> GetListAsync([FromQuery] UserQuery userQuery)
{
return userService.GetListAsync(userQuery);
}
扩展开发
1. 添加新的功能模块
- 创建领域实体:在
Models目录下创建实体类 - 创建服务接口:在
Application/{Module}/Contracts下定义接口 - 实现服务:在
Application/{Module}下实现服务 - 创建控制器:在
Controllers下创建 API 控制器 - 添加权限定义:在
IdentityPermissions中添加权限常量
2. 自定义权限验证
// 自定义权限处理器
public class CustomPermissionHandler : AuthorizationHandler<CustomPermissionRequirement>
{
protected override Task HandleRequirementAsync(
AuthorizationHandlerContext context,
CustomPermissionRequirement requirement)
{
// 自定义权限验证逻辑
if (/* 验证通过 */)
{
context.Succeed(requirement);
}
return Task.CompletedTask;
}
}
3. 领域事件
系统支持领域事件,可在用户创建、信息变更等操作时触发:
// 添加领域事件
user.AddUserCreateDomainEvent();
// 事件处理
public class UserCreateEventHandler : INotificationHandler<UserCreateDomainEvent>
{
public Task Handle(UserCreateDomainEvent notification, CancellationToken cancellationToken)
{
// 处理用户创建事件
return Task.CompletedTask;
}
}
数据库迁移
系统使用 FreeSql 的 Code First 模式,启动时会自动迁移数据库:
// Program.cs
await app.MigrationStartAsync();
部署
Docker 部署
# 构建镜像
docker build -t freekit-identity .
# 运行容器
docker run -d \
-p 5001:5001 \
-e ConnectionStrings__Default="Server=db;Database=freekit_identity;User=root;Password=password;" \
-e Redis__ConnectionString="redis:6379" \
freekit-identity
常见问题
1. 如何配置多租户?
系统支持多租户,通过 IdentityTenant 实体关联用户和租户。
2. 如何自定义密码策略?
在 IdentityUserManager 中配置密码策略:
services.Configure<IdentityOptions>(options =>
{
options.Password.RequireDigit = true;
options.Password.RequireLowercase = true;
options.Password.RequireNonAlphanumeric = true;
options.Password.RequireUppercase = true;
options.Password.RequiredLength = 8;
});
3. 如何集成第三方登录?
系统支持 OAuth2/OIDC 第三方登录,相关控制器为 OAuth2Controller 和 SsoController。