U
U
User992020-04-14 22:18:36
ASP.NET
User99, 2020-04-14 22:18:36

Why doesn't authorization work in ASP.NET Core?

I want to make authorization by roles like here .
In the AdminController controller

[Authorize(Roles = "admin")]
        public IActionResult Index()
        {
           return View();
        }

after authorization, it throws back to the Login, authorization page. If you remove [Authorize(Roles = "admin")] then the Index action of the AdminController controller works. For some reason, authorization does not work. An entry is added to ClaimTypes.Name and Role, checked. Cookies are allowed. Cookies are set after Submit
Startup.cs

public void ConfigureServices(IServiceCollection services)
        {
           services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
                .AddCookie(CookieAuthenticationDefaults.AuthenticationScheme, options =>
                {
                    options.LoginPath = new PathString("/Auth/Login");
                    options.AccessDeniedPath = new PathString("/Auth/AccessDen");
                });
            services.AddSingleton<IConfiguration>(Configuration);
            services.AddDistributedMemoryCache();
            services.TryAddSingleton<IHttpContextAccessor, HttpContextAccessor>();
            services.AddSession(opts =>
             {
                 opts.Cookie.IsEssential = true; // make the session cookie Essential
             });
            services.AddControllersWithViews();
        }

        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
                app.UseHsts();
            }
            app.UseHttpsRedirection();
            app.UseStaticFiles();
            app.UseRouting();
            app.UseCookiePolicy();
            app.UseSession();
            app.UseDeveloperExceptionPage();

            app.UseAuthentication();
            app.UseAuthorization();
       

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



AuthController

[HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Login(string iin,string pas)
        if (iin != null && pas!= null)
            {
                Users users = await reposUsers.FindUser(iin, pas); //Использую PostgreSQL+Dapper
                if (users != null)
                {
                    await Authenticate(iin, users.role);
                    return RedirectToAction("Index", "Admin");
                }
            }
       }
private async Task Authenticate(string iin,string role)
        {
            // создаем один claim
            var claims = new List<Claim>
            {
                new Claim(ClaimTypes.Name, iin),
                new Claim(ClaimTypes.Role, role),
            };
            // создаем объект ClaimsIdentity
            ClaimsIdentity id = new ClaimsIdentity(claims, "ApplicationCookie", ClaimsIdentity.DefaultNameClaimType,
                ClaimsIdentity.DefaultRoleClaimType);
            // установка аутентификационных куки
            await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(id));
        }

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question