我有一个 Blazor 应用程序配置为使用 OpenId 进行身份验证(在本例中为 Auth0)。在我的 Program.cs 中我有这个:
var auth0Domain = builder.Configuration["Auth0:Domain"];
var auth0ClientId = builder.Configuration["Auth0:ClientId"];
if (!string.IsNullOrEmpty(auth0Domain) && !string.IsNullOrEmpty(auth0ClientId))
{
builder.Services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = Auth0Constants.AuthenticationScheme;
})
.AddOpenIdConnect("Auth0", options =>
{
options.Authority = $"https://{auth0Domain}";
options.ClientId = auth0ClientId;
//options.ClientSecret = builder.Configuration["Auth0:ClientSecret"];
options.ResponseType = "code";
options.SaveTokens = true;
options.CallbackPath = new PathString("/account/callback");
options.SkipUnrecognizedRequests = true; //ESTO RESOLVIO EL PROBLMA DE MESSAGE.STATE NULL
options.Scope.Clear();
options.Scope.Add("openid");
options.Scope.Add("profile");
options.Scope.Add("email");
});
}
else
{
builder.Services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
});
}
在我的 AccountController 中我有这个:
[HttpGet]
public async Task ExternalLogin(string redirectUrl)
{
string callbackUrl = redirectUrl + "account/callback";
//Console.WriteLine(callbackUrl);
var authenticationProperties = new LoginAuthenticationPropertiesBuilder()
.WithRedirectUri(callbackUrl)
.Build();
await HttpContext.ChallengeAsync(Auth0Constants.AuthenticationScheme, authenticationProperties);
}
我想要的是能够在执行 ChallengeAsync 之前修改 Domain 和 ClientId。我的应用程序需要处理不同的身份验证方式,具体取决于尝试身份验证的用户。我的用户位于一个数据库中,我在其中存储他们使用的身份验证类型。
我一直在寻找一种方法来从我的 Program.cs 中进行 OpenId 配置
当然您可以使用选项监视器进行修改,如下所示:
[HttpGet]
public async Task ExternalLogin(string redirectUrl)
{
...
var serviceProvider = HttpContext.RequestServices;
var optionsMonitor = serviceProvider.GetService<IOptionsMonitor<OpenIdConnectOptions>>();
var OIDC_options = optionsMonitor.Get(Auth0Constants.AuthenticationScheme);
OIDC_options.Authority = "new domain";
OIDC_options.ClientId = "new id";
//other changes
OIDC_options.TokenValidationParameters.ValidAudiences = new[] { "newAudience" };
await HttpContext.ChallengeAsync(Auth0Constants.AuthenticationScheme, authenticationProperties);
}