locked
Authorisation role always giving access denied Asp.net core 3.1 Identity RRS feed

  • Question

  • User-183185495 posted

    My Authorisation is not working correctly even though they are in the role for example I am always getting access denied
    My Roles for Manger

    Do I need to place anyting in my identity sign in page and register page to assign the role when they login or register?

    Roles

    Users In Roles

    My Controller Decoration

            // GET: MISObjects/Details/5
            [Authorize(Roles = "Manager")]
            public async Task<IActionResult> Details(int? id) {
                if (id == null) {
                    return NotFound();
                }
    
                var mISObject = await _context.MISobject
                    .FirstOrDefaultAsync(m => m.Id == id);
                if (mISObject == null) {
                    return NotFound();
                }
    
                return View(mISObject);
            }

      public void ConfigureServices(IServiceCollection services) {
                services.AddDbContext<MISDBContext>
              (options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
                services.AddDbContext<ApplicationDbContext>(options =>
                    options.UseSqlServer(
                        Configuration.GetConnectionString("DefaultConnection")));
    
                services.AddIdentity<ApplicationUser, IdentityRole>()                
                    .AddDefaultUI()
                    .AddDefaultTokenProviders()
                    .AddEntityFrameworkStores<MISDBContext>().AddClaimsPrincipalFactory<MyUserClaimsPrincipalFactory>();  //<---- add this line 
    
    
                services.AddControllersWithViews();
                services.AddRazorPages();
                services.AddAuthorization(options =>
                {
                    options.AddPolicy("Admin", policy => policy.RequireRole("Admin"));
                    options.AddPolicy("Manager", policy => policy.RequireRole("Manager"));                
                    options.AddPolicy("ElevatedRights", policy =>
                      policy.RequireRole("Administrator", "PowerUser", "BackupAdministrator"));
                });
                 
            }

    Edit 2

    All my claims factory is doing is the following

        public class MyUserClaimsPrincipalFactory : UserClaimsPrincipalFactory<ApplicationUser> {
            public MyUserClaimsPrincipalFactory(
                UserManager<ApplicationUser> userManager,
                IOptions<IdentityOptions> optionsAccessor)
                    : base(userManager, optionsAccessor) {
            }
    
            protected override async Task<ClaimsIdentity> GenerateClaimsAsync(ApplicationUser user) {
                var identity = await base.GenerateClaimsAsync(user);
                identity.AddClaim(new Claim("FullName", user.FirstName + " " + user.LastName ?? "[Click to edit profile]"));
                return identity;
            }
        }
    }
    

    Here is the full reproduceable repo

    https://github.com/davidbuckleyni/AuthorisationRepoMS

    Wednesday, July 1, 2020 1:57 PM

Answers

  • User475983607 posted

    You are correct.  

    Again, you have a custom principal claim factory.  The community cannot see the code.  

    I use Identity in several projects and do not have this problem.  

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Saturday, July 18, 2020 11:47 AM

All replies

  • User-2091049410 posted

    Hi there! Can you please share your Configure method in your Startup.cs. It is key in what order in the middleware pipeline you put AddAuthentication() and AddAuthorization().

    Best regards

    Håkan

    Wednesday, July 1, 2020 7:27 PM
  • User-183185495 posted
    Excuse me but plz look at my orginal post configure services is there already
    Thursday, July 2, 2020 12:01 AM
  • User-2091049410 posted

    Yes, but I'm talking about the Configure() method, not the ConfigureServices() method. Authorization is a combination of services and middleware which are configured in two different methods, for example:

    public void ConfigureServices(IServiceCollection services)
    {
       
    ...
       services.AddIdentity(...);
       services.AddAuthorization(...);
    }

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {

       ...

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

       ...
    }

    Now the order in how the authentication/authorization should be added in Configure() was updated in .NET Core 3.0, so if you're upgrading an application from .NET Core 2.x it won't work unless move stuff around a bit.

    Regards

    Thursday, July 2, 2020 3:39 AM
  • User-183185495 posted

    Please find enclosed the configuration as requested

       // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
            public void Configure(IApplicationBuilder app, IWebHostEnvironment env) {
                if (env.IsDevelopment()) {
                    app.UseDeveloperExceptionPage();
                    app.UseDatabaseErrorPage();
                } 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.UseAuthentication();
                app.UseAuthorization();
    
                app.UseEndpoints(endpoints => {
                    endpoints.MapControllerRoute(
                        name: "default",
                        pattern: "{controller=Home}/{action=Index}/{id?}");
                    endpoints.MapRazorPages();
                });
            }

    Thursday, July 2, 2020 6:41 AM
  • User475983607 posted

    I do not see cookie authentication configuration.  There is nothing to cache the claims/roles.   

    The configuration shows a custom claims factory and it is not clear what programming problem the factory solves.   The configuration also shows  claims policies that are not being used.  Can you explain your security requirements?

    Thursday, July 2, 2020 10:37 AM
  • User-183185495 posted

     I am not sure where I need the claim code to save to the cookie that is what I am asking sign in and all the other features of identity are working except for claims and roles. I can add roles and make somoene a member of that role but I dont no how I do this when the person signs up or logins in I beleive you said the claim needs to be passed to the cookie somehow can you explain more or provide a like to 3.1 asp.net core documenation thanks.

    Thursday, July 2, 2020 5:21 PM
  • User-183185495 posted

    Can you please expand on cookie authontication configuration why do we need this in .net core when idenity takes care of that.

    Saturday, July 18, 2020 2:10 AM
  • User475983607 posted

    You are correct.  

    Again, you have a custom principal claim factory.  The community cannot see the code.  

    I use Identity in several projects and do not have this problem.  

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Saturday, July 18, 2020 11:47 AM
  • User-183185495 posted

    Hi  I have posted the code requested above as well as a reporduceable repo.

    Would need sql server to scafold the database thouugh

    Saturday, July 18, 2020 7:25 PM
  • User-183185495 posted

    Hi  I have posted the code requested above as well as a reporduceable repo.

    Would need sql server to scafold the database thouugh

    Its above post in edit 2

    You are correct.  

    Again, you have a custom principal claim factory.  The community cannot see the code.  

    I use Identity in several projects and do not have this problem.  

    Saturday, July 18, 2020 7:29 PM
  • User-183185495 posted

    Hi it ended being this line it over ridden the expect beahiour 

    .AddClaimsPrincipalFactory<MyUserClaimsPrincipalFactory>(); //<---- add this line

    All my factory was doing was getting the signed in name once it was removed it worked as expected

    You are correct.  

    Again, you have a custom principal claim factory.  The community cannot see the code.  

    I use Identity in several projects and do not have this problem.  

    Tuesday, July 21, 2020 12:38 AM
  • User-183185495 posted

    I showed the code in the second edit of the post if you look it was presented to the community ! For the claims facotory

    You are correct.  

    Again, you have a custom principal claim factory.  The community cannot see the code.  

    I use Identity in several projects and do not have this problem.  

    Tuesday, July 21, 2020 1:34 AM