我试图将IdentityServer4与资源所有者流+ aspnet标识一起使用,并将api嵌入同一项目中。
我在github上测试了示例,并且工作正常。我能够为数据库中的注册用户检索令牌,并使用此令牌从api获取受保护的资源。
api的示例与身份服务器分离,一旦两者都合并到一个项目中,我仍然能够获得令牌,但是Unauthorized
在尝试访问受保护的资源时却获得了401 。嵌入式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?}");
});
}
请注意,如果我们在内存中切换TestUser
而不是ApplicationUser
通过注释代码(1)
并将代码更改为来持久存储(2)
:
//(2)
//.AddAspNetIdentity<ApplicationUser>();
.AddTestUsers(Config.GetUsers());
整个系统正常工作,并且嵌入式api可以正常验证用户身份。
这段代码中缺少什么吗?在现实生活中,由于成本效益,该api几乎总是嵌入到身份服务器中,请问有什么示例可以使它起作用?
谢谢。
深入研究AspNet Identity源代码后,我意识到该AddIdentity
扩展正在做一些额外的工作来阻止验证令牌,但是如果没有令牌和AddEntityFrameworkStores
身份管理器的方法,则不能通过依赖项注入来设置身份管理器。
所以我们需要替换:
services.AddIdentity<ApplicationUser, IdentityRole>()
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders();
通过一段只执行依赖注入的代码:
services.TryAddScoped<IUserValidator<ApplicationUser>, UserValidator<ApplicationUser>>();
services.TryAddScoped<IPasswordValidator<ApplicationUser>, PasswordValidator<ApplicationUser>>();
services.TryAddScoped<IPasswordHasher<ApplicationUser>, PasswordHasher<ApplicationUser>>();
services.TryAddScoped<ILookupNormalizer, UpperInvariantLookupNormalizer>();
services.TryAddScoped<IRoleValidator<IdentityRole>, RoleValidator<IdentityRole>>();
services.TryAddScoped<IdentityErrorDescriber>();
services.TryAddScoped<ISecurityStampValidator, SecurityStampValidator<ApplicationUser>>();
services.TryAddScoped<IUserClaimsPrincipalFactory<ApplicationUser>, UserClaimsPrincipalFactory<ApplicationUser, IdentityRole>>();
services.TryAddScoped<UserManager<ApplicationUser>, AspNetUserManager<ApplicationUser>>();
services.TryAddScoped<SignInManager<ApplicationUser>, SignInManager<ApplicationUser>>();
services.TryAddScoped<RoleManager<IdentityRole>, AspNetRoleManager<IdentityRole>>();
services.TryAddScoped<IRoleStore<IdentityRole>, RoleStore<IdentityRole>>();
services.TryAddScoped<DbContext, ApplicationDbContext>();
services.TryAddScoped<IUserStore<ApplicationUser>, UserStore<ApplicationUser>>();
通过这样做,最终结果是使用AspNet Identity将可工作的身份服务器嵌入api。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句