ASP.NET Core 3.1 - Access denied

烈酒焚心 提交于 2021-02-11 13:50:23

问题


I'm quite new in ASP.NET Core 3.1 Razor Pages and I have a question. Hopefully you can help me further :).

What I want to have is an application with Windows AD Security. Description of what I want to do:

  • Customer needs to login using his/her AD account.
  • The user is authorized if entered a valid AD account/password combination.
  • The user have rights to see/adjust specific pages if in a specific group, let's say if in the Administrators group of the server where the application is running on.

The problem that I have is the following. In LaunchSettings.json I have placed this code:

    "windowsAuthentication": true,
    "anonymousAuthentication": false,
    "iisExpress": {
      "applicationUrl": "http://localhost:65385",
      "sslPort": 44356
    }
  } 

Then in Startup.cs I have added AddAuthentication.

    public void ConfigureServices(IServiceCollection services)
    {
      services.AddAuthentication(IISDefaults.AuthenticationScheme);
      services.AddRazorPages();
    }

And in the Configure part:

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

Then finally I created a separate folder, called Admin, in my Pages folder. I want to restrict this folder for only the Administrators group. So I added the Authorize to the Index1Model.

  [Authorize(Roles = "Administrators")]
  public class Index1Model : PageModel
    {
        public void OnGet()
        {
        }
    }

Launching this code locally with IIS Express and clicking the page protected I do get the following error:

Access denied

I thought it might have to do with impersonation. But when I enable this in IIS then I cannot open the application anymore. The user which is display in the upper corner of my program is in the Administrator group and therewith should be allowed to see the page. What am I overlooking? Thanks for helping me out!


回答1:


Have you enabled windows authentication in IIS? If not try that, else allow anonymous authentication and somewhere on your page display the user and it’s roles so you can see what identity is flowing through on IIS. You might have to change the identity that your app pool is running under but I am sure this has something to do with your IIS configuration.




回答2:


As far as I know, the windows authentication will just check the the user is authenticated or not. It will not provide any role based control in the MVC application.

So your Authorize attribute will be useless.

To achive AD role based authorize, I suggest you could consider using Policy-based authorization to authenticate only users from a Active Directory group have access to the page. Detials, you could refer to article.

You could create a custom Policy Authorization handlers to check User's all ADGroups and check if they contains your desired group name.

More details, you could refer to below steps:

1.Create CheckADGroupRequirement(accept a parameter)

public class CheckADGroupRequirement : IAuthorizationRequirement
    {
        public string GroupName { get; private set; }

        public CheckADGroupRequirement(string groupName)
        {
            GroupName = groupName;
        }
    }

2.Create Handler

public class CheckADGroupHandler : AuthorizationHandler<CheckADGroupRequirement>
    {
        protected override Task HandleRequirementAsync(AuthorizationHandlerContext context,
                                                       CheckADGroupRequirement requirement)
        {
            //var isAuthorized = context.User.IsInRole(requirement.GroupName);

            var groups = new List<string>();//save all your groups' name
            var wi = (WindowsIdentity)context.User.Identity;
            if (wi.Groups != null)
            {
                foreach (var group in wi.Groups)
                {
                    try
                    {
                        groups.Add(group.Translate(typeof(NTAccount)).ToString());
                    }
                    catch (Exception e)
                    {
                        // ignored
                    }
                }
               if(groups.Contains(requirement.GroupName))//do the check
                {
                    context.Succeed(requirement);
                }
            }

            return Task.CompletedTask;
        }
    }

3.Register Handler in ConfigureServices

services.AddAuthorization(options =>
{
    options.AddPolicy("ADRoleOnly", policy =>
        policy.Requirements.Add(new CheckADGroupRequirement("DOMAIN\\Domain Admin")));
});

services.AddSingleton<IAuthorizationHandler, CheckADGroupHandler>();

4.Controller

[Authorize(Policy = "ADRoleOnly")]
 public class ADController : Controller


来源:https://stackoverflow.com/questions/61430368/asp-net-core-3-1-access-denied

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!