asp.net MVC role based access to controller

后端 未结 2 723
梦毁少年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.

提交回复
热议问题