When adding a new razor page to locahost/error/404 I am not able to authenticate the user.The meny on the top does have Register and Login. But if I press "Login" and get sent to the https://localhost/Identity/Account/Login, I am authenticated. So this is only on custom razor pages that this is happening.
@page
@model WebApplication1.Pages.ErrorPages._404Model
@{
}
<h1>404 - THIS PAGE WAS NOT FOUND</h1>
@(User.IsInRole("Admin") ? ",AUTHENTICATED" : "NOT AUTHENTICATED")
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
namespace WebApplication1.Pages.ErrorPages
{
public class _404Model : PageModel
{
public void OnGet()
{
}
}
}
I tried asking ChatGPT. I have google a lot. And I have tried to add different parts and codes, eg:
private readonly DbContext _dbContext;
private readonly UserManager<ApplicationUser> _userManager;
private readonly SignInManager<ApplicationUser> _signInManager;
public IndexModel(DbContext context,
UserManager<ApplicationUser> userManager,
SignInManager<ApplicationUser> signInManager)
{
_dbContext = context;
_userManager = userManager;
_signInManager = signInManager;
}
I tried to verify if Program.cs does have any limitations regarding to authenticate only users on certain pages.
I added @(User.IsInRole("Admin") ? ",AUTHENTICATED" : "NOT AUTHENTICATED")
on a /Identity/Account-page, there it worked. On my custom pages it did not work.
The issue
So the issue is that all of the .net core pages/views I create does not inherit the authorization. The user appear to be unauthorized (and in backend code the user is unauthorized for these pages) . But if I go back to any of the Microsoft Identity pages he is authorized or if I go to my angular page I am authorized, so this is only something happening on my custom pages in the pages folder.
EDIT: So still looking for what could be wrong I found out that if I put my page inside the Areas/Identity/Manage-folder, the user is authenticated and I can verify it. But putting the file in /Pages/... will not be able to verify that the user is authenticated. If anyone have any idea what setting is limiting this, please tell.
So I found two similar post on stackoverflow who helped me out, and it was the following two:
User.Claims is empty for every page outside of Areas/Identity
How do I set up authentication & authorisation for ASP .NET Core 3.0 with PageModels?
So I ended up with changing my Program.cs and added spesific authorization in my handler, and that was it
builder.Services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = IdentityConstants.ApplicationScheme;
options.DefaultChallengeScheme = IdentityConstants.ApplicationScheme;
}).AddIdentityServerJwt();
And:
[Authorize(AuthenticationSchemes = "Identity.Application")]
And that was it!