Role Based Authorization in ASP.NET Core Razor (not MVC) CSHTML - asp.net-core

My application is ASP.NET Core 6 using Razor pages (not MVC). I will have OKTA claims once logged-in. In my Blazor application, I used below tags to authorize specific HTML sections:
<AuthorizeView Roles="Admins,Users">
<Authorized>
<<my html>>
</Authorized>
</AuthorizeView>
I can wrap any HTML sections in Blazor like this using AuthorizeView passing my role names. How I can achieve the same in ASP.NET Core with Razor pages .CSHTML files?

you can use (User.IsInRole("operation-admin")
#if (User.IsInRole("operation-admin"))
{
<h1>hello</h1>
}
else
{
<h1>bye</h1>
}

Related

How to get same claims in .cshtml page and in API in a hosted Blazor WA?

Hosted Blazor WA app with IdentityServer4 - standard template.
Scaffolded Identity pages.
Custom ProfileService which adds several claims.
Everything works as expected in strictly Blazor and API realms.
However inspecting User claims in Pages in Identity pages I notice that my custom claims added in ProfileService are missing.
My current configuration in Program.cs looks like this:
builder.Services.AddAuthentication()
.AddIdentityServerJwt();
I have tried extending config in AddApiAuthorization to add custom claim, but it did not help.
builder.Services.AddIdentityServer()
.AddApiAuthorization<User, ApplicationDbContext>(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");
options.IdentityResources["openid"].UserClaims.Add("mn");
options.ApiResources.Single().UserClaims.Add("mn");
})
.AddSigningCredentials();
How to configure app to be able to access all claims added in ProfileService in .cshtml?

Asp .net core - Authorize access to all files in a folder via roles

I'm upgrading some initial razor code into asp .net razor pages with .net core 5.0. I've been through many examples on the microsoft site, but it seems that I have to set attributes in all of my .cshtml.cs files. that feels just sloppy and error prone because something will be forgotten somewhere.
In .net 4.x razor, I have an _PageStart.cshtml file, I check the user's role, and I redirect them to the login page if they are not in a particular role. I'd like to do the same in asp .net core using a single file or configuration. I don't want to put an attribute on every pagemodel file, that just seems sloppy. I imagine that I would do something like:
options.Conventions.AuthorizeFolder("/Club", "ClubAdmin");
where ClubAdmin is a role in the application and Club is a folder that contains a bunch of razor pages and sub folders. Is this possible?
TIA
To do this, you can define a policy in your Startup.cs file that checks for a role and then configure razor pages to Authorize that folder for that specific policy:
//define the admin policy
services.AddAuthorization(options =>
{
options.AddPolicy("AdminPolicy", policy => policy.RequireRole("Administrator"));
});
services.AddRazorPages(options =>
{
options.Conventions.AuthorizeFolder("/Admin", "AdminPolicy");
});
The RequireRole extension method injects a RolesAuthorizationRequirement handler that will validate for the given role during authorization

How to serve blazor app from a controller action in ASP.NET Core

I've previously asked this question for Blazor around the time when the 3.0 preview was out.
Is there a way to serve a Blazor app from a specific controller action in a MVC app?
Since then Blazor 3.2 has arrived, I did some research on how to accomplish this, I tried following the examples on this github issue but didn't really manage to get it working.
https://github.com/dotnet/aspnetcore/issues/20642
Thoughts?
Try this:
public IActionResult MyAction([FromServices] IWebHostEnvironment webHost)
{
var file = webHost.WebRootFileProvider.GetFileInfo("index.html");
return PhysicalFile(file.PhysicalPath, "text/html");
}
And change fallback in Startup.cs to:
app.UseEndpoints(endpoints =>
{
...
endpoints.MapFallbackToController("MyAction","controller")
});
A mix of Kazbek's answer and this post helped me to integrate blazor wasm to the existing MVC site. Now I have wasm served by a controller action protected by [Authorize].

.NET Core MVC Unable to Redirect to Identity Login Page

I have a .NET Core MVC Application ,and i used scaffolding for Identity Pages like Login ,Logout,Register in my application .I have put a URL link in my _LayOut.csHtml file to login pages as below
<li><a asp-area="Identity" asp-page="/Account/Login">Login</a></li>
but it doesnt redirect to Login Page .I dont think the Identity pages are MVC as there is a .cs file with each razor page,so i didnt create controller for them and return View as for other pages.
I found the issue ,since Identity pages are Razor Pages with code behind we need to add following lines in our StartUp.cs
1)In ConfigureServices method add this line
services.AddRazorPages();
2) In Configure method add this line
endpoints.MapRazorPages();
so it will be like this
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
endpoints.MapRazorPages();
});
After using the Scaffold for Identity pages, please follow the instruction in Migrations, UseAuthentication, and layout to perform the following steps:
Create a migration and update the database.
Add UseAuthentication to Startup.Configure file.
Add <partial name="_LoginPartial" /> to the layout file.
Test the app:
Register a user or Navigate to Login page.
More detail information about using Identity in Asp.net core, check the following links:
Scaffold Identity in ASP.NET Core projects
Add, download, and delete custom user data to Identity in an ASP.NET Core project

Validate if User/Request is authenticated .net core

I have implemented cookie authentication together with Novel ldap authentication in my .net core application.
I have a login screen where the users enters their credentials and once authenticated it redirects them to Home page. On my Login layout page I want to have a logout link which logouts the user out of the application. Earlier in my .net mvc application I could do:
#if (Request.IsAuthenticated)
{
<li>Hello, #ViewData["FullName"] !</li>
<li>Log Out</li>
}
else
{
<li>Log In</li>
}
All my authentication, redirects etc work fine but whats the equivalent of Request.IsAuthenticated in .net core or how can I check if the user is authenticated and show links etc accordingly.
Would appreciate inputs
What svek shared above should work. Debug to see if you are authenticating properly, you are setting up your cookies fine.
Specifically for .net core this should work.
#if (User.Identity.IsAuthenticated)
{
<a asp-area="" asp-controller="YouController" asp-action="YourAction">Logout</a>
}
I think what you are looking for is
User.Identity.IsAuthenticated