[英]How to add identity based on roles to Razor Pages app?
I'm setting up a new Razor Pages app and I want to add roles-based authorization. 我正在设置一个新的Razor Pages应用程序,我想添加基于角色的授权。 There is a lot of tutorials on the web how to do it with an ASP.NET MVC app but not with Razor pages.
网上有很多教程如何使用ASP.NET MVC应用程序而不是Razor页面。 I have tried few solutions but nothing works for me.
我尝试过很少的解决方案,但对我来说没什么用。 At the moment I have a problem how to seed db with roles and add this roles to every new registered user.
目前,我遇到了如何使用角色为db生成种子并将此角色添加到每个新注册用户的问题。
This is how my Startup.cs
looks: 这就是我的
Startup.cs
样子:
public async Task ConfigureServices(IServiceCollection services)
{
var serviceProvider = services.BuildServiceProvider();
services.Configure<CookiePolicyOptions>(options =>
{
// This lambda determines whether user consent for non-essential cookies is needed for a given request.
options.CheckConsentNeeded = context => true;
});
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(
Configuration.GetConnectionString("DefaultConnection")));
services.AddDefaultIdentity<IdentityUser>(config =>
{
config.SignIn.RequireConfirmedEmail = true;
})
.AddRoles<IdentityRole>()
.AddDefaultUI(UIFramework.Bootstrap4)
.AddEntityFrameworkStores<ApplicationDbContext>();
services.AddAuthorization(config =>
{
config.AddPolicy("RequireAdministratorRole",
policy => policy.RequireRole("Administrator"));
});
services.AddTransient<IEmailSender, EmailSender>();
services.Configure<AuthMessageSenderOptions>(Configuration);
services.AddRazorPages()
.AddNewtonsoftJson()
.AddRazorPagesOptions(options => {
options.Conventions.AuthorizePage("/Privacy", "Administrator");
});
await CreateRolesAsync(serviceProvider);
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseDatabaseErrorPage();
}
else
{
app.UseExceptionHandler("/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseCookiePolicy();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapRazorPages();
});
}
/// <summary>
/// Method that creates roles
/// </summary>
/// <param name="serviceProvider"></param>
/// <returns></returns>
private async Task CreateRolesAsync(IServiceProvider serviceProvider)
{
//adding custom roles
var RoleManager = serviceProvider.GetRequiredService<RoleManager<IdentityRole>>();
string[] roleNames = { "Admin", "Member", "Outcast" };
IdentityResult roleResult;
foreach (var roleName in roleNames)
{
//creating the roles and seeding them to the database
var roleExist = await RoleManager.RoleExistsAsync(roleName);
if (!roleExist)
{
roleResult = await RoleManager.CreateAsync(new IdentityRole(roleName));
}
}
}
Now this code threw an exception: 现在这段代码引发了一个异常:
System.InvalidOperationException: 'Unable to find the required services.
System.InvalidOperationException:'无法找到所需的服务。 Please add all the required services by calling 'IServiceCollection.AddAuthorizationPolicyEvaluator' inside the call to 'ConfigureServices(...)' in the application startup code.'
请通过在应用程序启动代码中调用'ConfigureServices(...)'中调用'IServiceCollection.AddAuthorizationPolicyEvaluator'来添加所有必需的服务。
Adding AddAuthorizationPolicyEvaluator
changes nothing. 添加
AddAuthorizationPolicyEvaluator
改变任何内容。
Any tips? 有小费吗?
Ok, I just make my app work properly :) I think I just post here my Startup.cs
code for future questions - maybe it will help someone. 好吧,我只是让我的应用程序正常工作:)我想我只是在这里发布我的
Startup.cs
代码以备将来的问题 - 也许它会帮助某人。
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.Configure<CookiePolicyOptions>(options =>
{
// This lambda determines whether user consent for non-essential cookies is needed for a given request.
options.CheckConsentNeeded = context => true;
});
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(
Configuration.GetConnectionString("DefaultConnection")));
services.AddDefaultIdentity<IdentityUser>(config =>
{
config.SignIn.RequireConfirmedEmail = true;
})
.AddRoles<IdentityRole>()
.AddDefaultUI(UIFramework.Bootstrap4)
.AddEntityFrameworkStores<ApplicationDbContext>();
services.AddAuthorization(config =>
{
config.AddPolicy("RequireAdministratorRole",
policy => policy.RequireRole("Administrator"));
config.AddPolicy("RequireMemberRole",
policy => policy.RequireRole("Member"));
});
services.AddTransient<IEmailSender, EmailSender>();
services.Configure<AuthMessageSenderOptions>(Configuration);
services.AddRazorPages()
.AddNewtonsoftJson()
.AddRazorPagesOptions(options => {
options.Conventions.AuthorizePage("/Privacy", "RequireAdministratorRole");
});
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IServiceProvider serviceProvider, UserManager<IdentityUser> userManager)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseDatabaseErrorPage();
}
else
{
app.UseExceptionHandler("/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseCookiePolicy();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapRazorPages();
});
CreateDatabase(app);
CreateRolesAsync(serviceProvider).Wait();
CreateSuperUser(userManager).Wait();
}
private async Task CreateSuperUser(UserManager<IdentityUser> userManager)
{
var superUser = new IdentityUser { UserName = Configuration["SuperUserLogin"], Email = Configuration["SuperUserLogin"] };
await userManager.CreateAsync(superUser, Configuration["SuperUserPassword"]);
var token = await userManager.GenerateEmailConfirmationTokenAsync(superUser);
await userManager.ConfirmEmailAsync(superUser, token);
await userManager.AddToRoleAsync(superUser, "Admin");
}
private void CreateDatabase(IApplicationBuilder app)
{
using (var serviceScope = app.ApplicationServices.GetService<IServiceScopeFactory>().CreateScope())
{
var context = serviceScope.ServiceProvider.GetRequiredService<ApplicationDbContext>();
context.Database.EnsureCreated();
}
}
private async Task CreateRolesAsync(IServiceProvider serviceProvider)
{
//adding custom roles
var RoleManager = serviceProvider.GetRequiredService<RoleManager<IdentityRole>>();
string[] roleNames = { "Admin", "Member", "Outcast" };
IdentityResult roleResult;
foreach (var roleName in roleNames)
{
//creating the roles and seeding them to the database
var roleExist = await RoleManager.RoleExistsAsync(roleName);
if (!roleExist)
{
roleResult = await RoleManager.CreateAsync(new IdentityRole(roleName));
}
}
}
}
Generally the application on startup just creates new database, adds "Admin", "Member" and "Outcast" roles and the at the end creates superUser account based on user-secret credentials. 通常,启动时的应用程序只创建新数据库,添加“Admin”,“Member”和“Outcast”角色,最后根据用户机密凭证创建超级用户帐户。 Additionaly in
Register.cshtml.cs
file I have a line that adds default role "Member" to new members 另外在
Register.cshtml.cs
文件中我有一行将默认角色“Member”添加到新成员
public async Task<IActionResult> OnPostAsync(string returnUrl = null)
{
returnUrl = returnUrl ?? Url.Content("~/");
if (ModelState.IsValid)
{
var user = new IdentityUser { UserName = Input.Email, Email = Input.Email };
var result = await _userManager.CreateAsync(user, Input.Password);
if (result.Succeeded)
{
_logger.LogInformation("User created a new account with password.");
await _userManager.AddToRoleAsync(user, "Member");
var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);
var callbackUrl = Url.Page(
"/Account/ConfirmEmail",
pageHandler: null,
values: new { userId = user.Id, code = code },
protocol: Request.Scheme);
await _emailSender.SendEmailAsync(Input.Email, "Confirm your email to get acces to Functionality Matrix pages",
$"Please confirm your account by <a href='{HtmlEncoder.Default.Encode(callbackUrl)}'>clicking here</a>.");
// Block autologin after registration
//await _signInManager.SignInAsync(user, isPersistent: false);
return Redirect("./ConfirmEmailInfo");
}
foreach (var error in result.Errors)
{
ModelState.AddModelError(string.Empty, error.Description);
}
}
// If we got this far, something failed, redisplay form
return Page();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.