基于角色的授权在我的代码中不起作用,如果我缺少任何内容,请指导我。 我的项目在.net core 3.0框架上。
身份验证正常,但授权不起作用。
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
public void ConfigureServices(IServiceCollection services)
{
services.Configure<CookiePolicyOptions>(options =>
{
options.CheckConsentNeeded = context => true;
options.MinimumSameSitePolicy = SameSiteMode.None;
});
services.Configure<CookieTempDataProviderOptions>(options =>
{
options.Cookie.IsEssential = true;
});
services.AddDbContextPool<ApplicationDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
services.AddIdentity<ApplicationUser, IdentityRole>(config =>
{
config.User.RequireUniqueEmail = true; // ���������� email
config.User.AllowedUserNameCharacters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 -._@+";
config.SignIn.RequireConfirmedEmail = false;
}).AddEntityFrameworkStores<ApplicationDbContext>()
.AddClaimsPrincipalFactory<MyUserClaimsPrincipalFactory>()
.AddDefaultTokenProviders();
services.AddMvc(config => {
var policy = new AuthorizationPolicyBuilder()
.RequireAuthenticatedUser()
.Build();
config.Filters.Add(new AuthorizeFilter(policy));
}).AddRazorPagesOptions(options =>
{
options.Conventions.AuthorizeFolder("/");
options.Conventions.AllowAnonymousToPage("/Error");
options.Conventions.AllowAnonymousToPage("/Account/AccessDenied");
options.Conventions.AllowAnonymousToPage("/Account/ConfirmEmail");
options.Conventions.AllowAnonymousToPage("/Account/ExternalLogin");
options.Conventions.AllowAnonymousToPage("/Account/ForgotPassword");
options.Conventions.AllowAnonymousToPage("/Account/ForgotPasswordConfirmation");
options.Conventions.AllowAnonymousToPage("/Account/Lockout");
options.Conventions.AllowAnonymousToPage("/Account/Login");
options.Conventions.AllowAnonymousToPage("/Account/LoginWith2fa");
options.Conventions.AllowAnonymousToPage("/Account/LoginWithRecoveryCode");
options.Conventions.AllowAnonymousToPage("/Account/Register");
options.Conventions.AllowAnonymousToPage("/Account/ResetPassword");
options.Conventions.AllowAnonymousToPage("/Account/ResetPasswordConfirmation");
options.Conventions.AllowAnonymousToPage("/Account/SignedOut");
})
.SetCompatibilityVersion(CompatibilityVersion.Latest);
services.AddControllersWithViews().AddRazorRuntimeCompilation();
services.Configure<MailManagerOptions>(Configuration.GetSection("Email"));
if (Configuration["Email:EmailProvider"] == "SendGrid")
{
services.Configure<SendGridAuthOptions>(Configuration.GetSection("Email:SendGrid"));
services.AddSingleton<IMailManager, SendGridMailManager>();
}
else
{
services.AddSingleton<IMailManager, EmptyMailManager>();
}
services.AddScoped<ProfileManager>();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Error");
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapRazorPages();
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Dashboards}/{action=Index}/{id?}");
});
}
}
并且我在控制器中使用Authorize,我向我的userid添加了admin角色,i在数据库中验证了我的userid已与Admin角色映射,[Authorize]正常运行,但是在参数中赋予角色后,始终在AccessDenied中返回>
[HttpGet]
[Authorize(Roles = "Admin")]
public IActionResult CreateRole()
{
return View();
}
MyUserClaimsPrincipalFactory代码:
public class MyUserClaimsPrincipalFactory : UserClaimsPrincipalFactory<ApplicationUser>
{
private readonly ApplicationDbContext _context;
public MyUserClaimsPrincipalFactory(UserManager<ApplicationUser> userManager,IOptions<IdentityOptions> optionsAccessor, ApplicationDbContext context)
: base(userManager, optionsAccessor)
{
_context = context;
}
protected override async Task<ClaimsIdentity> GenerateClaimsAsync(ApplicationUser user)
{
var identity = await base.GenerateClaimsAsync(user);
return identity;
}
}