[英]ASP.NET Core 2.0 authentication based on host name
我會說帶有身份驗證的經典ASP.NET Core 2.0應用程序包括在Startup.cs文件的ConfigureServices
方法中添加所需的身份驗證服務:
services.AddAuthentication().AddFacebook(facebookOptions =>
{
facebookOptions.AppId = Configuration["Authentication:Facebook:AppId"];
facebookOptions.AppSecret = Configuration["Authentication:Facebook:AppSecret"];
});
只要在調用ConfigurationServices
方法期間知道身份驗證配置並且對於所有請求都相同,就可以了。
我們的案例需要不同的身份驗證配置,假設基於主機名:
company1.example.com // has own authentication configuration
company2.example.com // has own (probably different) authentication
有關更多詳細信息,company1僅配置了Facebook,company2僅配置了Google身份驗證。
問題 :是否可以對每個主機或每個請求使用不同的身份驗證? 例如,一旦我知道公司,我就可以加載和使用與此請求相關的身份驗證配置。
有幾種方法可以做到這一點。 在Facebook和Google的方案事件中包括使用IConfiguration
或將http上下文作為服務訪問。 這是最干凈的方法之一。 您可以制定自己的方案,如下所示:
public class MyCustomAuth : AuthenticationHandler<AuthenticationSchemeOptions>
{
public const string SchemeName = "MyCustom";
public MyCustomAuth(IOptionsMonitor<AuthenticationSchemeOptions> options, ILoggerFactory
logger, UrlEncoder encoder, ISystemClock clock) : base(options, logger, encoder, clock)
{
}
protected override async Task HandleChallengeAsync(AuthenticationProperties properties)
{
if (Request.Host.Value == "")
{
await Context.ChallengeAsync(GoogleDefaults.AuthenticationScheme);
}
await Context.ChallengeAsync(FacebookDefaults.AuthenticationScheme);
}
protected override async Task<AuthenticateResult> HandleAuthenticateAsync()
{
if (Request.Host.Value == "")
{
return await Context.AuthenticateAsync(GoogleDefaults.AuthenticationScheme);
}
return await Context.AuthenticateAsync(FacebookDefaults.AuthenticationScheme);
}
}
您可以將所有內容添加到啟動中,並進行如下設置:
services.AddAuthentication(MyCustomAuth.SchemeName)
.AddCookie(...)
.AddFacebook(...)
.AddGoogle(...)
.AddScheme<AuthenticationSchemeOptions, MyCustomAuth>(MyCustomAuth.SchemeName, opts => { });
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.