SimpleMembershipProvider roles not accessible
Asked Answered
M

1

0

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?

Martino answered 25/4, 2013 at 12:54 Comment(0)
U
4

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.

Utterance answered 25/4, 2013 at 15:36 Comment(1)
Filters.InitializeSimpleMembershipAttribute() does not exist.Symptomatology

© 2022 - 2024 — McMap. All rights reserved.