简体   繁体   中英

Role-based authorization with ASP.NET Core 5.0

I can't define my Admin, Company, Agency roles because

services.AddDefaultIdentity<IdentityUser>()
        .AddRoles<IdentityRole>()
        .AddEntityFrameworkStores<ApplicationDbContext>();

is not working or is not defining and it gives me an error

Error   CS1061  'IServiceCollection' does not contain a definition for 'AddDefaultIdentity' and no accessible extension method 'AddDefaultIdentity' accepting a first argument of type 'IServiceCollection' could be found (are you missing a using directive or an assembly reference?)

Here is my ConfigureServices method:

public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc();
    services.AddControllersWithViews();
    services.AddDbContext<TradeTurkDBContext>();
    services.AddDefaultIdentity<IdentityUser>()
            .AddRoles<IdentityRole>()
            .AddEntityFrameworkStores<TradeTurkDBContext>();

    services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
            .AddCookie(x =>
            {
                ...
            });
    services.AddMvc(config =>
        {
            ...
        });
}

And here is my using libraries

using BL.TradeTurk;
using DAL.TradeTurk;
using Entities.TradeTurk;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Identity;
using System.Security.Claims;

Can anyone tell me which part I am missing?

I looked at that AddRoles part in the Microsoft sources and there is nothing different my code and their source code.

Here is Microsoft source down to the page.

I did it in .net5 with customized identity as below:

  • create custom user and role:
public class AppUser : IdentityUser
{
}

public class AppRole : IdentityRole
{
}

public class AppUserRole : IdentityUserRole<string>
{
    public virtual AppUser User { get; set; }
    public virtual AppRole Role { get; set; }
}
  • Create custom db context:
public class ApplicationDbContext : IdentityDbContext<AppUser, AppRole, string, IdentityUserClaim<string>, AppUserRole, IdentityUserLogin<string>, IdentityRoleClaim<string>, IdentityUserToken<string>>
{
    public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options)
    {
    }

    protected override void OnModelCreating(ModelBuilder builder)
    {
        base.OnModelCreating(builder);
    } 
}
  • Register custom db context and identity classes in startup:
services.AddDbContext<ApplicationDbContext>(options => //...);
services.AddIdentity<AppUser, AppRole>(options => options.SignIn.RequireConfirmedAccount = true)
        .AddEntityFrameworkStores<ApplicationDbContext>()
        .AddDefaultUI()
        .AddDefaultTokenProviders();
  • Finally define role based authorization:
services.AddAuthorization(ops =>
{
    ops.AddPolicy("RequireAdmins", policy => policy.RequireRole("Admins"));
});

services.AddRazorPages()
        .AddRazorPagesOptions(ops =>
        {
                ops.Conventions.AuthorizeFolder("/", "RequireAdmins");
        });

I think The problem was in the order of Authentication and Authorization in the pipeline, Authentication should always be placed before Authorization. Change your middleware order in Configure method like below:-

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
            if (env.IsDevelopment())
                app.UseDeveloperExceptionPage();
            else
                app.UseExceptionHandler("/Home/Error");

            app.UseStaticFiles();
            app.UseRouting();

            app.UseAuthentication();
            app.UseAuthorization();
                
            app.UseEndpoints(endpoints =>
                {
                    endpoints.MapControllers();
                    endpoints.MapControllerRoute(
                        name: "default",
                        pattern: "{controller=Account}/{action=Login}/{id?}");
                });
}

Try using services.AddIdentityCore().AddRoles();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM