What is Webform's “UrlAuthorizationModule.CheckUrlAccessForPrincipal” equivalent for MVC?

最后都变了- 提交于 2019-12-24 01:53:59

问题


I got a problem as i am writing a custom SSO solution for my company. To mkae it simple, i've made a custom authentication httpmodule that intercepts all requests so as to check user authentication state. If not authenticated, user is redirected to my custom sso login page.

The thing is, when user is not authenticated, i'd like to check if he can access the requested page/resource... With Webforms, no problem, i add an authorization block in web.config, and i use UrlAuthorizationModule.CheckUrlAccessForPrincipal with an anonymous user. Everything works fine...

But when i apply my module to an MVC (3) web site, this does not work anymore (for obvious reasons, like the possibility to access the same controller and/or action from differents urls when using routing, and because authorizations are made through controller attributes).

How can I achieve this ?? I've been searching all day long, didn't find anything about that :/


回答1:


ASP.NET MVC 3 Internet Application template includes a basic AccountController which implements the following actions (along with the associated models and views):

  • LogOn
  • Register
  • ChangePassword / ChangePasswordSuccess

You simply need the [Authorize] attribute on the Actions or classes you wish to secure. But if you need something really custom you can do something like I've done.

I created a custom class to override security in my application.

public class AuthorizeActivityAttribute : AuthorizeAttribute
    {
       protected override bool AuthorizeCore(HttpContextBase httpContext)
       {
        HttpContext currentContext = HttpContext.Current;

        //Do your custom authentication stuff here and return true or false depending on results
        Return true;
       }
    }

And now in my Controller I have the following:

[AuthorizeActivity] 
        public ActionResult Index()
        {
            ViewBag.Message = "Welcome";

        return View();
        }



回答2:


I had the same problem.
See solution here: MVC equivalent of Webforms "UrlAuthorizationModule.CheckUrlAccessForPrincipal"

You would have to read the information from the other controller. This can be done by instantiating its context and the Descriptor, then instantiating the AuthorizationContext for that controller and read the filter info.



来源:https://stackoverflow.com/questions/11615870/what-is-webforms-urlauthorizationmodule-checkurlaccessforprincipal-equivalent

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