2016-02-04 75 views
1

我有一個數據庫表,其中列出了所有公司僱員。他們有爲每個員工定義的角色(a,b,c)。例如,僱員1有角色a,僱員2有角色b等等。使用數據庫和C#(MVC)的Windows身份驗證

現在,我想檢查一下僱員是否有3個角色之一。如果是,請提供該用戶訪問網站。如果沒有提及該用戶的任何角色,則拒絕訪問。 C#代碼應該能夠獲取Windows登錄信息,然後查詢數據庫。

任何人都可以請讓我知道如何使用C#代碼,並與東西

+0

@ Hogan- :(我知道這聽起來很基本的給你,但任何幫助表示讚賞隊友 – Ayesha

+0

然後使用Windows身份驗證它是由爲... –

+0

@ AdrianoRepetti-我只使用這個嗎?https://code.msdn.microsoft.com/windowsdesktop/Add-Window-Authentication-833ba913 – Ayesha

回答

2

延伸AuthorizeAttribute filter屬性開始。它在數據庫中獲取用戶的角色,並與分配給每個控制器或方法的角色進行比較。

public class UserRoleAuthorize : AuthorizeAttribute 
{ 
    protected override bool AuthorizeCore(HttpContextBase httpContext) 
    { 
     //Data Repository. Getting data from database 
     var repository = new LoginRoleRepository(); 
     //GetCharacterSeparator is an Extension method of String class 
     //It seperates the comma separated roles. 
     //The data comes from the controller 
     var roles = Roles.GetCharacterSeparator(',', true); 

     if (httpContext.User.Identity.IsAuthenticated) 
     { 
      //Here I check if the user is in the role, you can have your own logic. The data is gotten from DB. 
      var userRoles = 
       repository.All().Where(obj => obj.Login.Username == httpContext.User.Identity.Name).Single().Roles; 


      foreach (var role in roles) 
       if (userRoles.Any(obj => obj.Name == role)) 
        return true; 
     } 
     return false; 
    } 
} 

然後,您只需爲每個方法或控制器定義屬性如下。

//Both Doctors and Receptionist have access to Patient controller. 
[UserRoleAuthorize(Roles="Doctors, Receptionist")] 
public class PatientController : Controller 
{ 
    //Both Doctors and Receptionist have access to Schedule an appointment for patients. 
    public ActionResult Schedule() 
    { 
      return View(); 
    } 

    //Only Doctors have access to Treat patients. 
    [UserRoleAuthorize(Roles="Doctors")] 
    public ActionResult TreatPatient() 
    { 
      return View(); 
    } 
} 

您需要添加額外信息:。

//Here seperate the roles as Doctor:ReadWrite, Receptionist:Read 
//If you see Doctor:ReadWrite means the doctor has Read and Write and so on. 
//This code is in AuthorizeCore 
var roles = Roles.GetCharacterSeparator(',', true); 

//And Add the bellow to the controllers and methods. 
[UserRoleAuthorize(Roles="Doctors:Write, Employees:Read")] 
+0

唯一缺少的是你重寫方法AuthorizeCore但是你沒有執行基本方法的邏輯。 – Chad

+1

你不需要實現所有的方法。我已經在多個項目中使用它,它工作正常。您只需要實現登錄功能並使用FormsAuthentication.SetAuthCookie(model.Username,model.RememberMe)將用戶名存儲爲Cookie; –

+0

@Bewar Salah- [UserRoleAuthorize(Roles =「Doctors,Receptionist」)]。該命令將爲所有有醫生和接待員角色的用戶提供讀寫權限。但是,如果只需要給予「醫生」閱讀寫訪問權限和接待員作爲只讀訪問權限,應該怎麼做。我在哪裏設置這些? – Ayesha