Identity 2.0 Custom UserManager / RoleManager vs razor call User.IsInRole ("RoleName")
Below are the questions: read on to find out what you need to answer ...
I have
- VS 2013
- MVC 5 with Razor Views
- Dapper DAL Custom UserManager and UserStore / User: IUser <int>
I create my own UserManager, RoleManager, UserStore, RoleStore and all based on CustomUser: IUser <int> and CustomRole: IRole <int>
I can change passwords, recover forgotten passwords, login, logout ... everything works well.
However, in razor mode, when I try to use:
User.IsInRole("Administrators");
I am getting SQL exception (which is probably happening in iPrincipal Identity class ???) from another module:
System.Data.SqlClient.SqlException occurred
_HResult=-2146232060
_message=A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified)
Source=.Net SqlClient Data Provider
ErrorCode=-2146232060
_doNotReconnect=false
Class=20
LineNumber=0
Number=-1
Server=""
State=0
StackTrace:
at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
InnerException: <null>
But I can name
var user = AsyncHelpers.RunSync<CloudUser>(() => UserManager.FindByNameAsync(User.Identity.Name));
ViewBag.IsInAdminRole = AsyncHelpers.RunSync<bool>(() => UserManager.IsInRoleAsync(user.Id, "Administrators"));
In my controller server code ....
Questions:
-
What is the relationship between User.IsInRole and UserManager / UserStore and / or RoleManager
-
How do I get the User.IsInRole ("Administrators") in the Razor view so that it "understands" that it needs to use my own implementation of identity authentication?
source to share
I suspect your implementation is not providing ClaimsPrincipal
user login.
@User
should be ClaimsPrincipal
and IsInRole
( see source ) does not get into the database, but rather checks claims of the "Role" type set on the main identifier. If you see this exception, your IPrincipal has a different ClaimsPrincipal form.
I read the answer you linked and I don't think it is the best solution to use with the Identity framework. The answer is a provisional ID and speaks of the membership of the Provider. You should have done things like this when dealing with the MembershipProvider. Identity now gives you a much better and cleaner way of doing custom functionality.
I would advise against implementing CustomPrincipal
and using the ClaimsPrincipal
provided .Net framework. Just add type claims ClaimTypes.Role
with role names in your master when you return the IPrincipal from your UserManager.CreateIdentityAsync
.
source to share