简体   繁体   English

身份验证角色不起作用 .net 核心 mvc

[英]authentication roles doesn't work .net core mvc

everybody, I have used Authentication in my application with identity in .net core MVC everything works fine and even when I check User.IsInRole("Admin") works perfect what I try to use is checking Authorize in the controller but it doesn't work the page open even the user didn't have permission for that I try to use police from jwt but no sense大家,我已经在我的应用程序中使用身份验证在 .net 核心 MVC 中使用身份验证一切正常,即使我检查 User.IsInRole("Admin") 工作完美我尝试使用的是检查 controller 中的授权,但它不起作用即使用户没有权限打开页面我也尝试使用 jwt 的警察但没有意义

this is my startup这是我的创业

 public class Startup
{
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public IConfiguration Configuration { get; }

    public void ConfigureServices(IServiceCollection services)
    {

        services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DotnetCore")));

        // inject user Identity to use it in case without email vervication 

        services.AddIdentity<ApplicationUser, IdentityRole>()
            .AddEntityFrameworkStores<ApplicationDbContext>()
            .AddDefaultTokenProviders();



        services.AddAuthentication("CookieAuthentication")
             .AddCookie("CookieAuthentication", config =>
             {
                 config.Cookie.Name = "UserLoginCookie"; // Name of cookie   
                 config.LoginPath = "/Home/Index"; // Path for the redirect to user login page  
                 config.AccessDeniedPath = "/Home/AccessDenied";
             });

        services.AddAuthorization(config =>
        {
            config.AddPolicy("IsAdmin", policyBuilder =>
            {
                policyBuilder.UserRequireCustomClaim(ClaimTypes.Role);
            });
        });







        //  services.AddOptions();

        //In-Memory
        services.AddDistributedMemoryCache();
        services.AddSession(options => {
            options.IdleTimeout = TimeSpan.FromDays(1);
        });


        services.Configure<EmailSettings>(Configuration.GetSection("EmailSettings"));



        // add lang

        services.AddLocalization(options => options.ResourcesPath = "Resources");

        // add lang

        services.AddMvc()
            .AddViewLocalization(option => { option.ResourcesPath = "Resources"; })
            .AddViewLocalization(LanguageViewLocationExpanderFormat.Suffix)
            .AddDataAnnotationsLocalization();


        services.Configure<RequestLocalizationOptions>(opts =>
        {
            var supportedCultures = new List<CultureInfo>
            {
                new CultureInfo("en"),
                new CultureInfo("fr"),
            };

            opts.DefaultRequestCulture = new RequestCulture("en");
            opts.SupportedCultures = supportedCultures;
            opts.SupportedUICultures = supportedCultures;
        });


        //Password Strength Setting
        services.Configure<IdentityOptions>(options =>
        {
            // Password settings
            options.Password.RequireDigit = true;
            options.Password.RequireNonAlphanumeric = false;
            options.Password.RequireUppercase = false;
            options.Password.RequireLowercase = false;

            // Lockout settings
            options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(30);
            options.Lockout.MaxFailedAccessAttempts = 5;
            options.Lockout.AllowedForNewUsers = true;

            // User settings
            options.User.RequireUniqueEmail = true;
        });



        //JWT Token for User Authentication 

        services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
            .AddJwtBearer(options =>
            {
                options.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuer = true,
                    ValidateAudience = true,
                    ValidateLifetime = true,
                    ValidateIssuerSigningKey = true,
                    ValidIssuer = Configuration["Jwt:Issuer"],
                    ValidAudience = Configuration["Jwt:Audience"],
                    IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["Jwt:Key"]))
                };
            });




        // Add application services.

        services.AddTransient<IEmailSender, EmailSender>();



        services.AddScoped<IAuthorizationHandler, PoliciesAuthorizationHandler>();
        services.AddScoped<IAuthorizationHandler, RolesAuthorizationHandler>();

        services.AddControllersWithViews();
    }

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

        var options = app.ApplicationServices.GetService<IOptions<RequestLocalizationOptions>>();
        app.UseRequestLocalization(options.Value);

        app.UseSession();
        app.UseHttpsRedirection();
        app.UseStaticFiles();

        app.UseRouting();

        // who are you?
        app.UseAuthentication();

        // are you allowed?
        app.UseAuthorization();


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

my login code is我的登录代码是

   var result = await _signInManager.PasswordSignInAsync(model.Username, model.Password, model.RememberMe, lockoutOnFailure: true);


                if (result.Succeeded)
                {
                    _logger.LogInformation("User logged in.");


                    //added new part of jwt

                    //Save token in session object
                    var tokenvalue = GenerateJSONWebToken(model);
                    HttpContext.Session.SetString(tokenvalue, "tokencode");

                    // End of Jwt


                    return RedirectToAction("Index", "DashBoard");
                }
                if (result.IsLockedOut)
                {
                    _logger.LogWarning("User account locked out.");
                    return RedirectToAction(nameof(Lockout));
                }
                else
                {
                    ModelState.AddModelError(string.Empty, "Invalid login attempt.");
                    return View(model);
                }
            }

            ModelState.AddModelError(string.Empty, "Invalid login attempt.");
            return View(model);

in chtml pages and it works perfect在chtml页面中,它完美无缺

@if (SignInManager.IsSignedIn(User)) { @if (SignInManager.IsSignedIn(User)) {

if (User.IsInRole("Admin"))
    {
        // do something
    }

} }

I try to check Authorize using police or roles but no way我尝试使用警察或角色检查授权,但没有办法

[Authorize(Policy = "IsAdmin")]
        [Authorize(UserRoles.AdminEndUser)]
        public IActionResult Index()
        {
            return View();
        }

but it doesn't work I use .net core 3.1 and also I have added 3 classes helper for AuthorizationPolicyBuilder to check policy required and roles type但它不起作用我使用 .net 核心 3.1 并且我还为 AuthorizationPolicyBuilder 添加了 3 个类助手来检查所需的策略和角色类型

You don't need to create your policy to check Role claim.您无需创建策略即可检查Role声明。

You can use the Authorize attribute like this:您可以像这样使用Authorize属性:

[Authorize(Roles = "Admin")]

You can also use it to multiple role like this您也可以像这样将它用于多个角色

[Authorize(Roles = "Admin,CustomerServices,etc")]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 ASP.NET CORE MVC 身份用户和角色不起作用 - ASP.NET CORE MVC identity users and roles doesn't work 在Startup.cs中生成角色在.NET Core 2.0中不再起作用 - Generating Roles in Startup.cs doesn't work anymore in .NET Core 2.0 Microsoft.AnalysisServices.AdomdClient 在 .Net Core 应用程序中不起作用(身份验证问题) - Microsoft.AnalysisServices.AdomdClient doesn't work in .Net Core application (Authentication issue) Asp.Net Core:在 Web Farm 中共享身份验证 cookies 不起作用 - Asp.Net Core: Sharing authentication cookies in Web Farm doesn't work 使用Eager&Explicit加载查询相关实体在ASP.NET MVC的EF中不起作用 - Querying related entities with Eager & Explicit loading it doesn't work in EF for ASP.NET MVC CORE 使用 C# 从 ASP.NET Core MVC 中的 URL 解析 JSON 数据不起作用 - Parse JSON data from URL in ASP.NET Core MVC using C# doesn't work BindAttribute在ASP.Net MVC Core(2.0.8)中似乎不起作用 - BindAttribute doesn't seem to work in ASP.Net MVC Core (2.0.8) 没有数据库的 ASP NET MVC Core 2 角色 - ASP NET MVC Core 2 Roles without database Asp.net Core MVC 角色和授权 - Asp.net Core MVC Roles and Authorization MVC到Net Core 2迁移身份验证 - mvc to net core 2 migrate authentication
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM