SimpleMembershipProvider roles not accessible

天涯浪子 提交于 2019-12-12 00:48:29

问题


I have MVC4 application which uses SimpleMEmbershipProvider for authentication mechanism.

Everything works fine, apart of when I return to the application and authenticate using persistant cookie.

I am authenticated fine, but cannot access roles that I am assigned to. Effectively, cannot access roles at all:

string.Join(",", Roles.GetRolesForUser(User.Identity.Name)) 

returns empty string

What might be causing that?


回答1:


This can happen when the SimpleMembershipProvider hasn't been initialized. The example MVC forms authentication template assumes that you'll be allowing anonymous access to your site and doesn’t initialize the membership provider until you go to the login page. However, a more common security technique is to require a login for any site access and to define menu choices in the _layout page to be determined by roles. But, if you use the persistent cookie, you don’t revisit the login page so the roles for the authenticated user aren’t loaded from the membership database.

What you want to do is initialize the provider when the user enters the site so that values get loaded. To do this, you want to add the following filter in the RegisterGlobalFilters method of the FilterConfig class in the App_Start folder

filters.Add(new YourAppNameSpace.Filters.InitializeSimpleMembershipAttribute());

This will cause the user data to be loaded from the database when a cookie authenticated user enters the site.

Another alternative technique is to add the [InitializeSimpleMembership] decorator to any controller method that cookie autheticated users might enter directly. This is kind of messy though if you have to put it on a lot of controllers. Therefore, putting it in the global filter is better in most cases.



来源:https://stackoverflow.com/questions/16215316/simplemembershipprovider-roles-not-accessible

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