How to check if user is authorized inside Action

回眸只為那壹抹淺笑 提交于 2019-11-26 20:49:06

问题


Usually I protect my Actions with [Authorize] but this time I need to check if a user is authorized inside the action.

Eg

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

I believe I am using 'Forms Authentication'

This question is kind of similar to this but none of the answers given seemed to work.

EDIT: I have done some more digging- it seems if I breakpoint on an Action that has [Authorize], the User.Identity is set, but on Actions without it, the User.Identity is empty, even if I am logged in


回答1:


If you just want to know if the user is logged in:

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

If you are trying to do anything role-specific:

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

The User instance is a public property of the Controller class, so you always have access to it from a Controller you write. If no user is logged in you should have a GenericPrincipal for the User and a GenericIdentity for the User.Identity, so don't worry about checking for nulls.




回答2:


Request.IsAuthenticated should work for what you're trying to do.




回答3:


I suggest first figuring out what kind of Authorization your using. ;)

The answer you posted is correct. From what I remember poking around the [Authorize] attribute and related ActionFilter code MVC internally calls Page.User.Identity.IsAuthenticated just like those code examples.




回答4:


Create an attribute like this: OnActionExecuting will get executed first before other code from the action

     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.
            }
        }

on each action where you need to check, add attribute like this:

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

EDIT: This one still completes the action and then only redirect it. Not so much useful.



来源:https://stackoverflow.com/questions/2204766/how-to-check-if-user-is-authorized-inside-action

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!