この問題を解決しようとしていた長い一日の後、私は最終的に、コア2.0の新しいシングルミドルウェア設定用のカスタム認証ハンドラをマイクロソフトがどのように作りたいかを考え出しました。
MSDNのドキュメントを調べたところ、AuthenticationHandler<TOption>
というクラスが見つかりました。これはIAuthenticationHandler
インターフェイスを実装しています。
そこから、私はこれらのいずれかの内部https://github.com/aspnet/Security
にある既存の認証スキームと全体のコードベースを発見し、それはMicrosoftがJwtBearer認証スキームを実装する方法を示しています。 (https://github.com/aspnet/Security/tree/dev/src/Microsoft.AspNetCore.Authentication.JwtBearer)
ほとんどのコードを新しいフォルダにコピーして、JwtBearer
と関係のあるものをすべてクリアしました。
(AuthenticationHandler<>
を拡張)JwtBearerHandler
クラスでは、私はちょうど吐き、カスタムトークンサーバを介しての請求を設定し、まだ権限でいくつかの問題に遭遇したために私たちの古いミドルウェアに追加Task<AuthenticateResult> HandleAuthenticateAsync()
のオーバーライドがありますトークンが無効であり、クレームが設定されていない場合は401 Unauthorized
の代わりにを出してください。
コントローラー内で[Authorize(Roles="")]
を介してアクセス許可を設定するために何らかの理由でオーバーライドされたTask HandleChallengeAsync(AuthenticationProperties properties)
を認識しました。
このオーバーライドを除去した後、コードが働いていた、との許可が一致しませんでしたときに成功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 /設定では()を追加します
app.UseAuthentication();
はここで、これはすべてどのように見えるかの例です
public static class CustomAuthExtensions
{
public static AuthenticationBuilder AddCustomAuth(this AuthenticationBuilder builder, Action<CustomAuthOptions> configureOptions)
{
return builder.AddScheme<CustomAuthOptions, CustomAuthHandler>("Custom Scheme", "Custom Auth", configureOptions);
}
}
0新しいファイルを作成しますCustomAuthExtensions.cs
それは2つのスキームを言いますが、それはuが認証HTTPSに率い与えるにもかかわらず、このリンクを試してみてください新しいファイル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();
}
}
を作成
新しいファイルCustomAuthOptions.csを作成します。 ://wildermuth.com/2017/08/19/Two-AuthorizationSchemes-in-ASP-NET-Core-2 –
あなたのコードを追加してみることができますか?私はcore2.0でJWTに問題があることを知っています - 起動時にそれを移動させるケースでした – Webezine