2010-02-05 79 views
22

通常我用[Authorize]來保護我的操作,但是這次我需要檢查用戶是否在操作中被授權。如何檢查用戶是否被授權內部操作

if(userIsAuthorized) { 
    //do stuff 
} 
else { 
    //return to login page 
} 

我相信我使用 「窗體身份驗證」

這個問題是一種類似於this但沒有給出的答案似乎工作。

編輯:我已經做了一些更多的挖掘 - 看起來如果我有一個動作[Authorize],User.Identity已設置,但沒有它的操作的斷點,User.Identity是空的,即使我登錄在

+0

我已經解決了我的問題,通過使用hack-ish解決方法,我將假設你的答案都是正確的,這是由於我奇怪的執行身份驗證,事情很奇怪... – elwyn 2010-02-05 03:46:02

回答

42

如果你只是想知道,如果用戶登錄:

if (User.Identity.IsAuthenticated) { ... } 

如果你正在嘗試做的任何事情角色特有的:

if (User.IsInRole("Administrators")) { ... } 

User實例的公共屬性Controller類,所以您始終可以從您編寫的控制器訪問它。如果沒有用戶登錄,你應該有GenericPrincipalUserGenericIdentityUser.Identity,所以不要擔心檢查空值。

+0

再一次,只有在'[Authorize]'內使用'true'行動 – elwyn 2010-02-05 03:29:33

+0

@elwyn:我不相信這是正確的。我只是在一個沒有'[Authorize]'屬性的操作上測試它,'User.Identity.IsAuthenticated'是'true'。當你測試這個會話時,你確定會話實際上已經登錄嗎? – Aaronaught 2010-02-05 03:33:31

+0

@Aaronaught是的,只是雙(三)檢查,明確登錄嘗試,並仍然看到虛假 – elwyn 2010-02-05 03:36:04

1

我建議先弄清楚你使用的是什麼樣的授權。 ;)

您發佈的答案是正確的。從我記得在[Authorize]屬性和相關的ActionFilter代碼MVC中撥動的內容,MVC內部調用Page.User.Identity.IsAuthenticated,就像那些代碼示例一樣。

+0

雙重檢查,它是形式身份驗證 – elwyn 2010-02-05 03:22:53

3

Request.IsAuthenticated應該爲你想要做的事情工作。

+3

如果我在使用'[Authorize]'裝飾的Action上做到這一點,那麼它工作正常,但是如果我在此Action上執行此操作(未用[Authorize]裝飾),它始終爲假,無論我是否登錄。 – elwyn 2010-02-05 03:26:11

1

創建這樣一個屬性:OnActionExecuting會先被執行之前,其他代碼上的每個地方,你需要檢查操作的操作

 public class IsAuthenticatedAttribute : ActionFilterAttribute 
     { 
      public override void OnActionExecuting(ActionExecutingContext filterContext) 
      { 
       //do your validations here. and redirect to somewhere if needed. 
       filterContext.HttpContext.Response.Redirect("/") //this will send user to home. 
      } 
     } 

,添加屬性如下:

[IsAuthenticatedAttribute] 
public ActionResult ActionName(parameters?) 
{ 
    // no need to worry about checking here. 
    //do you action things 
} 

編輯: 這一個仍然完成的行動,然後只重定向它。沒那麼有用。

相關問題