FreeKit Identity API 使用示例
目录
快速开始
环境准备
- 确保 Identity 服务已启动
- 获取 API 基础地址(默认:
https://localhost:5001)
认证流程
- 调用登录接口获取 Token
- 在后续请求中携带 Token
- Token 过期时使用刷新接口
账户操作
1. 获取验证码
# 获取图片验证码
curl -X GET "https://localhost:5001/api/identity/account/captcha"
响应:
{
"tag": "captcha-tag-string",
"captchaBase64": "data:image/png;base64,iVBORw0KGgo..."
}
2. 发送注册验证码
# 需要先获取图片验证码
curl -X POST "https://localhost:5001/api/identity/account/send_email_code" \
-H "Content-Type: application/json" \
-H "tag: captcha-tag-string" \
-d '{
"email": "user@example.com",
"captcha": "abcd"
}'
响应:
"verify-token-string"
3. 用户注册
curl -X POST "https://localhost:5001/api/identity/account/register" \
-H "Content-Type: application/json" \
-d '{
"email": "user@example.com",
"password": "1q2w3E*",
"nickName": "用户昵称",
"verifyToken": "verify-token-string",
"verifyCode": "1234"
}'
4. 用户登录
# 用户名/邮箱 + 密码登录
curl -X POST "https://localhost:5001/api/identity/account/login" \
-H "Content-Type: application/json" \
-d '{
"userNameOrEmail": "user@example.com",
"password": "1q2w3E*",
"rememberMe": true
}'
响应:
{
"accessToken": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
"refreshToken": "refresh-token-string",
"expiresIn": 3600,
"tokenType": "Bearer"
}
5. 发送登录验证码
# 需要先获取图片验证码
curl -X POST "https://localhost:5001/api/identity/account/send_login_verify_code" \
-H "Content-Type: application/json" \
-H "tag: captcha-tag-string" \
-d '{
"phoneNumberOrEmail": "user@example.com",
"captcha": "abcd"
}'
6. 验证码登录
curl -X POST "https://localhost:5001/api/identity/account/login_verify_code" \
-H "Content-Type: application/json" \
-d '{
"phoneNumberOrEmail": "user@example.com",
"verifyToken": "verify-token-string",
"verifyCode": "1234"
}'
7. 刷新 Token
curl -X POST "https://localhost:5001/api/identity/account/refresh_token?refreshToken=your-refresh-token"
8. 退出登录
curl -X POST "https://localhost:5001/api/identity/account/logout" \
-H "Authorization: Bearer your-access-token"
9. 修改密码
curl -X POST "https://localhost:5001/api/identity/account/set_password" \
-H "Content-Type: application/json" \
-H "Authorization: Bearer your-access-token" \
-d '{
"currentPassword": "old-password",
"newPassword": "new-password",
"confirmNewPassword": "new-password"
}'
10. 重置密码(邮件链接方式)
# 发送重置密码邮件
curl -X POST "https://localhost:5001/api/identity/account/reset_password_email" \
-H "Content-Type: application/json" \
-d '{
"email": "user@example.com",
"type": "EmailLink"
}'
11. 重置密码(验证码方式)
# 发送重置密码验证码
curl -X POST "https://localhost:5001/api/identity/account/reset_password_email" \
-H "Content-Type: application/json" \
-d '{
"email": "user@example.com",
"type": "EmailCode"
}'
响应:
"verify-token-string"
# 确认重置密码
curl -X POST "https://localhost:5001/api/identity/account/reset_password_code_confirm" \
-H "Content-Type: application/json" \
-d '{
"verifyToken": "verify-token-string",
"verifyCode": "1234",
"newPassword": "new-password",
"confirmNewPassword": "new-password"
}'
用户管理
1. 获取用户列表
curl -X GET "https://localhost:5001/api/identity/user?page=1&pageSize=10&name=张三" \
-H "Authorization: Bearer your-access-token"
响应:
{
"items": [
{
"id": "guid",
"userName": "username",
"email": "user@example.com",
"name": "张三",
"nickName": "昵称",
"status": "Active",
"createTime": "2024-01-01T00:00:00"
}
],
"totalCount": 100
}
2. 获取用户详情
curl -X GET "https://localhost:5001/api/identity/user/{userId}" \
-H "Authorization: Bearer your-access-token"
3. 创建用户
curl -X POST "https://localhost:5001/api/identity/user" \
-H "Content-Type: application/json" \
-H "Authorization: Bearer your-access-token" \
-d '{
"userName": "newuser",
"email": "newuser@example.com",
"password": "1q2w3E*",
"name": "新用户",
"nickName": "昵称",
"gender": 1,
"roleNames": ["User"],
"orgUnitIds": ["org-guid-1", "org-guid-2"],
"positionIds": ["position-guid-1"]
}'
4. 更新用户
curl -X PUT "https://localhost:5001/api/identity/user/{userId}" \
-H "Content-Type: application/json" \
-H "Authorization: Bearer your-access-token" \
-d '{
"name": "更新后的姓名",
"nickName": "更新后的昵称",
"gender": 2,
"roleNames": ["User", "Admin"],
"orgUnitIds": ["org-guid-1"],
"positionIds": ["position-guid-1", "position-guid-2"]
}'
5. 删除用户
curl -X DELETE "https://localhost:5001/api/identity/user/{userId}" \
-H "Authorization: Bearer your-access-token"
6. 禁用/启用用户
curl -X PUT "https://localhost:5001/api/identity/user/lockout_user" \
-H "Content-Type: application/json" \
-H "Authorization: Bearer your-access-token" \
-d '{
"id": "user-guid",
"lockoutEnabled": true,
"lockoutEnd": "2024-12-31T23:59:59"
}'
7. 重置用户密码
curl -X PUT "https://localhost:5001/api/identity/user/reset_password" \
-H "Content-Type: application/json" \
-H "Authorization: Bearer your-access-token" \
-d '{
"userId": "user-guid",
"newPassword": "new-password",
"confirmNewPassword": "new-password"
}'
角色管理
1. 获取角色列表
curl -X GET "https://localhost:5001/api/identity/role?page=1&pageSize=10" \
-H "Authorization: Bearer your-access-token"
2. 创建角色
curl -X POST "https://localhost:5001/api/identity/role" \
-H "Content-Type: application/json" \
-H "Authorization: Bearer your-access-token" \
-d '{
"name": "新角色",
"displayName": "新角色显示名称",
"description": "角色描述",
"isDefault": false,
"isStatic": false,
"status": true
}'
3. 更新角色
curl -X PUT "https://localhost:5001/api/identity/role/{roleId}" \
-H "Content-Type: application/json" \
-H "Authorization: Bearer your-access-token" \
-d '{
"name": "更新后的角色名",
"displayName": "更新后的显示名称",
"description": "更新后的描述"
}'
4. 配置角色权限
curl -X PUT "https://localhost:5001/api/identity/role/grant_role_permission?id={roleId}" \
-H "Content-Type: application/json" \
-H "Authorization: Bearer your-access-token" \
-d '{
"permissionIds": ["permission-guid-1", "permission-guid-2", "permission-guid-3"]
}'
权限管理
1. 获取权限树
curl -X GET "https://localhost:5001/api/identity/permission/tree" \
-H "Authorization: Bearer your-access-token"
响应:
[
{
"id": "permission-guid",
"name": "用户管理",
"code": "Identity.Users",
"parentId": null,
"children": [
{
"id": "permission-guid-2",
"name": "用户查询",
"code": "Identity.Users.GetList",
"parentId": "permission-guid"
}
]
}
]
2. 获取当前用户权限
curl -X GET "https://localhost:5001/api/identity/permission/get_current_grant_permission" \
-H "Authorization: Bearer your-access-token"
响应:
["permission-guid-1", "permission-guid-2", "permission-guid-3"]
3. 获取当前用户权限 Code
curl -X GET "https://localhost:5001/api/identity/permission/get_current_grant_permission_code" \
-H "Authorization: Bearer your-access-token"
响应:
["Identity.Users.GetList", "Identity.Users.Create", "Identity.Roles.GetList"]
4. 配置用户/角色/岗位权限
curl -X POST "https://localhost:5001/api/identity/permission/grant_permission" \
-H "Content-Type: application/json" \
-H "Authorization: Bearer your-access-token" \
-d '{
"providerKey": "user-guid-or-role-name",
"permissionGrantType": "User",
"permissionIds": ["permission-guid-1", "permission-guid-2"]
}'
permissionGrantType 可选值:
User- 用户Role- 角色Position- 岗位
5. 检查权限
curl -X POST "https://localhost:5001/api/identity/permission/check_permission?permission=Identity.Users.GetList" \
-H "Authorization: Bearer your-access-token"
响应:
true
6. 复制角色权限
curl -X POST "https://localhost:5001/api/identity/permission/copy-role-permissions" \
-H "Content-Type: application/json" \
-H "Authorization: Bearer your-access-token" \
-d '{
"sourceRoleId": "source-role-guid",
"targetRoleId": "target-role-guid"
}'
7. 复制用户权限
curl -X POST "https://localhost:5001/api/identity/permission/copy-user-permissions" \
-H "Content-Type: application/json" \
-H "Authorization: Bearer your-access-token" \
-d '{
"sourceUserId": "source-user-guid",
"targetUserId": "target-user-guid"
}'
错误处理
常见错误码
| 错误信息 | 说明 | 解决方案 |
|---|---|---|
未注册 | 用户不存在 | 检查用户名/邮箱是否正确 |
账号或密码错误 | 登录凭证错误 | 检查密码是否正确 |
用户已锁定,无法登录 | 用户被禁用 | 联系管理员解锁 |
该邮箱已注册,请更换 | 邮箱重复 | 使用其他邮箱 |
验证码已超时 | 验证码过期 | 重新获取验证码 |
验证码错误 | 验证码不正确 | 检查验证码输入 |
权限不足 | 无访问权限 | 联系管理员分配权限 |
错误响应格式
{
"code": 400,
"message": "错误描述",
"details": "详细错误信息",
"traceId": "trace-id-for-debugging"
}
客户端集成示例
JavaScript/TypeScript
// 登录
async function login(username: string, password: string) {
const response = await fetch('/api/identity/account/login', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
userNameOrEmail: username,
password: password,
rememberMe: true
})
});
if (!response.ok) {
throw new Error('登录失败');
}
return await response.json();
}
// 获取用户列表
async function getUsers(token: string, page: number = 1, pageSize: number = 10) {
const response = await fetch(`/api/identity/user?page=${page}&pageSize=${pageSize}`, {
headers: {
'Authorization': `Bearer ${token}`
}
});
return await response.json();
}
// 检查权限
async function checkPermission(token: string, permission: string) {
const response = await fetch(`/api/identity/permission/check_permission?permission=${permission}`, {
method: 'POST',
headers: {
'Authorization': `Bearer ${token}`
}
});
return await response.json();
}
C# (.NET)
using System.Net.Http;
using System.Net.Http.Json;
public class IdentityApiClient
{
private readonly HttpClient _httpClient;
private string? _accessToken;
public IdentityApiClient(HttpClient httpClient)
{
_httpClient = httpClient;
}
public async Task LoginAsync(string username, string password)
{
var response = await _httpClient.PostAsJsonAsync("/api/identity/account/login", new
{
UserNameOrEmail = username,
Password = password,
RememberMe = true
});
response.EnsureSuccessStatusCode();
var result = await response.Content.ReadFromJsonAsync<LoginResponse>();
_accessToken = result?.AccessToken;
}
public async Task<List<UserDto>> GetUsersAsync(int page = 1, int pageSize = 10)
{
_httpClient.DefaultRequestHeaders.Authorization =
new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", _accessToken);
var response = await _httpClient.GetAsync($"/api/identity/user?page={page}&pageSize={pageSize}");
response.EnsureSuccessStatusCode();
var result = await response.Content.ReadFromJsonAsync<PagedResultDto<UserDto>>();
return result?.Items ?? new List<UserDto>();
}
public async Task<bool> CheckPermissionAsync(string permission)
{
_httpClient.DefaultRequestHeaders.Authorization =
new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", _accessToken);
var response = await _httpClient.PostAsync($"/api/identity/permission/check_permission?permission={permission}", null);
response.EnsureSuccessStatusCode();
return await response.Content.ReadFromJsonAsync<bool>();
}
}
public class LoginResponse
{
public string? AccessToken { get; set; }
public string? RefreshToken { get; set; }
public int ExpiresIn { get; set; }
public string? TokenType { get; set; }
}