简体   繁体   中英

Display HTML code depending on which group a user is in

I would like to selectively display a block of text on a page depending on which AD-Group a user is in. The page is a simple list of links ATM, no controller necessary. I have the code below which works perfectly when I am developing locally (I am logged onto the AD) - as soon I publish the application to an IIS server I get a 404 error - I have been able to locate the exact line that is causing the error -> in ActiveDirectory.IsInGroup () the line group.Translate is the culprit.

I have checked the Event Viewer on the IIS Server (and the log for IIS) but nothing is being logged at all?

This is the index.html:

@page
@using System.Security.Principal
@{
    ViewData["Title"] = "Landing Page";
}

@{    
   var principal = new WindowsPrincipal(WindowsIdentity.GetCurrent());
   bool itUser = ActiveDirectory.IsInGroup(principal, "IT Department");
}

<h4>Header</h4>

@if (itUser || adminUser)
    {
       <div class="card mb-4 shadow-sm">
          <div class="card-header">
             <h4 class="my-0 font-weight-normal">IT</h4>
          </div>
          <div class="card-body">
             <a target="_blank" href="http://www.test.com/Configuration/Index" class="btn btn-secondary my-2">Application Config</a><br />
          </div>
       </div>
    }

here is the C# code:

public static class ActiveDirectory

       public static bool IsInGroup(ClaimsPrincipal checkUser, string checkGroupName)
    {
        var identity = (WindowsIdentity)checkUser.Identity;
        if (identity?.Groups == null) return false;

        foreach (var group in identity.Groups)
        {
            var groupName = group.Translate(typeof(NTAccount)).ToString(); // this gives me a 404 error
            if (groupName.ToLower().Contains(checkGroupName.ToLower())) return true;
        }

        return false;
    }
}

Not utilizing a controller is bad practice (and defeats the purpose of utilizing MVC Framework (Model View Controller)), especially with concern to establishing auditability and authentication/authorization checks.

Best practice would be to have your default ActionResult (which is set in your RouteConfig file) on your controller call a function that you define to get a list of which groups your end user is a part of

Example:

Pass in the following in each controller ActionResult:

// what will be needed:    
using System.DirectoryServices;
using System.DirectoryServices.ActiveDirectory;



var userSignOn = System.Web.HttpContext.Current.Request.LogonUserIdentity.Name;

List<string> activedirectoryGroupList = new List<string>();

activedirectoryGroupList = GetGroupsFromSignOn(userSignOn);

The function being called:

internal static List<string> GetGroupsFromSignOn(string signOn)
{
    string searchText = "(&(objectCategory=person)(objectClass=user)(sAMAccountName={0}))";
    searchText = searchText.Replace("{0}", signOn);

    Domain domain = Domain.GetCurrentDomain();
    DirectoryEntry userEntry = domain.GetDirectoryEntry();

    DirectorySearcher searcher = new DirectorySearcher(userEntry, searchText);
    SearchResult result = searcher.FindOne();

    DirectoryEntry currentUserEntry = result.GetDirectoryEntry();

    List<string> activedirectoryGroupList = new List<string>();

    if (currentUserEntry != null)
    {           
        int propertyCount = currentUserEntry.Properties["memberOf"].Count;

        string activedirectoryGroup;

        for (int i = 0; i < propertyCount; i++)
        {
            activedirectoryGroup = Convert.ToString(currentUserEntry.Properties["memberOf"][i]);

            int startIndex = activedirectoryGroup.IndexOf('=');
            startIndex += 1;

            int endIndex = activedirectoryGroup.IndexOf(',');

            int stringLength = endIndex - startIndex;

            activedirectoryGroup = activedirectoryGroup.Substring(startIndex, stringLength);

            activedirectoryGroupList.Add(activedirectoryGroup);
        }

        return activedirectoryGroupList;
    }
    else
    {
        return null;
    }
}

From there, you would have a list of the AD Groups your user would be a part of, and you can either cross reference these groups with your authorized group name(s) that you can set either in your web config file, or in a SQL database that you can call out to.

As for determining what would be displayed, you should likely set up a master view, with partial views rendered on that page depending upon your user's authorization status for that information.

Edit:

Useful thread about the challenges of authentication with asp.net MVC

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM