2026-10-01 11:52:31 +02:00
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 ());
2026-10-01 12:09:19 +02:00
services . AddHostedService < OAuthPruner >();
2026-10-01 11:52:31 +02:00
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" );
2026-10-04 10:03:46 +02:00
options . AllowAuthorizationCodeFlow (). AllowClientCredentialsFlow (). AllowTokenExchangeFlow ();
//the only subject token accepted is the root JWT, for PersonaExchange; OpenIddict's own tokens are not exchanged
options . Configure ( server =>
{
server . SubjectTokenTypes . Clear ();
server . SubjectTokenTypes . Add ( PersonaExchange . SubjectTokenType );
});
options . AddEventHandler ( RootJwtSubjectToken . Descriptor );
2026-10-01 11:52:31 +02:00
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 ));
2026-10-18 09:18:26 +02:00
// a revoked token takes its Web Push subscription with it (R9), once OpenIddict has revoked it
options . AddEventHandler < HandleRevocationRequestContext >( builder => builder . UseInlineHandler ( async context =>
{
if ( context . GenericTokenPrincipal ?. GetTokenId () is { Length : > 0 } tokenId )
await PrivaPub . Domain . Social . WebPush . ForgetToken ( tokenId );
})
. SetOrder ( OpenIddictServerHandlers . Revocation . RevokeToken . Descriptor . Order + 1_000 )
. SetType ( OpenIddictServerHandlerType . Custom ));
// Mastodon 4.4's userinfo (Controllers/UserinfoController), named in the authorization server's metadata
options . AddEventHandler < HandleConfigurationRequestContext >( builder => builder . UseInlineHandler ( context =>
{
if ( context . Issuer != default )
context . UserInfoEndpoint = new Uri ( context . Issuer , Controllers . UserinfoController . Path . TrimStart ( '/' ));
return default ;
})
. SetOrder ( OpenIddictServerHandlers . Discovery . AttachEndpoints . Descriptor . Order + 1_000 )
. SetType ( OpenIddictServerHandlerType . Custom ));
2026-10-01 11:52:31 +02:00
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 ;
}
2026-11-10 01:24:43 +01:00
[System.Diagnostics.CodeAnalysis.SuppressMessage("HouseRules", "HR0003", Justification = "An OpenIddict inline handler: its signature is fixed and the request's token travels on the context.")]
2026-10-01 11:52:31 +02:00
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 : 16 px / 1.5 system - ui , sans - serif ; max - width : 480 px ; margin : 48 px auto ; padding : 0 16 px }
code { display : block ; font - size : 1.1 rem ; padding : 12 px ; border : 1 px 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 ();
}
}
}