Skip to content

Role-Based authorization not working in asp.net core 2.1 #11413

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
Danni-Ke opened this issue Jun 20, 2019 · 3 comments
Closed

Role-Based authorization not working in asp.net core 2.1 #11413

Danni-Ke opened this issue Jun 20, 2019 · 3 comments
Assignees
Labels
area-auth Includes: Authn, Authz, OAuth, OIDC, Bearer Needs: Author Feedback The author of this issue needs to respond in order for us to continue investigating this issue.

Comments

@Danni-Ke
Copy link

Danni-Ke commented Jun 20, 2019

Describe the bug

I followed the instruction on documentation and online about the role authorization, but the authorize since doesn't work even after I add the role type to my database. It always lets the user access the resources no matter what the user role is. I don't see why and have not idea what I am missing in my startup. Any helps will be appreciated.

To Reproduce

Steps to reproduce the behavior:

  1. Using this version of ASP.NET Core '2.1'
  2. Run this code '....'
  3. With these arguments '....'
  4. See error

Expected behavior

It should reject the user request to the API, but it doesn't.

My startup.cs

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

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            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;
            });

            services.AddDbContext<ApplicationDbContext>(options =>
                 options.UseMySql(Configuration.GetConnectionString("DefaultConnection")));
            //role service
            services.AddIdentity<IdentityUser, IdentityRole>()
                .AddRoles<IdentityRole>()
                .AddEntityFrameworkStores<ApplicationDbContext>()
                .AddDefaultTokenProviders();

            services.AddTransient<IEmailSender, AuthMessageSender>();
            //Disable the Password Hash 
            services.AddScoped<IPasswordHasher<IdentityUser>, MyPasswordHasher>();

            var migrationsAssembly = typeof(Startup).GetTypeInfo().Assembly.GetName().Name;
            //using the aspnetIdentity, the server will read the userdata via identity API

            services.AddIdentityServer()
                  .AddDeveloperSigningCredential()
                  .AddConfigurationStore(options =>
                  {
                      options.ConfigureDbContext = builder =>
                       builder.UseMySql(Configuration.GetConnectionString("DefaultConnection"),
                       sql => sql.MigrationsAssembly(migrationsAssembly));
                  })
                  .AddOperationalStore(options =>
                   {
                       options.ConfigureDbContext = builder =>
                           builder.UseMySql(Configuration.GetConnectionString("DefaultConnection"),
                           sql => sql.MigrationsAssembly(migrationsAssembly));

                       // this enables automatic token cleanup. this is optional.
                       options.EnableTokenCleanup = false;
                       options.TokenCleanupInterval = 30;
                   })
                    .AddAspNetIdentity<IdentityUser>();
     


            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
        }

        private void AddAspNetIdentity<T>()
        {
            throw new NotImplementedException();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, IServiceProvider serviceProvider)
        {
            if (env.IsDevelopment())
            {
                //InitDatabase(app);
                app.UseDeveloperExceptionPage();
                app.UseDatabaseErrorPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
                app.UseHsts();
            }
            app.UseAuthentication();
            app.UseHttpsRedirection();
            app.UseStaticFiles();
            app.UseCookiePolicy();
            app.UseIdentityServer();
           
            
            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });
            //CreateRoles(serviceProvider).Wait();
            
        }

        /// <summary>
        ///
        /// </summary>
        /// <param name="serviceProvider"></param>
        /// <returns></returns>
        private async Task CreateRoles(IServiceProvider serviceProvider)
        {
            var RoleManager = serviceProvider.GetRequiredService<RoleManager<IdentityRole>>();
            var UserManager = serviceProvider.GetRequiredService<UserManager<IdentityUser>>();
            IdentityResult roleResult;
            string[] roleNames = { "Admin", "User" };
            foreach (var roleName in roleNames)
            {
                var roleExist = await RoleManager.RoleExistsAsync(roleName);
                if (!roleExist)
                {
                    roleResult = await RoleManager.CreateAsync(new IdentityRole(roleName));
                }
            }
            await AddRoles("[email protected]", "Admin", serviceProvider);
            await AddRoles("[email protected]", "User", serviceProvider);
            await AddRoles("[email protected]", "User", serviceProvider);
            await AddRoles("[email protected]", "User", serviceProvider);
            await AddRoles("[email protected]", "User", serviceProvider);

        }
        private async Task AddRoles(string Email,string Role ,IServiceProvider serviceProvider)
        {
            var UserManager = serviceProvider.GetRequiredService<UserManager<IdentityUser>>();
            IdentityUser user = await UserManager.FindByNameAsync(Email);
            await UserManager.AddToRoleAsync(user, Role);
        }


### The API I want to protect
[Authorize(Roles = "Admin")]
        public IActionResult About()
        {
            ViewData["Message"] = "Your application description page.";

            return View();
        }

Additional context

Thanks, guys. I will update more information later.

@Danni-Ke Danni-Ke changed the title Role-Based not working in asp.net core 2.1 Role-Based authorization not working in asp.net core 2.1 Jun 20, 2019
@blowdart
Copy link
Contributor

When you put a break point in your about function and look at the user does it actually have roles in?

@Eilon Eilon added the area-auth Includes: Authn, Authz, OAuth, OIDC, Bearer label Jun 20, 2019
@blowdart
Copy link
Contributor

blowdart commented Jun 20, 2019

Also you're not adding authorization anywhere.

You need to

app.UseAuthorization();

and then also add the appropriate authentication configuration for identity server. The identity server configuration you have is to configure identity server and its stores, it doesn't add authentication and authorization to the application hosting it.

@analogrelay analogrelay added Needs: Author Feedback The author of this issue needs to respond in order for us to continue investigating this issue. waiting labels Jun 20, 2019
@blowdart
Copy link
Contributor

blowdart commented Jul 2, 2019

We're closing this issue as no response or updates have been provided in a timely manner. If you have more details and are encountering this issue please add a new reply and re-open the issue.

@blowdart blowdart closed this as completed Jul 2, 2019
@ghost ghost locked as resolved and limited conversation to collaborators Dec 3, 2019
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
area-auth Includes: Authn, Authz, OAuth, OIDC, Bearer Needs: Author Feedback The author of this issue needs to respond in order for us to continue investigating this issue.
Projects
None yet
Development

No branches or pull requests

5 participants