Retrieve user information from ASPNetUsers table - asp.net

I am really new to using Blazor WASM and the ASP.NET Core hosted. I have set up the login which stores all registered users to the ASPNetUsers table. I am wondering how I can then retrieve these users to display information to other users. For example I am looking to be able to have a user logged in who can then search all other users who have registered into the application as well. How might I go about displaying a list of all the users who have registered onto the application, stored in ASPNetUsers table
Options
Retrieve and send back
[HttpGet]
public async Task<ActionResult<IEnumerable<User>>> Get()
{
var result = userManager.Users.FirstOrDefault();
User x = new User();
x.Username = result.Email;
List<User> giveback = new List<User>();
giveback.Add(x);
return giveback;
}

To retrieve all users access the Users property on the UserManager:
var users = UserManager.Users.ToList();
The image in your post shows that you are only accessing the static members. You are not using an instance of UserManager.
You need to inject an instance into your controller:
readonly UserManager<ApplicationUser> _userManager;
public MyController(UserManager<ApplicationUser> userManager)
{
_userManager = userManager;
}
[HttpGet]
public ActionResult<IEnumerable<Ticket>> Get()
{
var user = _userManager.Users.FirstOrDefault();
}

Related

HotChocolate with Authorize attribute, how to get currently logged on user?

I've got a GraphQL mutation using HotChocolate with the [Authorize] attribute from HotChocolate.AspNetCore.Authorization to enforce authorization on my GraphQL endpoints.
This works fine, I can only call the mutation once I'm logged in as an Admin ...
... but now I'd like to retrieve the user which is authorized, but I don't seem to find a way to do it.
[ExtendObjectType(Name = "Mutation")]
[Authorize(Roles = new[] { "Administrators" })]
public class MyMutations
{
public bool SomeMethod()
{
// In a regular Web API controller, you can do User.Identity.Name to fetch the user name of the current user. What is the equivalent in Hot Chocolate?
var userName = "";
return false;
}
}
Any ideas?
HotChocolate uses the asp.net core authentication mechanisms, so you can get the user using the HttpContext.
[ExtendObjectType(Name = "Mutation")]
[Authorize(Roles = new[] { "Administrators" })]
public class MyMutations
{
public bool SomeMethod([Service] IHttpContextAccessor contextAccessor)
{
var user = contextAccessor.HttpContext.User; // <-> There is your user
// In a regular Web API controller, you can do User.Identity.Name to fetch the user name of the current user. What is the equivalent in Hot Chocolate?
var userName = "";
return false;
}
}

How to get current user id, if i inherits from IdentityUser?

I add some fields in IdentityUser like a
public class CustomUser: IdentityUser
{
public string field1 {get;set;}
public string field2 {get;set;}
}
after migration, on Sql Management studio i had all data, which i added with .OnModelCreating
But, How i can get any field from current authorized CustomUser (like a ID)
I try use
using Microsoft.AspNet.Identity;
CustomUser.Identity.GetUserId()
But it doesnt work.
Thanks for help!
In ASP.Net Core ,if your Controller inherits the Microsoft.AspNetCore.Mvc.Controller, you could get the IClaimsPrincipal from the User property and get the actual "Id" of the user,
using System.Security.Claims;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Identity;
ClaimsPrincipal currentUser = this.User;
var currentUserID = currentUser.FindFirst(ClaimTypes.NameIdentifier).Value;
You can also get the data of all fields(include Id) from the database's User entity:
1.DI UserManager
private readonly UserManager<ApplicationUser> _userManager;
public HomeController(UserManager<ApplicationUser> userManager)
{
_userManager = userManager;
}
2.Use it like below:
var id = userManager.GetUserId(User); // get user Id
var user = await userManager.GetUserAsync(User); // get user's all data
You need to first save user data in claims and then get authorized user data.
Add Claims
var identity = new ClaimsIdentity(OAuthDefaults.AuthenticationType);
identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, user.Id.ToString()));
Get Claims
var userId = (HttpContext.Current.User.Identity as ClaimsIdentity).Claims.FirstOrDefault(x => x.Type == ClaimTypes.NameIdentifier)

Getting related entities to an ASP.NET Identity User

Using asp.net Identity, I'm trying to work out if my AppUser has any Businesses attached (using a one to many relationship)
In the database I have an AppUser with many Businesses connected, but when I run the query to retrieve my user, Businesses is always null.
If I manually call the AspNetUsers table via a context and Include() the Businesses then they show up ok, but I thought the virtual keyword would retrieve the properties regardless?
Here is my user class:
public class AppUser : IdentityUser
{
public AppUser() {
Businesses = new List<Business>();
}
public bool HasABusinessProfile
{
get
{
return Businesses.Any();
}
}
public virtual ICollection<Business> Businesses { get; set; }
}
On login:
public async Task<IActionResult> Post([FromBody]UserLoginViewModel credentials)
{
var user = await GetClaimsIdentity(credentials.UserName, credentials.Password);
The problem is that at this point in the code, user.HasABusinessProfile is always false.

Net core custom user property

I'm using the default authorization in my .NET Core project. I want to check if an user is admin so in ApplicationUser.cs model I've added this:
public class ApplicationUser : IdentityUser
{
public bool admin { get; set; }
}
I migrated these changes into my SQL database and I can see the 'admin' property inside the AspNetUsers table. How do I check the 'admin' property of the currently logged in user?
You can access the current user instance through the UserManager<T> object, which can be injected into your controller as a constructor parameter. The method GetUserAsync takes a ClaimsPrincipal, which in this case is the User of the HttpContext.
private readonly UserManager<ApplicationUser> _userManager;
public HomeController(UserManager<ApplicationUser> userManager) {
_userManager = userManager;
var user = _userManager.GetUserAsync(HttpContext.User);
}
I agree with the above answer by Peter to just use the user variable and check for user.admin, however, I strongly suggest extending your project to use a simple Role-based Authorization to simplify things in the long run. You can achieve this with the following documentation: https://learn.microsoft.com/en-us/aspnet/core/security/authorization/roles

MVC user Authentication using Web API

I have built a WebAPI for user login, the webAPI can generate Access Token, if the user provided correct UserName and password. My Question is how I can pass user role information to the MVC application also.
For example,
I have a MVC app controller below, how can I pass the role 'Admin, UserEditor' from the Web API? I know I can use another WebAPI call to check user role, but it is not a good idea to do it.
[Authorized("Admin,UserEditor")]
ActionResult EditUser(int? Id)
{
........
}
You can read role information from claims.
Step-1 Create Role-s
I created it seed, but your choice may be different.
public static class MyDbInitializer
{
public static void Seed(this ModelBuilder builder)
{
Guid adminRoleId = Guid.Parse("90a5d1bb-2cf0-4014-9f1a-2d9f644a2e22");
builder.Entity<IdentityRole<Guid>>().HasData(
new IdentityRole<Guid>
{
Id = adminRoleId,
Name = RoleIdentifier.admin,
NormalizedName = RoleIdentifier.admin.ToUpper(CultureInfo.GetCultureInfo("en-GB"))
});
}
}
Step-2 Claims
public static class RoleIdentifier
{
public const string admin = "admin";
public const string user = "user";
}
public static class JwtClaimIdentifier
{
public const string UserId = "user_id";
public const string UserName = "user_name";
public const string Role = "role";
}
Where you generate tokens, add the role name to the claims information.
...
... string role = await _userService.GetRole(userId);
... identity.FindFirst(JwtClaimIdentifier.Role)
Step-3 Add authorize att. to controllers.
[Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme, Roles = RoleIdentifier.admin)]
public class FooController
{
}
When the logged in user wants to access this action, the possession of this role will match and access claims.
You need to use 2 authentication mechanisms (Bearer Tokens, and Cookies) because your are securing Web API end points using tokens and MVC 5 controllers using Cookies. I recommend you to check VS 2013 Web template with MVC core dependency selected. It contains all the code needed at your case. Inside the GrantResourceOwnerCredentials method you will find something similar to the below:
public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
{
var userManager = context.OwinContext.GetUserManager<ApplicationUserManager>();
ApplicationUser user = await userManager.FindAsync(context.UserName, context.Password);
if (user == null)
{
context.SetError("invalid_grant", "The user name or password is incorrect.");
return;
}
ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(userManager,
OAuthDefaults.AuthenticationType);
ClaimsIdentity cookiesIdentity = await user.GenerateUserIdentityAsync(userManager,
CookieAuthenticationDefaults.AuthenticationType);
AuthenticationProperties properties = CreateProperties(user.UserName);
AuthenticationTicket ticket = new AuthenticationTicket(oAuthIdentity, properties);
context.Validated(ticket);
context.Request.Context.Authentication.SignIn(cookiesIdentity);
}
Notice how there are oAuthIdentity for Web API, and cookiesIdentity for MVC application.

Resources