इसलिए, इस समस्या को हल करने के प्रयास के एक लंबे दिन के बाद, मैंने आखिरकार यह पता लगा लिया है कि कैसे Microsoft चाहता है कि हम कोर 2.0 में अपने नए सिंगल-मिडलवेयर सेटअप के लिए कस्टम प्रमाणीकरण हैंडलर बनाना चाहते हैं।
MSDN पर कुछ प्रलेखन के माध्यम से देखने के बाद, मैंने एक वर्ग पाया जो AuthenticationHandler<TOption>कि IAuthenticationHandlerइंटरफ़ेस को लागू करता है।
वहां से, मुझे https://github.com/aspnet/Security पर मौजूद मौजूदा प्रमाणीकरण योजनाओं के साथ एक पूरा कोडबेस मिला
इनमें से एक के अंदर, यह दिखाता है कि 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 =>
{
options.DefaultAuthenticateScheme = "Custom Scheme";
options.DefaultChallengeScheme = "Custom Scheme";
})
.AddCustomAuth(o => { });
Startup.cs / कॉन्फ़िगर () में जोड़ें:
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)
{
}
protected override async Task<AuthenticateResult> HandleAuthenticateAsync()
{
return AuthenticateResult.NoResult();
}
}