したがって、この問題を解決しようとする長い一日の後に、コア2.0での新しい単一ミドルウェアセットアップ用にカスタム認証ハンドラーを作成する方法をMicrosoftがどのように求めているのか、ようやくわかりました。
MSDNのドキュメントをいくつか調べたところAuthenticationHandler<TOption>、IAuthenticationHandlerインターフェイスを実装するというクラスが見つかりました。
そこから、https://github.com/aspnet/Securityにある既存の認証スキームを含むコードベース全体を見つけました
これらの1つの内部では、MicrosoftがJwtBearer認証スキームを実装する方法を示しています。(https://github.com/aspnet/Security/tree/master/src/Microsoft.AspNetCore.Authentication.JwtBearer)
私はそのコードのほとんどを新しいフォルダーにコピーし、に関係するすべてのことをクリアしましたJwtBearer。
ではJwtBearerHandlerクラス(拡張AuthenticationHandler<>)、のためのオーバーライドがありますTask<AuthenticateResult> HandleAuthenticateAsync()
カスタムトークンサーバーを介してクレームを設定するための古いミドルウェアを追加しまし200 OKた401 Unauthorizedが、トークンが無効でクレームが設定されていない場合に、代わりにを吐き出すだけで、権限に関する問題が発生していました。
Task HandleChallengeAsync(AuthenticationProperties properties)なんらかの理由[Authorize(Roles="")]で、コントローラでアクセス権を設定するために使用されるものをオーバーライドしたことに気付きました
このオーバーライドを削除した後、コードは機能し、401アクセス許可が一致しない場合に正常にスローされました。
このことから、メインお持ち帰りは今カスタムミドルウェアを使用することができないということです、あなたはそれを介して、実装する必要がありAuthenticationHandler<>、あなたが設定する必要がDefaultAuthenticateSchemeとDefaultChallengeScheme使用した場合services.AddAuthentication(...)。
これがどのように見えるかの例を次に示します。
Startup.cs / ConfigureServices()に以下を追加します:
services.AddAuthentication(options =>
{
    // the scheme name has to match the value we're going to use in AuthenticationBuilder.AddScheme(...)
    options.DefaultAuthenticateScheme = "Custom Scheme";
    options.DefaultChallengeScheme = "Custom Scheme";
})
.AddCustomAuth(o => { });
Startup.cs / Configure()に追加:
app.UseAuthentication();
新しいファイルCustomAuthExtensions.csを作成します。
public static class CustomAuthExtensions
{
    public static AuthenticationBuilder AddCustomAuth(this AuthenticationBuilder builder, Action<CustomAuthOptions> configureOptions)
    {
        return builder.AddScheme<CustomAuthOptions, CustomAuthHandler>("Custom Scheme", "Custom Auth", configureOptions);
    }
}
新しいファイルCustomAuthOptions.csを作成します。
public class CustomAuthOptions: AuthenticationSchemeOptions
{
    public CustomAuthOptions()
    {
    }
}
新しいファイルCustomAuthHandler.csを作成します。
internal class CustomAuthHandler : AuthenticationHandler<CustomAuthOptions>
{
    public CustomAuthHandler(IOptionsMonitor<CustomAuthOptions> options, ILoggerFactory logger, UrlEncoder encoder, ISystemClock clock) : base(options, logger, encoder, clock)
    {
        // store custom services here...
    }
    protected override async Task<AuthenticateResult> HandleAuthenticateAsync()
    {
        // build the claims and put them in "Context"; you need to import the Microsoft.AspNetCore.Authentication package
        return AuthenticateResult.NoResult();
    }
}