Доступ запрещен для администратора - PullRequest
0 голосов
/ 03 марта 2019

Я пытался добавить политику в свою область администратора моего веб-приложения и добавил моего пользователя-администратора и роль администратора в мои таблицы AspNetUsers, AspNetRoles и AspNetUserRoles, однако я не могуубедитесь, что подписанный мной пользователь является администратором.

AspNetUsers таблица

Id    |    UserName    |    NormalizedUserName    |    Email               |    NormalizedEmail
_______________________________________________________________________________________________
123   |    WebAdmin    |    WEBADMIN              |    admin@mysite.com    |    ADMIN@MYSITE.COM

AspNetRoles таблица

Id    |    Name    |    NormalizedName
_______________________________________
123   |    Admin   |    ADMIN
_______________________________________
321   |    User    |    USER

AspNetUserRoles таблица

UserId    |    RoleId
______________________
123       |    123

Я включил Identity в ConfirgureServices моего Startup класса

/// <summary>
/// This method gets called by the runtime. Use this method to add services to the container.
/// </summary>
/// <param name="services">Services to configure</param>
public void ConfigureServices(IServiceCollection services)
{
    // Regular Cookie Policy stuff
    services.Configure<CookiePolicyOptions>(options =>
    {
        // This lambda determines whether user consent for non-essential cookies is needed for a given request.
        options.CheckConsentNeeded = context => true;
        options.MinimumSameSitePolicy = SameSiteMode.None;
    });

    // Mailing service setup
    services.AddScoped<SmtpClient>((serviceProvider) =>
    {
        return new SmtpClient
        {
            Host = this.Configuration.GetValue<string>("Email:Smtp:Host"),
            Port = this.Configuration.GetValue<int>("Email:Smtp:Port"),
            UseDefaultCredentials = false,
            Credentials = new NetworkCredential(
                    this.Configuration.GetValue<string>("Email:Smtp:Username"), 
                    this.Configuration.GetValue<string>("Email:Smtp:Password")),
            EnableSsl = true
        };
    });

    // Connect to the Database
    services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(this.Configuration.GetConnectionString("DefaultConnection")));
    services.AddDbContext<WebSiteContext>(options => options.UseSqlServer(this.Configuration.GetConnectionString("DefaultConnection")));

    // Identity Stuff
    services.AddDefaultIdentity<IdentityUser>()
        .AddRoles<IdentityRole>()
        .AddDefaultTokenProviders()
        .AddEntityFrameworkStores<ApplicationDbContext>();

    // Configure Authorization
    services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

    // Authorization
    services.AddAuthorization(options =>
    {
        options.AddPolicy("RequireAdminRole", policy => policy.RequireRole("Admin"));
    });
}

Я использую все это также в моем Configure Методе

/// <summary>
/// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
/// </summary>
/// <param name="app">App being configured</param>
/// <param name="env">Environment the app is running in</param>
/// <param name="context">Injected <see cref="DbContext"/></param>
/// <param name="userManager">Injected <see cref="UserManager{TUser}"/></param>
/// <param name="roleManager">Injected <see cref="RoleManager{TRole}"/></param>
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ApplicationDbContext context, UserManager<IdentityUser> userManager, RoleManager<IdentityRole> roleManager)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
        app.UseDatabaseErrorPage();
    }
    else
    {
        app.UseExceptionHandler("/Home/Error");
        app.UseHsts();
    }

    // Set up the usings
    app.UseHttpsRedirection();
    app.UseStaticFiles();
    app.UseCookiePolicy();
    app.UseAuthentication();

    // Seed the Database on Startup
    Seeder.SeedDb(context, userManager, roleManager);

    // Use MVC
    app.UseMvc(routes =>
    {
        routes.MapRoute(
            name: "areas",
            template: "{area:exists}/{controller=Home}/{action=Index}/{id?}");

        routes.MapRoute(
            name: "default",
            template: "{controller=Home}/{action=Index}/{id?}");
    });
}

ManageController Контроллер для моей административной части имеет Authorize Декларацию

/// <summary>
/// ManageController - Controller for Managing Admin Stuff
/// </summary>
[Area("admin")]
[Route("admin/[controller]")]
[Authorize(Policy = "RequireAdminRole")]
public class ManageController : Controller
{
    /// <summary>
    /// Private instance of the <see cref="EmailViewModel"/> class
    /// </summary>
    private EmailViewModel emailViewModel;
    private SmtpClient smtpClient;

    /// <summary>
    /// Initializes a new instance of the <see cref="ManageController"/> class
    /// </summary>
    /// <param name="smtpClient"></param>
    public ManageController(SmtpClient smtpClient)
    {
        this.smtpClient = smtpClient;
    }


    /// <summary>
    /// HomePage for the admin management area
    /// </summary>
    /// <returns></returns>
    public IActionResult Index()
    {
        return View();
    }
}

Однако, когда я вхожу в систему как WebAdmin и перехожу в свою область admin/Manage, яполучить следующую ошибку:

Доступ запрещен - у вас нет доступа к этому ресурсу

Есть ли что-то, чего мне не хватает при проверке ролей в NET Core?

1 Ответ

0 голосов
/ 04 марта 2019

Я решил эту проблему.Проблема заключается в настройке службы идентификации.Мне нужно было использовать AddIdentity<IdentityUser, IdentityRole>() вместо AddDefaultIdentity<IdentityUser>()

Я изменил

// Identity Stuff
services.AddDefaultIdentity<IdentityUser>()
    .AddRoles<IdentityRole>()
    .AddDefaultTokenProviders()
    .AddEntityFrameworkStores<ApplicationDbContext>();

На

// Identity Stuff
services.AddIdentity<IdentityUser, IdentityRole>()
    .AddRoles<IdentityRole>()
    .AddDefaultTokenProviders()
    .AddEntityFrameworkStores<ApplicationDbContext>();

И это сработало.

...