asp.net MVC role based access to controller

后端 未结 2 724
梦毁少年i
梦毁少年i 2021-01-07 13:47

A lot of articles online on role based access speak of applying something like this to ensure role based access to a controller or action

[Authorize(Roles =          


        
相关标签:
2条回答
  • 2021-01-07 14:25

    You need to implement a custom IPrincipal (or a custom RoleProvider, but in my view IPrincipal is easier).

    In your forms authentication controller, authenticate against your user table and create an IPrincipal with roles from your role table. You will probably also want to set a Forms Auth cookie while you're at it with your roles so you don't need to hit the database each request (or use a session). Have a look at the code in this question for an example of this approach.

    If you don't have any custom attributes on your users, you may be able to use the built-in GenericIdentity and GenericPrincipal.

    Edit - if you're storing your user information in the session, you'll just need to make sure you set HttpContext.Current.User to your session-derived IPrincipal at the start of each request (OnPostAuthenticate)

    You will need to rebuild/redeploy to cater for new roles with this approach. If you want to dynamically assign roles and handle them at runtime, you'd need to implement a custom AuthorizationAttribute - this could take (e.g.) a string 'Operation' parameter which can be matched to roles in the DB. I would personally leave this until it becomes obvious you need it.

    0 讨论(0)
  • 2021-01-07 14:37

    Sounds like you might be outgrowing the role-based security design. If you need dynamic granular either/or privileges then you should start to at least look at a more claims-based approach.

    You might be able to achieve some of what you are describing by implementing a custom IPrincipal like the above link shows (without full claims-based).

    Hope this helps.

    0 讨论(0)
提交回复
热议问题