Attribute routing is not working properly in asp.net core 3.0 - asp.net-core

I was trying to migrate my application from asp.net core 2.1 to 3.0 which uses attribute routing
My Startup file's ConfigureServices and Configure methods:
public void ConfigureServices(IServiceCollection services)
{
services.ConfigureOptions(typeof(ABCClass));
services.AddTransient<ITagHelperComponent, XYZTagHelperComponent>();
services.AddMvc();
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseStaticFiles();
app.UseMvcWithDefaultRoute();
}
I have replaced services.AddMvc(); with services.AddMvc(options => options.EnableEndpointRouting = false); to disable Endpoint routing
My action method:
[Route("")]
[Route("Machines")]
public async Task<ViewResult> GetMachinesAsync()
{
return View("MachineView");
}
First time my application loads with MachineView, but when I try to call same action method on it gives me 404 error (page can’t be found)
action call from .cshtml file:
<li class="nav-item">
<a class="nav-link"
href="#Url.Action("GetMachinesAsync", "Machine")">
Machines
</a>
</li>
Can you please help me out if I am missing something here, or I have done something wrong while configuring middleware for routing.
Thanks in Advance.

Async suffix for controller action names will be trimmed by default in asp.net core 3.0.
Refer to https://stackoverflow.com/a/59024733/10158551
Solution1:
Replace GetMachinesAsync to GetMachines in view.
<li class="nav-item">
<a class="nav-link"
href="#Url.Action("GetMachines", "Machine")">
Machines
</a>
</li>
Solution2:
Keep using GetMachinesAsync
<li class="nav-item">
<a class="nav-link"
href="#Url.Action("GetMachinesAsync", "Machine")">
Machines
</a>
</li>
then disable that behavior in startup
services.AddMvc(options =>
{
options.EnableEndpointRouting = false;
options.SuppressAsyncSuffixInActionNames = false;
});

You don't require async suffixes for action methods. So if you want to refer GetMachinesAsync you need to use GetMachines, like this.
<li class="nav-item">
<a class="nav-link"
href="#Url.Action("GetMachines", "Machine")">
Machines
</a>
</li>

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");

How to keep the tab active? ASP.NET Core Razor Pages

Hi there,
I have a problem with my tabs in navbar.
The result I wish:
See the "Home" tab class active by default
Clicking on another tab must to remove active class from the <a> that is already active (at the starting point it is "Home" tab)
Add the same class active to the tab I click on (which also mean that app redirects me)
Keep the clicked tab active
What I've got so far:
I see the "Home" tab set active by default
Clicking on any tab removes class active as I mentioned above and adds the same class to the clicked tab
Redirection happens and "Home" tab returns its default state (becomes active again)
I share my code below:
HTML
<div class="navbar-collapse collapse d-sm-inline-flex flex-sm-row-reverse" id="navigation">
<ul class="navbar-nav flex-grow-1">
<li class="nav-item">
<a class="nav-link active" id="home" asp-area="" asp-page="/home/Index">Home</a>
</li>
<li class="nav-item">
<a class="nav-link" id="declarations" asp-area="" asp-page="/declarations/Index">Declarations</a>
</li>
<li class="nav-item">
<a class="nav-link" id="topics" asp-area="" asp-page="/topics/Index">List of Topics</a>
</li>
<li class="nav-item">
<a class="nav-link" id="contacts" asp-area="" asp-page="/contacts/Index">Contacts</a>
</li>
<li class="nav-item">
<a class="nav-link" id="faq" asp-area="" asp-page="/faq/Index">FAQ</a>
</li>
</ul>
</div>
jQuery
$("#navigation .navbar-nav a").click(function() {
$("#navigation .navbar-nav").find("a.active").removeClass("active");
$(this).addClass("active");
localStorage.className = "active";
});
$(document).ready(function() {
stayActive();
});
function stayActive() {
$(this).children().addClass(localStorage.className);
}
Since you are using Razor page, everytime user clicks on a tab, the page will be rendered again on server and then sent back. Therefore I suggest that we set the active class on serverside based on the current route.
Add a new HtmlHelper class
public static class HtmlHelperExtensions
{
public static string ActiveClass(this IHtmlHelper htmlHelper, string route)
{
var routeData = htmlHelper.ViewContext.RouteData;
var pageRoute = routeData.Values["page"].ToString();
return route == pageRoute ? "active" : "";
}
}
Go to your _ViewImports.cshtml and add this import.
Without this, it will not recognize the helper we're about to add in step 3.
#using <Namespace of the class you wrote in step 1, if not already here>
Then your cshtml will be
<div class="navbar-collapse collapse d-sm-inline-flex flex-sm-row-reverse" id="navigation">
<ul class="navbar-nav flex-grow-1">
<li class="nav-item">
<a class="nav-link #Html.ActiveClass("/home/Index")" id="home" asp-area="" asp-page="/home/Index">Home</a>
</li>
<li class="nav-item">
<a class="nav-link #Html.ActiveClass("/declarations/Index")" id="declarations" asp-area="" asp-page="/declarations/Index">Declarations</a>
</li>
...Same for 3 other tabs, make sure that the route you pass in ActiveClass method
...must be the same as the route in asp-page
...If you're afraid of duplication, make some static class to store these routes as constants
</ul>
</div>
In addition to #Nam Le answer I suggest complete solution.
I've found the way how can we use the exception properly.
First of all, as we set active class on serverside based on the current route, we have to add asp-route-routeId="{routeId:int}" in the cshtml we work with.
Secondly, use this jQuery code:
jQuery
$("#navigation .navbar-nav a").click(function() {
$("#navigation .navbar-nav").find("a.active").removeClass("active");
$(this).addClass("active");
localStorage.className = "active";
});
$(document).ready(function() {
stayActive();
});
function stayActive() {
$(this).addClass(localStorage.className);
}
And the last step is to setup "launchUrl": "route/routeId" in the launchSetting.json file to run the application with certain route. This action make our HtmlHelper extension react and add active status to the tab we want.
Hope that here is no any gross mistakes in the solution I suggest :)
UPD: don't forget to add route in cshtml #page "/route/routeId"

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>

How do you display a users full name in the login partial view in 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.