feat(auth): support RS256 + OIDC discovery (JWKS auto-fetch)
Build Docker Image / build (push) Has been cancelled
Build Docker Image / build (push) Has been cancelled
Add Jwt__Algorithm config to choose between HS256 (shared symmetric key, existing behavior, default) and RS256 (Authority-based OIDC discovery, public-key auto-fetch with periodic refresh). RS256 mode makes the server compatible with any standard OAuth 2.1 / OIDC provider (Logto, ZITADEL, Keycloak, Auth0) without requiring a shared secret. HS256 mode remains the default for minimal self-built AS setups.
This commit is contained in:
+41
-10
@@ -8,13 +8,19 @@ namespace ObsidianMcp.Auth;
|
||||
public static class JwtBearerSetup
|
||||
{
|
||||
/// <summary>
|
||||
/// 配置 HS256 JWT Bearer 认证。
|
||||
/// 支持 Current + Previous 双密钥,方便密钥轮换过渡期。
|
||||
/// 配置 JWT Bearer 认证。根据 JwtOptions.Algorithm 选择:
|
||||
/// <list type="bullet">
|
||||
/// <item><c>HS256</c>:与 AS 共享对称密钥(Current + Previous 双密钥用于轮换)。</item>
|
||||
/// <item><c>RS256</c>:委托 ASP.NET Core 通过 OIDC discovery 拉 JWKS,
|
||||
/// 自动刷新公钥(默认 24h),AS 端密钥轮换无需重启本服务。</item>
|
||||
/// </list>
|
||||
/// </summary>
|
||||
public static IServiceCollection AddObsidianJwtBearer(
|
||||
this IServiceCollection services,
|
||||
JwtOptions opts)
|
||||
{
|
||||
var algorithm = (opts.Algorithm ?? "HS256").Trim().ToUpperInvariant();
|
||||
|
||||
services
|
||||
.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
|
||||
.AddJwtBearer(options =>
|
||||
@@ -23,7 +29,7 @@ public static class JwtBearerSetup
|
||||
// ClaimTypes.NameIdentifier 之类的长 URI,下游 FindFirst("sub") 取不到。
|
||||
options.MapInboundClaims = false;
|
||||
|
||||
options.TokenValidationParameters = new TokenValidationParameters
|
||||
var tvp = new TokenValidationParameters
|
||||
{
|
||||
ValidateIssuer = true,
|
||||
ValidIssuer = opts.Issuer,
|
||||
@@ -32,25 +38,46 @@ public static class JwtBearerSetup
|
||||
ValidAudience = opts.Audience,
|
||||
|
||||
ValidateIssuerSigningKey = true,
|
||||
// Current 必须有值;Previous 可选(密钥轮换过渡期)。
|
||||
// ToList 物化一次,避免每次验签都重建 SymmetricSecurityKey。
|
||||
IssuerSigningKeys = BuildSigningKeys(opts).ToList(),
|
||||
|
||||
ValidateLifetime = true,
|
||||
ClockSkew = TimeSpan.FromMinutes(2),
|
||||
|
||||
// scope claim 的 claim type 直接保持原样,User.FindAll("scope") 能取到。
|
||||
NameClaimType = "sub",
|
||||
};
|
||||
|
||||
if (algorithm == "RS256")
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(opts.Issuer))
|
||||
throw new InvalidOperationException(
|
||||
"Jwt:Issuer 未配置,RS256 模式无法启动。");
|
||||
|
||||
// Authority = Issuer 时,JwtBearer 会自动从
|
||||
// <Issuer>/.well-known/openid-configuration 拉 OIDC 元数据,
|
||||
// 再从其中的 jwks_uri 拉公钥并周期性刷新。IssuerSigningKeys
|
||||
// 由 ConfigurationManager 在验签时动态注入,无需在此设置。
|
||||
options.Authority = opts.Issuer;
|
||||
options.RequireHttpsMetadata = !IsLocalhostUrl(opts.Issuer);
|
||||
}
|
||||
else if (algorithm == "HS256")
|
||||
{
|
||||
tvp.IssuerSigningKeys = BuildHs256Keys(opts).ToList();
|
||||
}
|
||||
else
|
||||
{
|
||||
throw new InvalidOperationException(
|
||||
$"Jwt:Algorithm '{opts.Algorithm}' 不支持。可选值:HS256, RS256");
|
||||
}
|
||||
|
||||
options.TokenValidationParameters = tvp;
|
||||
});
|
||||
|
||||
return services;
|
||||
}
|
||||
|
||||
private static IEnumerable<SecurityKey> BuildSigningKeys(JwtOptions opts)
|
||||
private static IEnumerable<SecurityKey> BuildHs256Keys(JwtOptions opts)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(opts.SigningKey.Current))
|
||||
throw new InvalidOperationException("Jwt:SigningKey:Current 未配置,服务无法启动。");
|
||||
throw new InvalidOperationException(
|
||||
"Jwt:SigningKey:Current 未配置,HS256 模式无法启动。");
|
||||
|
||||
yield return new SymmetricSecurityKey(
|
||||
Encoding.UTF8.GetBytes(opts.SigningKey.Current));
|
||||
@@ -59,4 +86,8 @@ public static class JwtBearerSetup
|
||||
yield return new SymmetricSecurityKey(
|
||||
Encoding.UTF8.GetBytes(opts.SigningKey.Previous));
|
||||
}
|
||||
|
||||
private static bool IsLocalhostUrl(string url) =>
|
||||
url.StartsWith("http://localhost", StringComparison.OrdinalIgnoreCase) ||
|
||||
url.StartsWith("http://127.0.0.1", StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
+13
-1
@@ -2,18 +2,30 @@ namespace ObsidianMcp.Config;
|
||||
|
||||
/// <summary>
|
||||
/// JWT 验签配置。
|
||||
/// 环境变量:Jwt__Issuer, Jwt__Audience, Jwt__SigningKey__Current, Jwt__SigningKey__Previous
|
||||
/// 环境变量:Jwt__Algorithm, Jwt__Issuer, Jwt__Audience, Jwt__SigningKey__Current, Jwt__SigningKey__Previous
|
||||
/// </summary>
|
||||
public class JwtOptions
|
||||
{
|
||||
public const string Section = "Jwt";
|
||||
|
||||
/// <summary>
|
||||
/// JWT 签名算法。
|
||||
/// <list type="bullet">
|
||||
/// <item><c>HS256</c>(默认):与 AS 共享对称密钥(SigningKey.Current 必填)。适合自建极简 AS。</item>
|
||||
/// <item><c>RS256</c>:从 Issuer 走 OIDC discovery 自动拉 JWKS(含自动刷新)。
|
||||
/// 适合任何标准 OAuth 2.1 / OIDC AS(Logto / ZITADEL / Keycloak / Auth0 等)。
|
||||
/// 要求 Issuer 暴露 <c>/.well-known/openid-configuration</c>。</item>
|
||||
/// </list>
|
||||
/// </summary>
|
||||
public string Algorithm { get; set; } = "HS256";
|
||||
|
||||
/// <summary>期望的 iss claim(你的 auth server 的 issuer URL),必须通过 env 注入</summary>
|
||||
public string Issuer { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>期望的 aud claim,默认 obsidian</summary>
|
||||
public string Audience { get; set; } = "obsidian";
|
||||
|
||||
/// <summary>HS256 模式使用;RS256 模式下忽略。</summary>
|
||||
public SigningKeyPair SigningKey { get; set; } = new();
|
||||
|
||||
public class SigningKeyPair
|
||||
|
||||
@@ -4,7 +4,12 @@ Read and write an Obsidian vault via [MCP (Model Context Protocol)](https://mode
|
||||
gated by OAuth-issued JWT bearer tokens.
|
||||
|
||||
This server pairs with any OAuth 2.1 + PKCE authorization server that can mint
|
||||
HS256 JWTs containing `aud`, `iss`, `sub`, `scope` claims. Bring your own AS.
|
||||
JWTs containing `aud`, `iss`, `sub`, `scope` claims. Two signing modes:
|
||||
|
||||
- **HS256** (default) — shared symmetric key between AS and this server. Use for self-built minimal AS.
|
||||
- **RS256** — fetches JWKS automatically via OIDC discovery from `<Issuer>/.well-known/openid-configuration`. Use with any standard provider: [Logto](https://logto.io), [ZITADEL](https://zitadel.com), [Keycloak](https://www.keycloak.org), [Auth0](https://auth0.com), etc.
|
||||
|
||||
See [Choosing an AS](#choosing-an-as) below for setup guidance.
|
||||
|
||||
## Architecture
|
||||
|
||||
@@ -47,10 +52,11 @@ prefixes (double underscore = nested section). Production values must be injecte
|
||||
| `Vault__Root` | `/vault` | yes | Vault root directory inside the container |
|
||||
| `Vault__Blacklist__0` | — | no | Extra path segments to deny (`.obsidian`, `.trash`, `.git` are always denied) |
|
||||
| `Vault__WriteWhitelist__0` | — | for write tools | Writable path entries (see below) |
|
||||
| `Jwt__Algorithm` | `HS256` | no | `HS256` or `RS256` |
|
||||
| `Jwt__Issuer` | — | **yes** | Expected `iss` claim — your AS's issuer URL |
|
||||
| `Jwt__Audience` | `obsidian` | no | Expected `aud` claim |
|
||||
| `Jwt__SigningKey__Current` | — | **yes** | HS256 signing key, shared with your AS |
|
||||
| `Jwt__SigningKey__Previous` | — | no | Previous key during rotation window |
|
||||
| `Jwt__SigningKey__Current` | — | HS256 only | HS256 signing key, shared with your AS |
|
||||
| `Jwt__SigningKey__Previous` | — | no | Previous HS256 key during rotation window |
|
||||
| `Mcp__OAuthDiscovery__Issuer` | — | **yes** | `/.well-known/oauth-authorization-server` `issuer` field |
|
||||
| `Mcp__OAuthDiscovery__AuthorizationEndpoint` | — | **yes** | Your AS's `/authorize` URL |
|
||||
| `Mcp__OAuthDiscovery__TokenEndpoint` | — | **yes** | Your AS's `/token` URL |
|
||||
@@ -136,6 +142,35 @@ builds and pushes the image. It expects these repository Variables / Secrets:
|
||||
- `vars.IMAGE_OWNER` — registry owner/namespace
|
||||
- `secrets.PACKAGES_TOKEN` — registry push token
|
||||
|
||||
## Choosing an AS
|
||||
|
||||
Claude.ai chat enforces the full OAuth Authorization Code + PKCE flow against
|
||||
your MCP server's `/.well-known/oauth-authorization-server` endpoint — there
|
||||
is no bearer-token shortcut. Pick one of these paths:
|
||||
|
||||
**Hosted (fastest start, recommended for new setups)** — RS256 mode:
|
||||
|
||||
| Provider | Free tier | Notes |
|
||||
|---|---|---|
|
||||
| [Logto Cloud](https://logto.io) | 5000 MAU | Lightest, ~30 min setup |
|
||||
| [ZITADEL Cloud](https://zitadel.com) | 25k auths/month | More featureful, slightly heavier docs |
|
||||
|
||||
Set `Jwt__Algorithm=RS256` and `Jwt__Issuer=<your-tenant-issuer-URL>`.
|
||||
Public keys are fetched automatically from `<Issuer>/.well-known/openid-configuration`.
|
||||
|
||||
**Self-hosted, full-featured** — RS256 mode:
|
||||
[Keycloak](https://www.keycloak.org), [ZITADEL](https://github.com/zitadel/zitadel), [Logto](https://github.com/logto-io/logto), [Authentik](https://goauthentik.io).
|
||||
|
||||
**Self-hosted, minimal** — HS256 mode:
|
||||
Write your own ~500 LoC AS that issues HS256 JWTs with the right claims. The
|
||||
MCP server's `Jwt__SigningKey__Current` and the AS's signing key must match.
|
||||
|
||||
**Required AS features regardless of choice:**
|
||||
- OAuth 2.1 + PKCE (RFC 7636)
|
||||
- Dynamic Client Registration (RFC 7591) — so Claude.ai can self-register
|
||||
- `resource` parameter support (RFC 8707) — for audience-bound tokens
|
||||
- Custom scope support (`read:obsidian`, `write:obsidian`)
|
||||
|
||||
## Running tests
|
||||
|
||||
```bash
|
||||
|
||||
@@ -16,7 +16,9 @@
|
||||
},
|
||||
|
||||
// JWT 验签配置(生产值必须通过 env 覆盖)
|
||||
// Algorithm: "HS256"(默认,与 AS 共享 SigningKey)或 "RS256"(从 Issuer 走 OIDC discovery 拉 JWKS)
|
||||
"Jwt": {
|
||||
"Algorithm": "HS256",
|
||||
"Issuer": "",
|
||||
"Audience": "obsidian",
|
||||
"SigningKey": {
|
||||
|
||||
Reference in New Issue
Block a user