Mapping User.Identity in .NET MVC app to active di

2019-03-31 13:01发布

I'm writing a .NET MVC 5 app which is on an intranet, uses Windows Authentication and needs to query Active Directory to see what groups are available and then check if a user is in that role.

The source of group and user names will be active directory. I then need to check identity and membership using .NET Identity. I'm not sure what fields map to what.

Fields of interest in AD seem to be:

  • SamAccountName: I think this is the username that I get from User.Identity, but the docs say that this property is: The logon name used to support clients and servers running earlier versions of the operating system, such as Windows NT 4.0, Windows 95, Windows 98, and LAN Manager.
  • CN: A displayable version of the user's name
  • objectGUID: An identifier for a user or group that won't change. Important as users will change their username if their surname changes.

So, I think SamAccountName == User.Identity.Name, but the docs say that SamAccountName is for earlier operating systems. Does this effectively mean this is deprecated and I should be using something else?

Also, are my assertions about CN and objectGUID correct?

1条回答
戒情不戒烟
2楼-- · 2019-03-31 13:08

First step: setting the parameters to use AD:

In your the section of your web.config file, set the following:

<authentication mode="Windows" />

<roleManager enabled="true" defaultProvider="AspNetWindowsTokenRoleProvider">
   <providers>
      <clear />
      <add 
          name="AspNetWindowsTokenRoleProvider"
          type="System.Web.Security.WindowsTokenRoleProvider" 
          applicationName="/" />
   </providers>
</roleManager>

Now, you will be able to directly use methods from the System.Web.Security namespace.

If you want to restrict the access to a View to only people members of the "groupName" group of your AD:

You only have to decorate your controller action like that:

[Authorize(Roles = @"DOMAIN\groupName")]
Public ActionResult Index()
{...}

If you want to do treatments based on the AD groups of users:

Use methods such as "IsInRole(rolename)" in your treatments:

if (User.IsInRole("DOMAIN\\groupName"))
{
     // Do what you want
}

EDIT: implementation of the problematic: here you should save the sAMAccountName of the group affected to your task when you create the task. Then when a user wants to mark the task as complete, just check:

if (User.IsInRole("DOMAIN\\" + sAMAccountNameOfTheGroupDedicatedToYourTask))
{
     // Mark as complete
}
查看更多
登录 后发表回答