【发布时间】:2017-12-04 16:41:55
【问题描述】:
我正在尝试将 IdentityServer4 与资源所有者流程 + aspnet 身份一起使用,并将 api 嵌入到同一个项目中。
我测试了示例here on github,它工作正常。我能够在数据库中检索注册用户的令牌并使用此令牌从 api 获取受保护的资源。
api 示例与身份服务器分离,一旦将两者合并到一个项目中,我仍然能够获得令牌,但是我在尝试访问受保护的资源时得到 401 Unauthorized。不知何故,嵌入式 api 不再验证令牌。
这是Startup.cs 代码:
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
//(1)
services.AddIdentity<ApplicationUser, IdentityRole>()
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders();
services.AddMvc(config =>
{
var policy = new AuthorizationPolicyBuilder()
.RequireAuthenticatedUser()
.Build();
config.Filters.Add(new AuthorizeFilter(policy));
});
services
.AddIdentityServer()
.AddDeveloperSigningCredential()
.AddInMemoryPersistedGrants()
.AddInMemoryIdentityResources(Config.GetIdentityResources())
.AddInMemoryApiResources(Config.GetApiResources())
.AddInMemoryClients(Config.GetClients())
//(2)
.AddAspNetIdentity<ApplicationUser>();
//.AddTestUsers(Config.GetUsers());
var corsBuilder = new CorsPolicyBuilder();
corsBuilder.AllowAnyHeader();
corsBuilder.AllowAnyMethod();
corsBuilder.AllowAnyOrigin();
corsBuilder.AllowCredentials();
corsBuilder.WithExposedHeaders("Location");
services.AddCors(options =>
{
options.AddPolicy("CorsPolicy", corsBuilder.Build());
});
services.AddMvcCore()
.AddAuthorization()
.AddJsonFormatters();
services.AddAuthentication("Bearer")
.AddIdentityServerAuthentication(options =>
{
options.Authority = "http://localhost:51318";
options.RequireHttpsMetadata = false;
options.ApiName = "api";
});
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseBrowserLink();
}
else
{
app.UseExceptionHandler("/Home/Error");
}
app.UseStaticFiles();
app.UseCors("CorsPolicy");
app.UseIdentityServer();
app.UseAuthentication();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
请注意,如果我们通过注释(1) 中的代码并将(2) 中的代码更改为:
//(2)
//.AddAspNetIdentity<ApplicationUser>();
.AddTestUsers(Config.GetUsers());
整个系统正常工作,嵌入式api正常验证用户。
此代码中是否缺少某些内容?在现实生活场景中,由于成本效益,api 几乎总是嵌入到身份服务器中,有没有我可以用来使其工作的示例?
谢谢。
【问题讨论】:
-
那么您在
Config.GetUsers()中定义的用户和您在数据库中定义的用户有什么区别?顺便说一句,我不同意您的“在现实生活中”的说法,并且很少遇到绑定到 API 项目本身的身份服务器实现,即使在 API 是访问令牌的唯一使用者的情况下也是如此。将它们分开更容易/更清洁,而且对大多数公司而言,任何成本影响都非常小。 -
ApplicationUser是一个简单的Microsoft.AspNetCore.Identity.IdentityUser
标签: asp.net-core asp.net-identity identityserver4