跳到主要内容

AspNet.Security.OAuth.KitSSO

ASP.NET Core OIDC 认证中间件,为 KitSSO(FreeKit 身份认证服务)提供开箱即用的 OAuth2 / OpenID Connect 认证支持。

NuGet 包

dotnet add package AspNet.Security.OAuth.KitSSO

依赖

  • Microsoft.AspNetCore.Authentication.OpenIdConnect 10.0.9

默认配置

属性默认值说明
AuthenticationSchemeKitSSO认证方案名称
CallbackPath/signin-kitssoOAuth 回调路径
ResponseTypeCodeAuthorization Code 流程
ResponseModeQuerycode 通过 query string 回传
UsePkcetrue启用 PKCE 防护
SaveTokenstrue保存 token 到 AuthenticationProperties
GetClaimsFromUserInfoEndpointtrue从 userinfo 端点获取 claims
Scopeopenid profile email默认请求的 scope

快速接入

1. 注册认证服务

builder.Services.AddAuthentication(options =>
{
options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = "KitSSO";
})
.AddCookie()
.AddKitSSO(options =>
{
options.Authority = "https://auth.igeekfan.cn"; // KitSSO 服务地址
options.ClientId = "your-client-id";
options.ClientSecret = "your-client-secret";
});

2. 添加登录/登出端点

app.MapGet("/login", () =>
Results.Challenge(new AuthenticationProperties
{
RedirectUri = "/"
}, authenticationSchemes: ["KitSSO"]));

app.MapGet("/logout", () =>
Results.SignOut(new AuthenticationProperties
{
RedirectUri = "/"
}, authenticationSchemes: ["KitSSO", CookieAuthenticationDefaults.AuthenticationScheme]));

3. 在控制器中保护资源

[Authorize(AuthenticationSchemes = CookieAuthenticationDefaults.AuthenticationScheme)]
public class HomeController : Controller
{
public IActionResult Index()
{
// User.Identity.Name — 用户名
// User.Claims — 包含 sub/name/email/role 等
return View();
}
}

三种重载方式

// 1. 使用默认 scheme "KitSSO"
services.AddKitSSO(options => { /* ... */ });

// 2. 自定义 scheme 名称
services.AddKitSSO("MyKitSSO", options => { /* ... */ });

// 3. 自定义 scheme + 显示名称
services.AddKitSSO("MyKitSSO", "MyKitSSO Display", options => { /* ... */ });

OIDC Discovery 机制

只需配置 Authority,SDK 会自动从 {Authority}/.well-known/openid-configuration 发现所有端点:

  • Authorization Endpoint → 用户授权
  • Token Endpoint → 换取 Token
  • UserInfo Endpoint → 获取用户信息

无需手动配置这些端点地址。

工作原理

┌──────────────┐ ┌──────────────┐ ┌──────────────┐
│ 应用(SPA/ │ │ KitSSO │ │ 你的 API │
│ MVC/Blazor) │ │ Auth Server │ │ (Resource) │
└──────┬───────┘ └──────┬───────┘ └──────┬───────┘
│ │ │
│ 1. /login 跳转 │ │
│─────────────────────>│ │
│ │ │
│ │ 2. 用户登录/授权 │
│<─────────────────────│ │
│ │ │
│ 3. /signin-kitsso │ │
│ (code) │ │
│<─────────────────────│ │
│ │ │
│ 4. 换取 token │ │
│─────────────────────>│ │
│<─────────────────────│ │
│ access_token │ │
│ │ │
│ 5. API 请求 (Bearer token) │
│─────────────────────────────────────────────>│

KitSSOAuthOptions 选项

属性类型说明
AuthoritystringKitSSO 服务基地址
ClientIdstring客户端 ID
ClientSecretstring客户端密钥
CallbackPathstring回调路径
ResponseTypestring响应类型
UsePkcebool是否启用 PKCE
SaveTokensbool是否保存 token
GetClaimsFromUserInfoEndpointbool是否从 userinfo 获取 claims
ScopeIList<string>请求的 scope 列表

相关文档