Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET Core 2.0 Dynamic Authentication

When using .AddOpenIdConnect() within ConfigureServices, is it possible to change the ClientId and ClientSecret based on the host from the request?

I know the Startup itself doesn't have access to the HttpContext, but I was wondering if using a middleware would solve this where it would have access to the context.

I've tried following the below link, however my values are always null after it runs through the CustomAuthHandler ASP.NET Core 2.0 authentication middleware

like image 536
niko619 Avatar asked Jan 15 '18 08:01

niko619


1 Answers

I believe you can achieve your goal assigning function to RedirectToIdentityProvider property.

Invoked before redirecting to the identity provider to authenticate. This can be used to set ProtocolMessage.State that will be persisted through the authentication process. The ProtocolMessage can also be used to add or customize parameters sent to the identity provider.

public void ConfigureServices(IServiceCollection services)
{
    services
    .AddAuthentication()
    .AddOpenIdConnect(options =>
        {
            options.Events.OnRedirectToIdentityProvider = context =>
             {
                  // Retrieve identity from current HttpContext
                  var identity = context.HttpContext.User.Identity;

                  // Lookup for your client_id and client_secret
                  var clientId = "find your client id";
                  var clientSecret = "find your client secret";

                  // Assign client_id and client_secret
                  context.ProtocolMessage.ClientId = clientId;
                  context.ProtocolMessage.ClientSecret = clientSecret;

                  return Task.FromResult(0);
              };
         });
}

Related links

OpenIdConnectEvents.OnRedirectToIdentityProvider Property

like image 158
dropoutcoder Avatar answered Oct 16 '22 06:10

dropoutcoder