ASP.NET MVC 5 Web API + Windows Authentication – Validate Existing User Account which is existed from Specific Active Directory Group

ASP.NET MVC 5 Web API + Windows Authentication – Validate Existing User Account which is existed from Specific Active Directory Group

   WindowAuthenticationHelper.cs
 
   using System;
   using System.Linq;
   using System.Collections.Generic;
   using System.Security.Principal;
 
   namespace ADGroupTest.Library
   {
     public class WindowAuthenticationHelper
     {
       public static bool isExistfromGroup(WindowsIdentity identity, string GroupName)
       {
         var groups = from groupIdentity in identity.Groups
                               where groupIdentity.IsValidTargetType(typeof(NTAccount))
                               select groupIdentity.Translate(typeof(NTAccount)) as NTAccount;
 
         foreach (var domaingroup in groups)
         {
           if (domaingroup.Value.Equals(GroupName))
             return true;
         }
 
         return false;
       }
     }
   }
 
   ExtendApiController.cs ( Inherit Root Web API Controller )
 
   using System;
   using System.Linq;
   using System.Web;
   using System.Web.Http;
   using System.Security.Principal;
   using ADGroupTest.Library;
   using ADGroupTest.Controllers;
   using Newtonsoft.Json.Linq;
 
   namespace ADGroupTest.Controllers
   {
     public class ExtendApiController : ApiController
     {
       internal bool HasAccessRight;
       internal const string ADGroup = "… …\\Domain Users";   /* can be defined this from web.conf or a Constant Value Class. */
 
       public ExtendApiController()
       {
         this.HasAccessRight = WindowAuthenticationHelper.isExistfromGroup(WindowsIdentity.GetCurrent(), ADGroup);
       }
 
       public JObject Exception(string type, string message)
       {
         JObject exception = new JObject();
 
         exception.Add("Type", type);
         exception.Add("Message", message);
 
         return exception;
       }
 
       public JObject AceessDenied()
       {
         return this.Exception("Access Right",
         "Access Denied. " + WindowsIdentity.GetCurrent().Name + "is not existed in " + ADGroup.Replace("//", "/") + ".");
       }
     }
   }
 
   ValuesController.cs ( Web API – Controller )
 
   using System;
   using System.Linq;
   using System.Net;
   using System.Net.Http;
   using System.Web.Http;
   using ADGroupTest.Library;
   using System.Security.Principal;
   using ADGroupTest.Controllers;
   using Newtonsoft.Json.Linq;
 
   namespace ADGroupTest.Controllers
   {
     [Authorize]
     public class ValuesController : ExtendApiController
     {
       [Authorize]
       public JObject Get()
       {
         JObject result = new JObject();
 
         if (this.HasAccessRight)
         {
           result.Add("User", WindowsIdentity.GetCurrent().Name);
           return result;
         }
         else
           return this.AceessDenied();
       }
 
       … …
 
     }
   }