services.AddAuthentication(options =>
{
options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
})
.AddCookie()
.AddOpenIdConnect(options =>
{
options.Authority = Configuration.GetValue("AuthServer:Authority");
options.ClientId = Configuration.GetValue("AuthServer:ClientId");
options.ClientSecret = Configuration.GetValue("AuthServer:ClientSecret");
options.ResponseType = "code";
options.RequireHttpsMetadata = false;
options.Scope.Add("openid");
options.Scope.Add("profile");
});
@inject Microsoft.AspNetCore.Components.Services.IUriHelper UriHelper
@{
var currentUri = UriHelper.GetAbsoluteUri();
var clientId = Configuration.GetValue("AuthServer:ClientId");
var redirectUris = Configuration.GetSection("AuthServer:RedirectUris").Get();
}
在上面的代码中,我们使用了 UriHelper 来获取当前的 URL(绝对 URI)。我们还使用 Configuration 来获取我们需要的配置值。
例如,您可以将 RedirectUris 传递给 OpenIdConnect 的 Options,如下所示:
.AddOpenIdConnect(options =>
{
// other options
options.RedirectUri = redirectUris[0];
})
请注意,我们可以使用 redirectUris[0] 来获取第一个 RedirectUri。如果您有多个 URI,您可以根据需要使用其中一个。
这样,您就可以从 _Host.cshtml 访问 ClientId 和 RedirectUris。