【发布时间】:2018-10-07 07:38:34
【问题描述】:
我将 ASP.Net MVC Core 应用程序从 1.1 升级到 2.1,包括将 ASP.Net Identity 从 1.1 迁移到 2.1。
我得到了工作,包括使用 Sqlite 进行 ASP.Net Identity EntityFramework 集成。
我的startup.cs 配置看起来像this:
services.AddDefaultIdentity<IdentityUser>()
.AddEntityFrameworkStores<ApplicationDbContext>();
services.Configure<IdentityOptions>(options =>
{
// Password settings.
options.Password.RequireDigit = true;
options.Password.RequireLowercase = true;
options.Password.RequireNonAlphanumeric = true;
options.Password.RequireUppercase = true;
options.Password.RequiredLength = 6;
options.Password.RequiredUniqueChars = 1;
// Lockout settings.
options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(5);
options.Lockout.MaxFailedAccessAttempts = 5;
options.Lockout.AllowedForNewUsers = true;
// User settings.
options.User.AllowedUserNameCharacters =
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._@+";
options.User.RequireUniqueEmail = false;
});
services.AddAuthentication()
.AddMicrosoftAccount(options =>
{
options.ClientId = Configuration["Authentication:Microsoft:ClientId"];
options.ClientSecret = Configuration["Authentication:Microsoft:ClientSecret"];
});
services.AddAuthorization(options =>
{
options.AddPolicy(PolicyNames.RequireTauchbold, policy => policy.RequireRole(Rolenames.Tauchbold));
});
在 Configure() 中我有:
app.UseAuthentication();
然后在我的控制器中我有:
[Authorize(Policy = PolicyNames.RequireTauchbold)]
public class EventController : Controller
{
...
可以在 GitHub 上找到完整的源代码。
问题
问题是即使我正确登录并分配了角色,对控制器的上述检查总是返回“拒绝访问”。我不知道这里会出错。有人知道我会想念什么here吗?
更新
我认为,普通的空 [Authorize] 属性有效(强制登录)但 [Authorize(Policy = '...')] 不识别角色。我检查了数据库表,但它们对我来说看起来不错。除了ÀspNetUsers、AspNetRoles 和AspNetUserRoles 之外,我还需要在数据库中配置其他任何内容吗?
更新 2:
我使用@itminus 的解决方案让它工作,但必须在启动时添加对AddDefaultUI() 的调用才能使登录和注册再次工作。所以我的启动现在包含这些行来配置身份:
services.AddIdentity<IdentityUser, IdentityRole>()
.AddRoleManager<RoleManager<IdentityRole>>()
.AddDefaultUI()
.AddEntityFrameworkStores<ApplicationDbContext>();
【问题讨论】:
标签: c# asp.net-core asp.net-core-mvc asp.net-core-identity