簡體   English   中英

如何根據角色向Razor Pages應用添加身份?

[英]How to add identity based on roles to Razor Pages app?

我正在設置一個新的Razor Pages應用程序,我想添加基於角色的授權。 網上有很多教程如何使用ASP.NET MVC應用程序而不是Razor頁面。 我嘗試過很少的解決方案,但對我來說沒什么用。 目前,我遇到了如何使用角色為db生成種子並將此角色添加到每個新注冊用戶的問題。

這就是我的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));
            }
        }
}

現在這段代碼引發了一個異常:

System.InvalidOperationException:'無法找到所需的服務。 請通過在應用程序啟動代碼中調用'ConfigureServices(...)'中調用'IServiceCollection.AddAuthorizationPolicyEvaluator'來添加所有必需的服務。

添加AddAuthorizationPolicyEvaluator改變任何內容。

有小費嗎?

好吧,我只是讓我的應用程序正常工作:)我想我只是在這里發布我的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));
            }
        }
    }
}

通常,啟動時的應用程序只創建新數據庫,添加“Admin”,“Member”和“Outcast”角色,最后根據用戶機密憑證創建超級用戶帳戶。 另外在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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM