ASP. net mvc 2 authorize-custom authorize implementation

Source: Internet
Author: User
ASP. net mvc 2 authorize-custom authorize implementation

 

 

This article is mainly reproduced. With this small example, you can easily customize your authorize permission control, because I do not know ASP very well. net webform's membership implementation mechanism does not dare to say whether the custom performance has passed. Currently, it is quite easy to use custom features.

 

 

Transferred from:

========================================================== ==================================

 

Using custom authorizeattribute in ASP. NET MVC2 bypasses the built-in membership/role mechanism

// Indicate the author and link for all original articles.
// Blackboycpp (AT) gmail.com
// QQ: 135202158

Thanks to DSO at http://stackoverflow.com/users/38087/DSO

In ASP. NET MVC2, we can use authorize filter to restrict user access to content, as shown in

View plaincopy to clipboardprint?
  1. [Authorize]
  2. Public class mycontroller: Controller
  3. {
  4. //...
  5. }
  6. // Or
  7. [Authorize (roles = "admin")]
  8. Public class mycontroller: Controller
  9. {
  10. //...
  11. }

 

The premise is that the membership/role mechanism is used. We need to use the built-in mechanism, or derive our own.

In any case, it is troublesome. In fact, we can bypass this mechanism and use authorizeattribute.

The following are the opinions of DSO:

With MVC it is simple to bypass the membership and role provider framework altogether. sometimes it is easier to do this than to implement custom membership/role providers, in particle if your Authn/authz model doesn't quite fit the mold of those providers.

First, you shoshould realize that you don't need to write everything from scratch, you can use the core Forms authentication API,Which can be used independentlyOf the membership/role provider framework:

  • FormsAuthentication.SetAuthCookie-Call this after user has been authenticated, specify the user name
  • Request.IsAuthenticated-Returns true if setauthcookie was called
  • HttpContext.Current.User.Identity.Name-Returns the user name specified in the call to setauthcookie

So here is what you do in MVC to bypass the membership/role provider:

  1. Authentication: In your controller, authenticate the user using your custom logic. If successful, callFormsAuthentication.SetAuthCookieWith the user name.

  2. Authorization: Create a custom authorize attribute (deriving from authorizeattribute). InAuthorizeCoreOverride, implement your custom authorization logic, taking the user inHttpContext.Current.User.Identity.NameAnd the roles defined in the roles property of the authorizeattribute base class. note you can also define properties on your custom authorization attribute and use that in your authorization logic. for example you can define a property representing roles as enumerated values specific to your app, instead of using the roles property which is just a string.

  3. Affix your controllers and actions with your custom authorize attribute, instead of the default authorize attribute.

I thought it was very enlightening, but I don't know how to reload the authorizeattribute authorizecore method. For this reason, I made a demo:

1. Use vs2010 to create an ASP. Net MVC2 web project AUT and create a new myauthattribute class under the model directory, as shown below:

 

View plaincopy to clipboardprint?
  1. Using system;
  2. Using system. Collections. Generic;
  3. Using system. LINQ;
  4. Using system. Web;
  5. Using system. Web. MVC;
  6. Namespace authtest. Models
  7. {
  8. Public class myauthattribute: authorizeattribute
  9. {
  10. // You only need to reload this method to simulate the custom Role authorization mechanism.
  11. Protected override bool authorizecore (httpcontextbase httpcontext)
  12. {
  13. String currentrole = getrole (httpcontext. User. Identity. Name );
  14. If (roles. Contains (currentrole ))
  15. Return true;
  16. Return base. authorizecore (httpcontext );
  17. }
  18. // Return the role corresponding to the user. In practice, the user's role information can be read from the SQL database.
  19. Private string getrole (string name)
  20. {
  21. Switch (name)
  22. {
  23. Case "AAA": Return "user ";
  24. Case "BBB": Return "admin ";
  25. Case "CCC": Return "God ";
  26. Default: Return "fool ";
  27. }
  28. }
  29. }
  30. }

 

2. Modify homecontroller as follows:

 

View plaincopy to clipboardprint?
  1. Using system;
  2. Using system. Collections. Generic;
  3. Using system. LINQ;
  4. Using system. Web;
  5. Using system. Web. MVC;
  6. Using system. Web. Security;
  7. Using authtest. models;
  8. Namespace authtest. Controllers
  9. {
  10. [Handleerror]
  11. Public class homecontroller: Controller
  12. {
  13. Public actionresult index ()
  14. {
  15. Viewdata ["message"] = "Welcome to ASP. net mvc! ";
  16. // Simulate successful User Login
  17. Formsauthentication. setauthcookie ("AAA", false );
  18. Return view ();
  19. }
  20. // Verify whether the custom authorizeattribute works,
  21. // This action can only be accessed by users with the role "God"
  22. [Myauth (roles = "God")]
  23. Public actionresult about ()
  24. {
  25. Return view ();
  26. }
  27. }
  28. }

 

3. Press F5 for debugging and then click the "about" link on the page. Haha, OK?

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.