How to teach User.IsInRole

goal

Teach the User.IsInRole() method what roles exist in the database.

Problem

I do not know how to do that.

Laboratory

I created the following view to check for role detection:

 @if (User.IsInRole("Administrator")) { <p>Hello, admin!</p> } else { <p>Hello, guy!</p> } 

And I always get the message Hello, guy! even if I am an administrator.

To get a string array of available roles from the database, I created the following method:

 public class PermissionProvider : RoleProvider { private AppContext context = new AppContext(); [...] public override string[] GetRolesForUser(string username) { app_users user = context.app_users.FirstOrDefault(u => u.Email == username); if (user == null) { return new string[] { }; } List<String> permissions = context.app_users_types.Select(p => p.Label).ToList(); return permissions.ToArray(); } public override bool IsUserInRole(string username, string roleName) { app_users user = context.app_users.FirstOrDefault(u => u.Email == username); app_users_types type = context.app_users_types.FirstOrDefault(t => t.Label == roleName); if (user.TypeId == type.Id) { return true; } return false; } [...] } 

( app_users_types is the table in which the available roles are stored. The Label property is the name of the role.)

Knowledge [update 1]

I have already installed RoleProvider on my Web.Config . Take a look:

 <roleManager enabled="true" defaultProvider="PermissionProvider"> <providers> <add name="PermissionProvider" type="App.Security.PermissionProvider" /> </providers> </roleManager> 

But when I run the application, I get this error:

This method cannot be called during the initialization phase before starting the application.

And as you can see, there is a PermissionProvider class in the App.Security namespace.

+4
source share
1 answer

A RoleProvider must implement the IsUserInRole () method. Setting up a role provider as you have it is all you need to do.

+2
source

Source: https://habr.com/ru/post/1498268/


All Articles