How do you display a users full name in the login partial view in ASP.NET Core - asp.net-core

I'm new to ASP.NET Core, most of my existing experience is with Java/PHP, and a little ASP.NET MVC about 10 years ago.
I'm using a Mac so I'm trying to build a project using Visual Studio Code and ASP.NET Core.
I've created a web application using 'yo'. I've changed the default database connection string to use an MSSQL database I have on a server. I've ran the dotnet ef database update command to create the necessary tables in the database.
I wanted to add firstname and lastname to the user, so I've created the columns in the AspNetUser table, and edited the ApplicationUser class to reflect this;
namespace pabulicms.Models
{
// Add profile data for application users by adding properties to the ApplicationUser class
public class ApplicationUser : IdentityUser
{
public string Firstname { get; set; }
public string Lastname { get; set; }
}
}
I've gone ahead and amended the view model for the registration form to include the firstname and lastname, and I've updated the Signup method so that the firstname and lastname is saved to the database.
By default the _LoginPartial.cshtml view displays the users username(email address), I'd like to change this to display the users full name, but I'm unsure as to how I do this.
This is what the _LoginPartial looks like at the moment;
#using Microsoft.AspNetCore.Identity
#using pabulicms.Models
#inject SignInManager<ApplicationUser> SignInManager
#inject UserManager<ApplicationUser> UserManager
#if (SignInManager.IsSignedIn(User))
{
<form asp-area="" asp-controller="Account" asp-action="Logout" method="post" id="logoutForm" class="navbar-right">
<ul class="nav navbar-nav navbar-right">
<li>
<a asp-area="" asp-controller="Manage" asp-action="Index" title="Manage">Hello #UserManager.GetUserName(User)!</a>
</li>
<li>
<button type="submit" class="btn btn-link navbar-btn navbar-link">Log out</button>
</li>
</ul>
</form>
}
else
{
<ul class="nav navbar-nav navbar-right">
<li><a asp-area="" asp-controller="Account" asp-action="Register">Register</a></li>
<li><a asp-area="" asp-controller="Account" asp-action="Login">Log in</a></li>
</ul>
}
It's obviously this line I need to change;
Hello #UserManager.GetUserName(User)!
However changing it to #UserManager.GetFirstname(User)! doesn't work, as it tells me that the method GetFirstname doesn't exist;

I searched a lot and finally found this solution:
Change this:
#UserManager.GetUserName(User)
To this: #UserManager.GetUserAsync(User).Result.LastName
refer to: Link

ASP.NET Core Identity library uses claims-based approach to Authorization. It means that a logged in user (the one you can access via User object in your views) has some list of claims (name-value pairs) associated with it.
By default, that list contains two claims: for ID and username.
However, it's easy to add to that list any other claim you need (first/last name, the name of the company, current user's balance, etc.).
You will just need to create your own implementation of IUserClaimsPrincipalFactory interface and register it in DI to override the default one.
Here is the article with a step-by-step description how to do it.
You can skip the first part ("zero" part to be more exact) "Preparations" if you already have the additional properties (like FirstName/LastName) in your ApplicationUser class.

In the end I used a view component.
First I created a view component myprojectname/ViewComponents/AccountStatusViewComponent.cs
namespace myprojectname.ViewComponents
{
public class AccountStatusViewComponent : ViewComponent
{
private readonly SignInManager<ApplicationUser> _signInManager;
private readonly UserManager<ApplicationUser> _userManager;
public AccountStatusViewComponent(SignInManager<ApplicationUser> signInManager, UserManager<ApplicationUser> userManager)
{
_signInManager = signInManager;
_userManager = userManager;
}
public async Task<IViewComponentResult> InvokeAsync()
{
AccountStatusModel model = new AccountStatusModel();
model.User = _userManager.GetUserAsync(Request.HttpContext.User).Result;
return View(model);
}
}
}
Next I created the view for the view component myprojectname/Views/Shared/Components/AccountStatus/Default.cshtml
#model AccountStatusModel
#using Microsoft.AspNetCore.Identity
#using myprojectname.Models.ViewComponentModels;
#using myprojectname.Models
#inject SignInManager<ApplicationUser> SignInManager
#inject UserManager<ApplicationUser> UserManager
#if (SignInManager.IsSignedIn(User))
{
<form asp-area="" asp-controller="Account" asp-action="Logout" method="post" id="logoutForm" class="navbar-right">
<ul class="nav navbar-nav navbar-right">
<li>
<a asp-area="" asp-controller="Manage" asp-action="Index" title="Manage">Hello #Model.User.Firstname #Model.User.Lastname</a>
</li>
<li>
<button type="submit" class="btn btn-link navbar-btn navbar-link">Log out</button>
</li>
</ul>
</form>
}
else
{
<ul class="nav navbar-nav navbar-right">
<li><a asp-area="" asp-controller="Account" asp-action="Register">Register</a></li>
<li><a asp-area="" asp-controller="Account" asp-action="Login">Log in</a></li>
</ul>
}
I created a model to hold the data I wanted passing the view in myprojectname/Models/ViewComponentModels/AccountStatusModel.cs
using System;
namespace pabulicms.Models.ViewComponentModels
{
public class AccountStatusModel
{
public ApplicationUser User { get; set; }
}
}
Finally, in the example .NET website I edited the file Views/Shared/_Layout.cshtml and replaced this line;
#await Html.PartialAsync("_LoginPartial")
With;
#await Component.InvokeAsync("AccountStatus")

my simple way :
top of view
#{
#inject UserManager<ApplicationUser> UserManager;
var DisplayName= UserManager.Users.FirstOrDefault(m=>m.UserName==User.Identity.Name).FullName;
}
Hello #DisplayName
ofcourse may it's not be a best way with best performance but worked for me.

Related

Authorize with roles is not working in .NET 5.0 Blazor Client app

I have a .NET 5.0 Blazor client app and I am unable to get the [Authorize(Roles="Admin")] and AuthorizeView tag to work.
I have scaffolded identity pages as well:
I am using a custom identity implementation that uses Cosmos Db: https://github.com/pierodetomi/efcore-identity-cosmos
I know that Authorization with roles in the Blazor client project template is an issue: https://github.com/dotnet/AspNetCore.Docs/issues/17649#issuecomment-612442543
I tried workarounds as mentioned in the above Github issue thread and the following SO answer: https://stackoverflow.com/a/64798061/6181928
...still, I am unable to get it to work.
Ironically, the IsInRoleAsync method is not even called after logging in to the application. I have applied a breakpoint on its implementation in the custom CosmosUserStore class and it doesn't get hit.
The browser console shows this after logging in to the application with the admin user:
Startup.cs
public void ConfigureServices(IServiceCollection services)
{
services.AddDatabaseDeveloperPageExceptionFilter();
services.AddCosmosIdentity<MyDbContext, IdentityUser, IdentityRole>(
// Auth provider standard configuration (e.g.: account confirmation, password requirements, etc.)
options => options.SignIn.RequireConfirmedAccount = true,
options => options.UseCosmos(
"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
databaseName: "xxxxxxxxxxxxxxxxxxxxxxxxx"
),
addDefaultTokenProviders: true
).AddDefaultUI().AddRoles<IdentityRole>();
services.AddScoped<IUsersRepository, UsersRepository>();
services.AddIdentityServer().AddApiAuthorization<IdentityUser, MyDbContext>(options =>
{
options.IdentityResources["openid"].UserClaims.Add("role");
options.ApiResources.Single().UserClaims.Add("role");
});
// Need to do this as it maps "role" to ClaimTypes.Role and causes issues
JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Remove("role");
services.AddAuthentication()
.AddIdentityServerJwt();
services.AddControllersWithViews();
services.AddRazorPages();
}
Program.cs
public class Program
{
public static async Task Main(string[] args)
{
var builder = WebAssemblyHostBuilder.CreateDefault(args);
builder.RootComponents.Add<App>("#app");
builder.Services.AddHttpClient("IdentityDocApp.ServerAPI", client => client.BaseAddress = new Uri(builder.HostEnvironment.BaseAddress))
.AddHttpMessageHandler<BaseAddressAuthorizationMessageHandler>();
// Supply HttpClient instances that include access tokens when making requests to the server project
builder.Services.AddScoped(sp => sp.GetRequiredService<IHttpClientFactory>().CreateClient("IdentityDocApp.ServerAPI"));
builder.Services.AddHttpClient();
builder.Services.AddScoped<IManageUsersService, ManageUsersService>();
builder.Services.AddBlazorTable();
builder.Services.AddApiAuthorization();
builder.Services.AddApiAuthorization(options =>
{
options.UserOptions.RoleClaim = "role";
});
await builder.Build().RunAsync();
}
}
App.razor
NavMenu.razor
<div class="#NavMenuCssClass" #onclick="ToggleNavMenu">
<ul class="nav flex-column">
<li class="nav-item px-3">
<NavLink class="nav-link" href="" Match="NavLinkMatch.All">
<span class="oi oi-home" aria-hidden="true"></span> Home
</NavLink>
</li>
<AuthorizeView Roles="Admin">
<li class="nav-item px-3">
<NavLink class="nav-link" href="users">
<span class="oi oi-person" aria-hidden="true"></span> Users
</NavLink>
</li>
</AuthorizeView>
</ul>
ManageUsers.razor
ManageUsersController
The database has the right data in the UserRoles collection. No issues there.
So, what could be the issue? What am I doing wrong?
Update:
It is embarrassing but my IsInRoleAsync implementation in the custom user store was not correct. As soon as I fixed it the issue was gone.
I am only using the following code in the Startup.cs of the server side:
services.AddIdentityServer()
.AddApiAuthorization<IdentityUser, MyDbContext>(options =>
{
options.IdentityResources["openid"].UserClaims.Add("name");
options.ApiResources.Single().UserClaims.Add("name");
options.IdentityResources["openid"].UserClaims.Add("role");
options.ApiResources.Single().UserClaims.Add("role");
});
JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Remove("role");
In the Program.cs of client-side I am only using builder.Services.AddApiAuthorization();
Thanks to #MrC aka Shaun Curtis for letting me know that the issue lied on the server-side.
Paste this into your Index page so you can see the information for your user:
#if (user is not null)
{
<h3>#user.Identity.Name</h3>
<div class="m-2 p-2">
Is Authenticated: #user.Identity.IsAuthenticated
</div>
<div class="m-2 p-2">
Authentication Type: #user.Identity.AuthenticationType
</div>
<div class="m-2 p-2">
Admin Role: #user.IsInRole("Admin")
</div>
<div class="m-2 p-2">
<h5>Claims</h5>
#foreach (var claim in user.Claims)
{
<span>
#claim.Type
</span>
<span>:</span>
<span>
#claim.Value
</span>
<br />
}
</div>
}
else
{
<div class="m-2 p-2">
No User Exists
</div>
}
#code {
[CascadingParameter] public Task<AuthenticationState> AuthTask { get; set; }
private System.Security.Claims.ClaimsPrincipal user;
protected async override Task OnInitializedAsync()
{
var authState = await AuthTask;
this.user = authState.User;
}
}
You should get something like this:
This shows which roles have been passed in the authentication data in the header from the authentication provider. This should include role.
Update
Remove:
// Need to do this as it maps "role" to ClaimTypes.Role and causes issues
JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Remove("role");

ASP.Net Core MVC Passing model to controller empty why?

I have a razor view page which is showing data from my database. I have a submit button which calls the action with the model but in the controller the model is empty. Can some please explain what I am doing wrong? Here is my razor page code:
<div class="row align-items-start mt-4">
<div class="col-12">
<a class="btn btn-primary float-right" asp-controller="CustomerDetails" asp-action="UpdateCustomer" asp-route-customermodel="#Model.customer"><span class="fas fa-plus-circle"></span> Submit</a>
</div>
</div>
Here is my controller code: -
public IActionResult UpdateCustomer(Customer customermodel)
{
if (ModelState.IsValid)
{
customerRepository.update(customermodel);
} else
{
string error = ModelState.Values.ToString();
}
return View("../Home/Index");
}
I found the line of code below which seems to work but again I have to add 50 property names rather than just the model. Seems like this is not the correct approach or I am doing it wrong.
public ActionResult Create([Bind(Include = "CourseID,Title,Credits,DepartmentID")]Course course)
Thanks for any advice,
If you use asp-route-customermodel="#Model.customer",you will get:
<a class="btn btn-primary float-right" href="/CustomerDetails/UpdateCustomer?customermodel=ClientSideDemo3.Models.Customer"><span class="fas fa-plus-circle"></span> Submit</a>
asp-route-xxxcannot bind model,here is a demo:
Model:
public class Customer
{
public int Id { get; set; }
public string Name { get; set; }
}
View:
<a class="btn btn-primary float-right" asp-controller="CustomerDetails" asp-action="UpdateCustomer" asp-route-Id="#Model.customer.Id" asp-route-Name="#Model.customer.Name"><span class="fas fa-plus-circle"></span> Submit</a>
result:

How to display First Name and Last Name instead of email _LoginPartial

am building a web application using ASP.NET CORE 3.0(razor pages), I extended my IdentityUser by adding first name and last name field, and I want display the both fields in place of email in _loginPartial here is my Class
public partial class AppUser : IdentityUser
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string Gender { get; set; }
}
Here is where am calling the username
<li>
<a class="nav-link text-dark" asp-area="Identity" asp-page="/Account/Manage/Index" title="Manage">Hello #User.Identity.Name!</a>
<ul>
<li>
<form class="form-inline" asp-area="Identity" asp-page="/Account/Logout" asp-route-returnUrl="#Url.Page("/", new { area = "" })" method="post">
<button type="submit" class="nav-link btn btn-link text-dark">Logout</button>
</form>
</li>
</ul>
</li>
I am not sure of how to get FirstName and LastName in place of User.Identity.Name.
please I need help.
The simplest way to achieve that is to add it to ViewData like this:
In your Account controller on the Manage index view
// read the application user from db
var user = dbContext.Users...
ViewData["UserFirstName"] = user.FirstName;
ViewData["LastName"] = user.LastName;
And then in your view just read those values from ViewData
<div>
Hello #ViewData["UserFirstName"] #ViewData["UserLastName"]
</div>
Another approach is to add a model to your view; here are some good docs that you can read:
https://learn.microsoft.com/en-us/aspnet/core/mvc/views/overview?view=aspnetcore-3.1

Returning active user from IdentityServer4 when login to the MVC .netaspcore client

I'm sure someone has asked this question or its something easy that i'm just struggling with.
I have going their the Identity Server docs and I've been able to setup as server, api, and MVC Client.
I'm able to login to the MVC Client using the Identity Server.
I'm trying to add currently login user and logout to a _loginPartial this should prove I can authorize view based on login as well. But I keep running into errors that UserManger is not doesn't have type registered.
any help or even a link to and example would be appreciated.
Based on the IdentityServer4 mvc client sample code, you could get current user from user claims.To display all the claims, you could use
#foreach (var claim in User.Claims)
{
<dt>#claim.Type</dt>
<dd>#claim.Value</dd>
}
Try to use below code in _loginPartial.cshtml to get Name claim of user
<ul class="navbar-nav">
#if (User.FindFirst("Name").Value != null)
{
<li class="nav-item">
<a> Hello #User.FindFirst("Name").Value !</a>
</li>
<li class="nav-item">
<form id="logoutForm" class="form-inline" asp-area="" asp-controller="Home" asp-action="Logout"">
<button id="logout" type="submit" class="nav-link btn btn-link text-dark">Logout</button>
</form>
</li>
}
</ul>
Logout action:
public IActionResult Logout()
{
return SignOut("Cookies", "oidc");
}

ClaimType.GivenName doesn't return my first name

I am developing .net core 2.2 application that authenticates from Azure AD. I would like to get the user's first name in the _LoginPartial.cshtml in RAZOR web app. I am able to get the user's surname and email but not the first name. Is there away to get this?
This is what i have in my login partial view:
Claim nameClaim = User.Claims.FirstOrDefault<Claim>(claim => string.Compare(claim.Type, "name", StringComparison.Ordinal) == 0);
string userName = (nameClaim != null) && !string.IsNullOrEmpty(nameClaim.Value) ? nameClaim.Value : ((User != null) && (User.Identity != null) ? User.Identity.Name : string.Empty);
Also i tried this:
#User.FindFirst(System.Security.Claims.ClaimTypes.GivenName).Value
The given name returns email same as name and email properties!!
What would be the ideal way to get the first name by extending the identity model in asp.net?
For Identity, there is no FirstName in the built-in IdentityUser, you need to implement your own user like:
public class ApplicationUser:IdentityUser
{
public string FirstName { get; set; }
}
Then, implement UserClaimsPrincipalFactory<ApplicationUser>
public class CustomClaimsIdentityFactory : UserClaimsPrincipalFactory<ApplicationUser>
{
public CustomClaimsIdentityFactory(UserManager<ApplicationUser> userManager
, IOptions<IdentityOptions> optionsAccessor)
: base(userManager, optionsAccessor)
{
}
public async override Task<ClaimsPrincipal> CreateAsync(ApplicationUser user)
{
var principal = await base.CreateAsync(user);
//custom claims
((ClaimsIdentity)principal.Identity).AddClaims(new[] {
new Claim("FirstName", user.FirstName)
});
return principal;
}
}
Then, you could check the FirstName by #User.Claims.FirstOrDefault(c => c.Type == "FirstName")?.Value like
#using Microsoft.AspNetCore.Identity
#using TestIdentity.Data
#inject SignInManager<ApplicationUser> SignInManager
#inject UserManager<ApplicationUser> UserManager
<ul class="navbar-nav">
#if (SignInManager.IsSignedIn(User))
{
<li class="nav-item">
<a class="nav-link text-dark" asp-area="Identity" asp-page="/Account/Manage/Index" title="Manage">Hello #User.Claims.FirstOrDefault(c => c.Type == "FirstName")?.Value!</a>
</li>
<li class="nav-item">
<form class="form-inline" asp-area="Identity" asp-page="/Account/Logout" asp-route-returnUrl="#Url.Action("Index", "Home", new { area = "" })">
<button type="submit" class="nav-link btn btn-link text-dark">Logout</button>
</form>
</li>
}
else
{
<li class="nav-item">
<a class="nav-link text-dark" asp-area="Identity" asp-page="/Account/Register">Register</a>
</li>
<li class="nav-item">
<a class="nav-link text-dark" asp-area="Identity" asp-page="/Account/Login">Login</a>
</li>
}
</ul>