Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
279 views
in Technique[技术] by (71.8m points)

c# - ASP.NET - Redirect to Error Page if Roles Authorization Fails

I am using MVC 3 with Forms Authentication. On my controller or methods, I am doing the following:

[Authorize (Roles = "developer")]

In this situation, I want to check if the user is logged in and if not, return them to the login page. However, if the 'IsInRole' check for that user returns false, I want them to go to a different view that says something like 'Not authorized'.

What is the best way to accomplish something like this? I was hoping to avoid creating a new Authorization attribute so I didn't have to refactor every Authorize attribute in my entire application, but if that is what is required, I will go that route.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

A custom authorize attribute overriding the HandleUnauthorizedRequest method could do the job:

public class MyAuthorizeAttribute : AuthorizeAttribute
{
    protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
    {
        if (!filterContext.HttpContext.User.Identity.IsAuthenticated)
        {
            // The user is not authenticated
            base.HandleUnauthorizedRequest(filterContext);
        }
        else if (!this.Roles.Split(',').Any(filterContext.HttpContext.User.IsInRole))
        {
            // The user is not in any of the listed roles => 
            // show the unauthorized view
            filterContext.Result = new ViewResult
            {
                ViewName = "~/Views/Shared/Unauthorized.cshtml"
            };
        }
        else
        { 
            base.HandleUnauthorizedRequest(filterContext);
        }
    }
}

and then:

[MyAuthorize(Roles = "developer")]
public ActionResult Develop()
{
    ...
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...