[英]ASP.NET Core 2.0 authentication based on host name
I would say that classic ASP.NET Core 2.0 application with authentication consists of adding desired authentication service in ConfigureServices
method in the Startup.cs file: 我会说带有身份验证的经典ASP.NET Core 2.0应用程序包括在Startup.cs文件的
ConfigureServices
方法中添加所需的身份验证服务:
services.AddAuthentication().AddFacebook(facebookOptions =>
{
facebookOptions.AppId = Configuration["Authentication:Facebook:AppId"];
facebookOptions.AppSecret = Configuration["Authentication:Facebook:AppSecret"];
});
This is fine as long as the authentication configuration is known during the time when ConfigurationServices
method is called and is the same for all requests. 只要在调用
ConfigurationServices
方法期间知道身份验证配置并且对于所有请求都相同,就可以了。
Our case needs different authentication configuration, let say based on host name: 我们的案例需要不同的身份验证配置,假设基于主机名:
company1.example.com // has own authentication configuration
company2.example.com // has own (probably different) authentication
For more details company1 has configured only Facebook and company2 has configured only Google authentication. 有关更多详细信息,company1仅配置了Facebook,company2仅配置了Google身份验证。
Question : Is it possible to have different authentication for each host or otherwise for each request? 问题 :是否可以对每个主机或每个请求使用不同的身份验证? For instance once I know company I can load and use authentication configuration relevant for this request.
例如,一旦我知道公司,我就可以加载和使用与此请求相关的身份验证配置。
There are several ways of doing this. 有几种方法可以做到这一点。 Including using your
IConfiguration
or accessing http context as a service within your scheme events of facebook and google. 在Facebook和Google的方案事件中包括使用
IConfiguration
或将http上下文作为服务访问。 Here is one of the cleanest ways of doing this. 这是最干净的方法之一。 You can make your own scheme something like this:
您可以制定自己的方案,如下所示:
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);
}
}
You can add everything to your startup and set it up like this: 您可以将所有内容添加到启动中,并进行如下设置:
services.AddAuthentication(MyCustomAuth.SchemeName)
.AddCookie(...)
.AddFacebook(...)
.AddGoogle(...)
.AddScheme<AuthenticationSchemeOptions, MyCustomAuth>(MyCustomAuth.SchemeName, opts => { });
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.