Home > OS >  Why Authorize Identity not work correctly?
Why Authorize Identity not work correctly?

Time:09-11

Hi I try Create project with asp.net core mvc. I Create some Controller and also user Identity 3.1 for add manage users and add role to them. I Create 2 role (Normal, Admin) and for example I want only normal user access to the My AccountController. also the users default role is Normal after Registered. But when this type of user login and try open the account they redirect to the signin page. How can I fix this ?
i change all of the password option false temporary to create user test faster. the below code is all of my configure from startup.

 [Authorize(Roles = "Normal")]

public class AccountController : Controller
{
    public IActionResult Index()
    {
        return View("Account");
    }
}

enter code| services.AddDbContext<DataAcessLayer.DB>(s => s.UseSqlServer(Configuration.GetConnectionString("CON1")) );
        services.AddIdentity<User, IdentityRole>(option =>
        {
            option.Password.RequireDigit = false;
            option.Password.RequireLowercase = false;
            option.Password.RequireUppercase = false;
            option.Password.RequireNonAlphanumeric = false;
            option.Password.RequiredLength = 5;
            option.SignIn.RequireConfirmedPhoneNumber = false;
            option.SignIn.RequireConfirmedAccount = false;
            option.SignIn.RequireConfirmedEmail = false;
        })
            
            .AddUserManager<UserManager<User>>()
            .AddRoles<IdentityRole>()
            .AddRoleManager<RoleManager<IdentityRole>>()
            .AddEntityFrameworkStores<DataAcessLayer.DB>();
             



        services.ConfigureApplicationCookie(options =>
        {
            options.AccessDeniedPath = "/Sign/404";
            options.Cookie.Name = "WebAppIdentityCookie";
            options.Cookie.HttpOnly = true;
            options.ExpireTimeSpan = TimeSpan.FromMinutes(20);
            options.LoginPath = "/Sign/SignIn";
            options.SlidingExpiration = true;
           
        });

and this is my login code:

 [HttpPost]
    public async Task<IActionResult> login(Models.UserModel usermodel)
    {
        var user = await userManager.FindByNameAsync(usermodel.UserName);
        if (user == null)
        {
            ModelState.AddModelError("", "نام کاربری یا رمز عبور اشتباه است.");
            return View("SignIn", usermodel);
        }

        var SignInResult = await signInManager.PasswordSignInAsync(user, usermodel.Password, true, true);

        if (SignInResult.Succeeded)
        {
            return RedirectToAction("Index", "Account");
        }
        else
        {
            ModelState.AddModelError("", "نام کاربری یا رمز عبور اشتباه است.");
            return View("SignIn", usermodel);
        }

    }

       public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseExceptionHandler("/Home/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.UseRouting();


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

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

CodePudding user response:

try changing

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

to

app.UseAuthentication();
app.UseAuthorization()

read this article:
Asp.net Core Middlewares

  • Related