asp.net MVC role based access to controller

那年仲夏 提交于 2019-12-01 01:34:42
Sam

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.

Davin Tryon

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.

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