How to get roles of a user in ASP.NET Identity
I have a custom user store defined this way:
public class ExternalUserStore<T> : IUserStore<T>, IUserPasswordStore<T>, IUserRoleStore<T> where T : Models.ApplicationUser
One of the methods is:
public Task<IList<string>> GetRolesAsync(T user)
That method is called by ASP.NET identity in custom OAuthProvider GrantResourceOwnerCredentials method, this way:
var userManager = context.OwinContext.GetUserManager<ApplicationUserManager>();
ApplicationUser user = await userManager.FindAsync(context.UserName, context.Password);
if (user == null)
{
context.SetError("invalid_grant", "El nombre de usuario o la contraseña no son correctos.");
return;
}
var roles = await userManager.GetRolesAsync(user.Id);
My implementation of GetRolesAsync method is:
public Task<IList<string>> GetRolesAsync(T user)
{
IList<string> roles = new List<string>();
foreach (var userRole in user.Roles)
{
// Here I need to create ApplicationRole objects
}
return Task.FromResult(roles);
}
I think that I need to iterate over user.Roles, and since user.Roles is a list a object whose properties are UserId and RoleId, I need to find the role by the id and then to add it to the list.
However, user.Roles is empty and it is obvious since I am not populating any role for the user.
The question is how to populate it.
This is the FindByIdAsync mthod of the user that populates user information:
public Task<T> FindByIdAsync(string userId)
{
using (var db = Helpers.DataRetrieval.GetConnector())
{
var usuarioStored = db.GetUsuarioPorId(userId);
if (usuarioStored == null)
return Task.FromResult((T)null);
var appUser = PopulateUserData(usuarioStored);
return Task.FromResult((T)appUser);
}
}
private Models.ApplicationUser PopulateUserData(MiddleTier.Models.IUsuario usuario)
{
var appUser = new Models.ApplicationUser()
{
Id = usuario.Id.ToString(),
UserName = usuario.Login,
Email = usuario.Email,
EmailConfirmed = true,
PasswordHash = usuario.PasswordHash,
SecurityStamp = usuario.PasswordSalt,
PhoneNumber = usuario.Telefono,
PhoneNumberConfirmed = !String.IsNullOrWhiteSpace(usuario.Telefono),
TwoFactorEnabled = false,
LockoutEnabled = usuario.Bloqueado
};
return appUser;
}
As you see, I can in appUser assign Roles property but I encounter the same problem..... Roles is a list of IdentityUserRoles which has 2 properties, UserId and RoleId.
What can I do it?
c# asp.net asp.net-identity owin
add a comment |
I have a custom user store defined this way:
public class ExternalUserStore<T> : IUserStore<T>, IUserPasswordStore<T>, IUserRoleStore<T> where T : Models.ApplicationUser
One of the methods is:
public Task<IList<string>> GetRolesAsync(T user)
That method is called by ASP.NET identity in custom OAuthProvider GrantResourceOwnerCredentials method, this way:
var userManager = context.OwinContext.GetUserManager<ApplicationUserManager>();
ApplicationUser user = await userManager.FindAsync(context.UserName, context.Password);
if (user == null)
{
context.SetError("invalid_grant", "El nombre de usuario o la contraseña no son correctos.");
return;
}
var roles = await userManager.GetRolesAsync(user.Id);
My implementation of GetRolesAsync method is:
public Task<IList<string>> GetRolesAsync(T user)
{
IList<string> roles = new List<string>();
foreach (var userRole in user.Roles)
{
// Here I need to create ApplicationRole objects
}
return Task.FromResult(roles);
}
I think that I need to iterate over user.Roles, and since user.Roles is a list a object whose properties are UserId and RoleId, I need to find the role by the id and then to add it to the list.
However, user.Roles is empty and it is obvious since I am not populating any role for the user.
The question is how to populate it.
This is the FindByIdAsync mthod of the user that populates user information:
public Task<T> FindByIdAsync(string userId)
{
using (var db = Helpers.DataRetrieval.GetConnector())
{
var usuarioStored = db.GetUsuarioPorId(userId);
if (usuarioStored == null)
return Task.FromResult((T)null);
var appUser = PopulateUserData(usuarioStored);
return Task.FromResult((T)appUser);
}
}
private Models.ApplicationUser PopulateUserData(MiddleTier.Models.IUsuario usuario)
{
var appUser = new Models.ApplicationUser()
{
Id = usuario.Id.ToString(),
UserName = usuario.Login,
Email = usuario.Email,
EmailConfirmed = true,
PasswordHash = usuario.PasswordHash,
SecurityStamp = usuario.PasswordSalt,
PhoneNumber = usuario.Telefono,
PhoneNumberConfirmed = !String.IsNullOrWhiteSpace(usuario.Telefono),
TwoFactorEnabled = false,
LockoutEnabled = usuario.Bloqueado
};
return appUser;
}
As you see, I can in appUser assign Roles property but I encounter the same problem..... Roles is a list of IdentityUserRoles which has 2 properties, UserId and RoleId.
What can I do it?
c# asp.net asp.net-identity owin
add a comment |
I have a custom user store defined this way:
public class ExternalUserStore<T> : IUserStore<T>, IUserPasswordStore<T>, IUserRoleStore<T> where T : Models.ApplicationUser
One of the methods is:
public Task<IList<string>> GetRolesAsync(T user)
That method is called by ASP.NET identity in custom OAuthProvider GrantResourceOwnerCredentials method, this way:
var userManager = context.OwinContext.GetUserManager<ApplicationUserManager>();
ApplicationUser user = await userManager.FindAsync(context.UserName, context.Password);
if (user == null)
{
context.SetError("invalid_grant", "El nombre de usuario o la contraseña no son correctos.");
return;
}
var roles = await userManager.GetRolesAsync(user.Id);
My implementation of GetRolesAsync method is:
public Task<IList<string>> GetRolesAsync(T user)
{
IList<string> roles = new List<string>();
foreach (var userRole in user.Roles)
{
// Here I need to create ApplicationRole objects
}
return Task.FromResult(roles);
}
I think that I need to iterate over user.Roles, and since user.Roles is a list a object whose properties are UserId and RoleId, I need to find the role by the id and then to add it to the list.
However, user.Roles is empty and it is obvious since I am not populating any role for the user.
The question is how to populate it.
This is the FindByIdAsync mthod of the user that populates user information:
public Task<T> FindByIdAsync(string userId)
{
using (var db = Helpers.DataRetrieval.GetConnector())
{
var usuarioStored = db.GetUsuarioPorId(userId);
if (usuarioStored == null)
return Task.FromResult((T)null);
var appUser = PopulateUserData(usuarioStored);
return Task.FromResult((T)appUser);
}
}
private Models.ApplicationUser PopulateUserData(MiddleTier.Models.IUsuario usuario)
{
var appUser = new Models.ApplicationUser()
{
Id = usuario.Id.ToString(),
UserName = usuario.Login,
Email = usuario.Email,
EmailConfirmed = true,
PasswordHash = usuario.PasswordHash,
SecurityStamp = usuario.PasswordSalt,
PhoneNumber = usuario.Telefono,
PhoneNumberConfirmed = !String.IsNullOrWhiteSpace(usuario.Telefono),
TwoFactorEnabled = false,
LockoutEnabled = usuario.Bloqueado
};
return appUser;
}
As you see, I can in appUser assign Roles property but I encounter the same problem..... Roles is a list of IdentityUserRoles which has 2 properties, UserId and RoleId.
What can I do it?
c# asp.net asp.net-identity owin
I have a custom user store defined this way:
public class ExternalUserStore<T> : IUserStore<T>, IUserPasswordStore<T>, IUserRoleStore<T> where T : Models.ApplicationUser
One of the methods is:
public Task<IList<string>> GetRolesAsync(T user)
That method is called by ASP.NET identity in custom OAuthProvider GrantResourceOwnerCredentials method, this way:
var userManager = context.OwinContext.GetUserManager<ApplicationUserManager>();
ApplicationUser user = await userManager.FindAsync(context.UserName, context.Password);
if (user == null)
{
context.SetError("invalid_grant", "El nombre de usuario o la contraseña no son correctos.");
return;
}
var roles = await userManager.GetRolesAsync(user.Id);
My implementation of GetRolesAsync method is:
public Task<IList<string>> GetRolesAsync(T user)
{
IList<string> roles = new List<string>();
foreach (var userRole in user.Roles)
{
// Here I need to create ApplicationRole objects
}
return Task.FromResult(roles);
}
I think that I need to iterate over user.Roles, and since user.Roles is a list a object whose properties are UserId and RoleId, I need to find the role by the id and then to add it to the list.
However, user.Roles is empty and it is obvious since I am not populating any role for the user.
The question is how to populate it.
This is the FindByIdAsync mthod of the user that populates user information:
public Task<T> FindByIdAsync(string userId)
{
using (var db = Helpers.DataRetrieval.GetConnector())
{
var usuarioStored = db.GetUsuarioPorId(userId);
if (usuarioStored == null)
return Task.FromResult((T)null);
var appUser = PopulateUserData(usuarioStored);
return Task.FromResult((T)appUser);
}
}
private Models.ApplicationUser PopulateUserData(MiddleTier.Models.IUsuario usuario)
{
var appUser = new Models.ApplicationUser()
{
Id = usuario.Id.ToString(),
UserName = usuario.Login,
Email = usuario.Email,
EmailConfirmed = true,
PasswordHash = usuario.PasswordHash,
SecurityStamp = usuario.PasswordSalt,
PhoneNumber = usuario.Telefono,
PhoneNumberConfirmed = !String.IsNullOrWhiteSpace(usuario.Telefono),
TwoFactorEnabled = false,
LockoutEnabled = usuario.Bloqueado
};
return appUser;
}
As you see, I can in appUser assign Roles property but I encounter the same problem..... Roles is a list of IdentityUserRoles which has 2 properties, UserId and RoleId.
What can I do it?
c# asp.net asp.net-identity owin
c# asp.net asp.net-identity owin
asked Nov 20 '18 at 22:34
jstuardojstuardo
99452862
99452862
add a comment |
add a comment |
0
active
oldest
votes
Your Answer
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53402606%2fhow-to-get-roles-of-a-user-in-asp-net-identity%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
0
active
oldest
votes
0
active
oldest
votes
active
oldest
votes
active
oldest
votes
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53402606%2fhow-to-get-roles-of-a-user-in-asp-net-identity%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown