Mastodon clients can sign in: OAuth with a persona per token
OpenIddict 7.7 (MongoDB stores, keys kept in Mongo so tokens survive
restarts) serves /oauth/authorize, /oauth/token, /oauth/revoke and the
discovery documents, including /.well-known/oauth-authorization-server:
- authorization code (PKCE optional) and client credentials, Mastodon's
scopes including the granular ones, non-expiring reference tokens,
`created_at` in the token response, and the urn:ietf:wg:oauth:2.0:oob
page that shows the code;
- /oauth/login signs the private login into a fifteen-minute cookie that
only /oauth sees (rate limited, antiforgery-protected); /oauth/authorize
then asks which persona the application acts as. The token's subject
is that persona's id and nothing else; no root id reaches a token, an
authorization or a log line;
- the token exchange refuses a persona whose login is banned or deleted,
and every API request checks the same.
/api/v1/apps registers applications dynamically, /api/v1/apps/
verify_credentials, /api/v1/instance (v1 and v2, "4.2.0 (compatible;
PrivaPub)") and verify_credentials answer in Mastodon's shapes: snake_case
with explicit nulls, Rails-style parameters from query, form or JSON,
{"error": ...} on failure, Link paging. CORS exposes Link.
/api goes to OpenIddict validation and everything else to the existing
JWT; the JWT failure handler no longer sends the exception and stack trace
to the client.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012CzABvBkbcFqoHdmi8b9WB
This commit is contained in:
1 parent
e6a6fe46d7
commit
4d9be37c1c
22 files changed
+1394
-7
No files matched your search
@@ -0,0 +1,111 @@
|
||||
using Microsoft.AspNetCore;
|
||||
using Microsoft.AspNetCore.Authentication.Cookies;
|
||||
using Microsoft.Extensions.Options;
|
||||
using Microsoft.IdentityModel.Tokens;
|
||||
|
||||
using MongoDB.Driver;
|
||||
using MongoDB.Entities;
|
||||
|
||||
using OpenIddict.Abstractions;
|
||||
using OpenIddict.Server;
|
||||
using OpenIddict.Server.AspNetCore;
|
||||
|
||||
using PrivaPub.Models;
|
||||
|
||||
using System.Net;
|
||||
|
||||
using static OpenIddict.Server.OpenIddictServerEvents;
|
||||
|
||||
namespace PrivaPub.Api.Mastodon.Auth
|
||||
{
|
||||
public static class OAuthSetup
|
||||
{
|
||||
public const string LoginScheme = "PrivaPub.OAuth";
|
||||
public const string OutOfBand = "urn:ietf:wg:oauth:2.0:oob";
|
||||
|
||||
public static IServiceCollection PrivaPubOAuth(this IServiceCollection services, IWebHostEnvironment environment)
|
||||
{
|
||||
services.AddSingleton<IMongoDatabase>(_ => DB.Default.Database());
|
||||
|
||||
services.AddAuthentication()
|
||||
.AddCookie(LoginScheme, options =>
|
||||
{
|
||||
options.Cookie.Name = "privapub.oauth";
|
||||
options.Cookie.Path = "/oauth";
|
||||
options.Cookie.HttpOnly = true;
|
||||
options.Cookie.SameSite = SameSiteMode.Lax;
|
||||
options.Cookie.SecurePolicy = CookieSecurePolicy.SameAsRequest;
|
||||
options.ExpireTimeSpan = TimeSpan.FromMinutes(15);
|
||||
options.SlidingExpiration = false;
|
||||
options.LoginPath = "/oauth/login";
|
||||
});
|
||||
|
||||
services.AddOpenIddict()
|
||||
.AddCore(options => options.UseMongoDb())
|
||||
.AddServer(options =>
|
||||
{
|
||||
options.SetAuthorizationEndpointUris("/oauth/authorize")
|
||||
.SetTokenEndpointUris("/oauth/token")
|
||||
.SetRevocationEndpointUris("/oauth/revoke")
|
||||
.SetConfigurationEndpointUris("/.well-known/openid-configuration", "/.well-known/oauth-authorization-server");
|
||||
options.AllowAuthorizationCodeFlow().AllowClientCredentialsFlow();
|
||||
options.RegisterScopes(MastodonScopes.All);
|
||||
options.UseReferenceAccessTokens();
|
||||
options.SetAccessTokenLifetime(null);
|
||||
options.SetAuthorizationCodeLifetime(TimeSpan.FromMinutes(10));
|
||||
options.DisableAccessTokenEncryption();
|
||||
|
||||
var aspNetCore = options.UseAspNetCore()
|
||||
.EnableAuthorizationEndpointPassthrough()
|
||||
.EnableTokenEndpointPassthrough();
|
||||
if (!environment.IsProduction())
|
||||
aspNetCore.DisableTransportSecurityRequirement();
|
||||
|
||||
options.AddEventHandler<ApplyAuthorizationResponseContext>(builder => builder.UseInlineHandler(OutOfBandCode)
|
||||
.SetOrder(OpenIddictServerAspNetCoreHandlers.Authentication.ProcessFormPostResponse.Descriptor.Order - 1_000)
|
||||
.SetType(OpenIddictServerHandlerType.Custom));
|
||||
options.AddEventHandler<ApplyTokenResponseContext>(builder => builder.UseInlineHandler(context =>
|
||||
{
|
||||
if (context.Response.AccessToken != default)
|
||||
context.Response["created_at"] = DateTimeOffset.UtcNow.ToUnixTimeSeconds();
|
||||
return default;
|
||||
}));
|
||||
})
|
||||
.AddValidation(options =>
|
||||
{
|
||||
options.UseLocalServer();
|
||||
options.UseAspNetCore();
|
||||
});
|
||||
|
||||
services.AddOptions<OpenIddictServerOptions>().Configure<IOptionsMonitor<AppConfiguration>>((options, app) =>
|
||||
{
|
||||
options.Issuer = new Uri(app.CurrentValue.BackendBaseAddress.TrimEnd('/') + "/");
|
||||
options.SigningCredentials.Add(new SigningCredentials(OidcKey.Load(OidcKey.Signing), SecurityAlgorithms.RsaSha256));
|
||||
options.EncryptionCredentials.Add(new EncryptingCredentials(OidcKey.Load(OidcKey.Encryption),
|
||||
SecurityAlgorithms.RsaOAEP, SecurityAlgorithms.Aes256CbcHmacSha512));
|
||||
});
|
||||
return services;
|
||||
}
|
||||
|
||||
static async ValueTask OutOfBandCode(ApplyAuthorizationResponseContext context)
|
||||
{
|
||||
if (context.RedirectUri != OutOfBand || context.Response.Code == default)
|
||||
return;
|
||||
var http = context.Transaction.GetHttpRequest()?.HttpContext;
|
||||
if (http == default)
|
||||
return;
|
||||
var code = WebUtility.HtmlEncode(context.Response.Code);
|
||||
http.Response.StatusCode = StatusCodes.Status200OK;
|
||||
http.Response.ContentType = "text/html; charset=utf-8";
|
||||
http.Response.Headers["Content-Security-Policy"] = "default-src 'none'; style-src 'unsafe-inline'";
|
||||
http.Response.Headers["Cache-Control"] = "no-store";
|
||||
await http.Response.WriteAsync($$"""
|
||||
<!DOCTYPE html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<title>Authorization code</title><style>body{font:16px/1.5 system-ui,sans-serif;max-width:480px;margin:48px auto;padding:0 16px}
|
||||
code{display:block;font-size:1.1rem;padding:12px;border:1px solid #ccc;word-break:break-all}</style></head>
|
||||
<body><h1>Authorization code</h1><p>Copy this code into the application:</p><code>{{code}}</code></body></html>
|
||||
""");
|
||||
context.HandleRequest();
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user