zijian666.WebApi.AuthService
2.2.1-beta
This is a prerelease version of zijian666.WebApi.AuthService.
dotnet add package zijian666.WebApi.AuthService --version 2.2.1-beta
NuGet\Install-Package zijian666.WebApi.AuthService -Version 2.2.1-beta
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="zijian666.WebApi.AuthService" Version="2.2.1-beta" />
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="zijian666.WebApi.AuthService" Version="2.2.1-beta" />
<PackageReference Include="zijian666.WebApi.AuthService" />
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add zijian666.WebApi.AuthService --version 2.2.1-beta
The NuGet Team does not provide support for this client. Please contact its maintainers for support.
#r "nuget: zijian666.WebApi.AuthService, 2.2.1-beta"
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package zijian666.WebApi.AuthService@2.2.1-beta
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=zijian666.WebApi.AuthService&version=2.2.1-beta&prerelease
#tool nuget:?package=zijian666.WebApi.AuthService&version=2.2.1-beta&prerelease
The NuGet Team does not provide support for this client. Please contact its maintainers for support.
AuthService 认证授权服务模块
概述
AuthService 是一个重新封装的认证和授权功能模块,旨在简化 ASP.NET Core 应用中认证与授权的配置和使用。该模块通过统一的构建器模式和插件化的 Token 解析机制,在满足 80% 常见场景的前提下,简化 80% 的代码操作。
核心特性
🎯 简化配置
- 零配置启动:只需实现
ITokenParser接口即可完成认证配置 - 自动中间件注册:自动配置认证和授权中间件,无需手动调用
UseAuthentication()和UseAuthorization() - 动态方案注册:根据注册的 Token 解析器自动创建认证方案
🔌 插件化架构
- 灵活的 Token 解析:支持多个 Token 解析器,按顺序尝试解析
- 自定义请求头:每个解析器可指定自己的请求头名称
- 多方案支持:支持在同一应用中配置多个认证方案
🛡️ 增强功能
- Claims 转换:支持通过
IClaimsTransformation扩展用户身份信息 - 授权策略访问:授权策略自动存储到
HttpContext.Items中,便于后续访问 - 统一异常处理:认证失败和授权失败自动转换为业务异常
快速开始
1. 实现 Token 解析器
实现 ITokenParser 接口来定义如何解析令牌:
using System.Security.Claims;
using zijian666.WebApi.Abstractions;
public class JwtTokenParser : ITokenParser
{
public string HeaderName => "Authorization"; // 默认从 Authorization 请求头读取
public async Task<ClaimsPrincipal?> Parse(string token, ApiActionContext context)
{
// 解析 JWT Token 或 Bearer Token
// 返回包含用户信息的 ClaimsPrincipal
// 如果无法解析,返回 null
if (string.IsNullOrWhiteSpace(token))
return null;
var user = Parse(token);
// 示例:解析 JWT Token
var claims = new List<Claim>
{
new Claim(ClaimTypes.NameIdentifier, user.Id),
new Claim(ClaimTypes.Name, user.Name),
new Claim(ClaimTypes.Role, user.Role),
};
return new ClaimsPrincipal(new ClaimsIdentity(claims, "Bearer"));
}
}
2. 注册服务
在 Program.cs 或 Startup.cs 中注册认证服务:
using zijian666.WebApi;
var builder = WebApplication.CreateBuilder(args);
// 添加认证服务并注册 Token 解析器
builder.Services.AddWebApi(webApi =>
{
webApi.AddAuthService(auth =>
{
auth.AddTokenParse<JwtTokenParser>();
});
});
var app = builder.Build();
// 使用认证服务(中间件会自动注册)
app.UseWebApi();
app.Run();
3. 使用授权
在控制器或 Action 上使用授权特性:
[ApiController]
[Route("api/[controller]")]
public class UserController : ControllerBase
{
[HttpGet("profile")]
// [Authorize] // 启用服务后, 默认全局需要认证, 不需要单独设置特性
public IActionResult GetProfile()
{
var userId = User.FindFirst(ClaimTypes.NameIdentifier)?.Value;
return Ok(new { UserId = userId });
}
[HttpGet("admin")]
[Authorize(Roles = "Admin")] // 需要 Admin 角色
public IActionResult GetAdminData()
{
return Ok("Admin Data");
}
}
高级用法
多个 Token 解析器
支持注册多个 Token 解析器,系统会按注册顺序依次尝试解析:
auth.AddTokenParse<JwtTokenParser>();
auth.AddTokenParse<ApiKeyTokenParser>(); // 第二个解析器
auth.AddTokenParse<CustomTokenParser>(); // 第三个解析器
自定义请求头
每个解析器可以指定自己的请求头名称:
public class ApiKeyTokenParser : ITokenParser
{
public string HeaderName => "X-API-Key"; // 从自定义请求头读取
public async Task<ClaimsPrincipal?> Parse(string token, ApiActionContext context)
{
// 解析 API Key
return new ClaimsPrincipal(/* ... */);
}
}
多个认证方案
通过 AuthenticateScheme 属性支持多个认证方案:
public class AdminTokenParser : ITokenParser
{
public string AuthenticateScheme => "Admin"; // 指定认证方案名称
public async Task<ClaimsPrincipal?> Parse(string token, ApiActionContext context)
{
// 解析管理员 Token
return new ClaimsPrincipal(/* ... */);
}
}
// 在控制器中使用特定方案
[Authorize(AuthenticationSchemes = "Admin")]
public class AdminController : ControllerBase
{
// ...
}
Claims 转换
通过 IClaimsTransformation 扩展用户身份信息:
public class CustomClaimsTransformation : IClaimsTransformation
{
public Task<ClaimsPrincipal> TransformAsync(ClaimsPrincipal principal)
{
var identity = new ClaimsIdentity();
// 添加自定义 Claims
if (!principal.HasClaim(c => c.Type == "CustomClaim"))
{
identity.AddClaim(new Claim("CustomClaim", "CustomValue"));
}
principal.AddIdentity(identity);
return Task.FromResult(principal);
}
}
// 注册 Claims 转换服务
auth.AddClaimsTransformation<CustomClaimsTransformation>();
自定义认证方案名称
auth.SchemeName = "MyCustomScheme"; // 默认为 "Authorization"
API 参考
AuthServiceBuilder
属性
SchemeName:认证方案名称,默认为"Authorization"
方法
AddTokenParse<T>():添加一个 Token 解析器(泛型版本)AddTokenParse(Type type):添加一个 Token 解析器(类型版本)AddClaimsTransformation<T>():添加一个 Claims 转换服务(泛型版本)AddClaimsTransformation(Type type):添加一个 Claims 转换服务(类型版本)
ITokenParser
属性
AuthenticateScheme:认证方案名称,用于区分不同的授权方式HeaderName:请求头名称,默认为"Authorization"。如果为空字符串,则直接调用Parse方法
方法
Parse(string token, ApiActionContext context):解析令牌,返回ClaimsPrincipal,如果无法解析返回null
工作原理
服务注册阶段(
AddService):- 自动注册
Authorization服务 - 注册自定义的
AuthorizationResultHandler - 配置
Authentication服务,设置默认认证方案
- 自动注册
中间件启用阶段(
UseService):- 从服务容器中获取所有注册的
ITokenParser实例 - 根据
AuthenticateScheme对解析器进行分组 - 为每个分组动态创建
TokenAuthenticationScheme - 自动调用
UseAuthentication()和UseAuthorization()
- 从服务容器中获取所有注册的
请求处理阶段:
TokenParserAuthenticationHandler按顺序尝试每个解析器- 如果解析器指定的请求头存在,则调用解析器
- 第一个成功解析的解析器返回
ClaimsPrincipal - 如果所有解析器都无法解析,返回
NoResult()
最佳实践
- 单一职责:每个
ITokenParser实现应该只负责一种 Token 类型的解析 - 性能优化:将最常用的解析器放在前面,减少不必要的解析尝试
- 错误处理:在
Parse方法中妥善处理异常,返回null而不是抛出异常 - Claims 设计:使用标准的
ClaimTypes或自定义的常量来定义 Claim 类型,保持一致性
注意事项
- 至少需要注册一个
ITokenParser实现,否则在UseService阶段会抛出异常 HeaderName为空字符串时,解析器会被直接调用,适用于不从请求头读取 Token 的场景- 认证失败会抛出
UnauthorizedAccessException,HTTP 状态码为 401 - 授权失败会抛出
UnauthorizedAccessException,HTTP 状态码为 403
示例项目
更多使用示例请参考:
example/WebApiDemo7:基础 Token 解析示例example/WebApiDemo8:多方案和 Claims 转换示例
| Product | Versions Compatible and additional computed target framework versions. |
|---|---|
| .NET | net6.0 is compatible. net6.0-android was computed. net6.0-ios was computed. net6.0-maccatalyst was computed. net6.0-macos was computed. net6.0-tvos was computed. net6.0-windows was computed. net7.0 is compatible. net7.0-android was computed. net7.0-ios was computed. net7.0-maccatalyst was computed. net7.0-macos was computed. net7.0-tvos was computed. net7.0-windows was computed. net8.0 was computed. net8.0-android was computed. net8.0-browser was computed. net8.0-ios was computed. net8.0-maccatalyst was computed. net8.0-macos was computed. net8.0-tvos was computed. net8.0-windows was computed. net9.0 was computed. net9.0-android was computed. net9.0-browser was computed. net9.0-ios was computed. net9.0-maccatalyst was computed. net9.0-macos was computed. net9.0-tvos was computed. net9.0-windows was computed. net10.0 was computed. net10.0-android was computed. net10.0-browser was computed. net10.0-ios was computed. net10.0-maccatalyst was computed. net10.0-macos was computed. net10.0-tvos was computed. net10.0-windows was computed. |
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.
-
net6.0
- zijian666.WebApi.Abstractions (>= 2.2.1-beta)
- zijian666.WebApi.Core (>= 2.2.1-beta)
-
net7.0
- zijian666.WebApi.Abstractions (>= 2.2.1-beta)
- zijian666.WebApi.Core (>= 2.2.1-beta)
NuGet packages (1)
Showing the top 1 NuGet packages that depend on zijian666.WebApi.AuthService:
| Package | Downloads |
|---|---|
|
zijian666.WebApi
用于快速创建简单易用的标准化WebApi项目 |
GitHub repositories
This package is not used by any popular GitHub repositories.
| Version | Downloads | Last Updated |
|---|---|---|
| 2.2.1-beta | 82 | 5/31/2026 |
UPLOGS.md