ASP.NET Core 2.0 authentication based on host name

可紊 提交于 2019-12-11 02:34:30

问题


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:

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.

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.

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.


回答1:


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. 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 => { });


来源:https://stackoverflow.com/questions/50104753/asp-net-core-2-0-authentication-based-on-host-name

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!