2010-02-05 72 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 
} 

编辑: 这一个仍然完成的行动,然后只重定向它。没那么有用。

相关问题