所有IdentityServer4示例在配置期间对Authority
属性进行硬编码:
services.AddAuthentication(IdentityServerAuthenticationDefaults.AuthenticationScheme)
.AddIdentityServerAuthentication(options =>
{
options.Authority = "http://localhost:5000";
options.ApiName = "api";
options.RequireHttpsMetadata = Env.IsStaging() || Env.IsProduction();
});
我如何根据环境(即登台和制作)加载权限?
答案 0 :(得分:2)
这就是我们的工作:
我们为每个环境提供了不同的appSettings.json
个文件。
所有文件都包含IdentityServer的单独值。 e.g。
{
"IdentityServerSettings": {
"Authority": "http://localhost:5000",
"ApiName": "tb5api"
}
}
然后在Startup.cs类中,我们根据当前环境加载设置json文件。
private readonly IHostingEnvironment _env;
public IConfigurationRoot Configuration { get; }
public Startup(IHostingEnvironment env)
{
_env = env;
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
.AddEnvironmentVariables();
Configuration = builder.Build();
}
public void ConfigureServices(IServiceCollection services)
{
services.Configure<IdentityServerSettings>(Configuration.GetSection("IdentityServerSettings"));
......
然后我们有一个类将我们的设置加载到:
/// <summary>
/// This class is a representation of the configuration of the API for Identity Server
/// </summary>
public class IdentityServerSettings
{
// Authority is the Identity Server URL
public string Authority { get; set; }
// Current API/Resource Name
public string ApiName { get; set; }
}
然后,只要您需要IdentityServerSettings
,您可以将它们注入控制器或配置方法中:
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
#region Identity Server Config
var identityServerOptions = app.ApplicationServices.GetService<IOptions<IdentityServerSettings>>().Value;
// Setup Identity Server Options for this API -
app.UseIdentityServerAuthentication(new IdentityServerAuthenticationOptions
{
Authority = identityServerOptions.Authority,
RequireHttpsMetadata = false,
ApiName = identityServerOptions.ApiName,
NameClaimType = "username",
});
.......