2015-09-04 67 views
1

我目前有一個非常簡單的安裝程序運行。該設置由一個實體框架項目和一個IIS服務器組成。 IIS被配置爲使用Windows身份驗證。如何在ASP.NET Entity Framework中處理Microsoft身份驗證

現在在我的項目中,我只想讓某些用戶訪問某些控制器。在我工作的組織內部,有一個「權限」系統,一個包含允許用戶訪問什麼數據的表格。所以,我想獲取用戶登錄的電子郵件,並檢查數據庫是否有權限。

我這樣做的計劃是製作一段獨立的代碼,它不能從Web訪問,包含函數「boolean hasPermissions(String email,byte permissions)」。但是我不知道該把這個放在哪裏,我也找不到這方面的任何信息。我記得正確的方法嗎?如果,那麼如何正確執行這種方法?

回答

1

你應該使用Windows身份驗證,使用的IPrincipal,你將有一個用戶對象,你可以問IsInRole特定的基於角色的安全性,而不是位/布爾

閱讀所有關於它在Asp.net windows authentication

以及如何實現的IPrincipal Implement custom security

代碼示例: 用戶對象:

public class User : IPrincipal 
{ 
    private readonly IPrincipal _user; 
    public IIdentity Identity { get; private set; } 

    public User (IPrincipal user) 
    { 
     Identity = user.Identity; 
     _user = user; 

    } 

    public bool IsInRole(string role) 
    { 
     return _user.IsInRole(role); 
    } 
} 

在MVC添加過濾器

public class CustomAuthenticationAttribute : ActionFilterAttribute, IAuthenticationFilter 
    { 

     public void OnAuthentication(AuthenticationContext filterContext) 
     { 

      var user= new User (HttpContext.Current.User); 
      Thread.CurrentPrincipal = user; 
     } 

    } 

而且使用

filters.Add(new CustomAuthenticationAttribute()); 

然後,用你的應用程序

var user = new User(Thread.CurrentPrincipal); 
if(user.IsInRole("admin")) /* do the choka choka */; 
+0

我有這個想法內的用戶對象時過濾器添加到您的一個FilterConfig你確實是對的,而這正是我需要的。然而,我現在一直在考慮最近兩個小時,而且我不知道如何實現這一點。你會有我的代碼示例嗎?主要關於如何獲取用戶對象以及認證碼的放置位置。 –

+0

爲您添加了一個代碼示例 – Thorarins

+1

非常感謝。我做了一個編輯建議,其中包含我必須使其適應的適應性。這對於像我這樣的未來新手來說,他們不知道什麼是什麼。 –