I'm working on a dotnet core/js application in which all of the frontend code including authentication page is produced with a JS framework where the bundled frontend is injected into a single Razor page. The frontend accesses all dotnet core logic from controller api endpoints. The authentication utilize bearer tokens and the [Authorize(role='whatever')] is used in several controllers.
For some reason, a single javascript plugin is injected into the app from the razor page. I basically need this plugin not to be visible before the user is authenticated. It's not a matter of "secret" content but the plugin just isn't useful before the user is authenticated. Is there a simple way for me to find out if the user is authorized within the CSHTML of the code as with the controller attributes? I've been searching around and found nothing very useful. Not an expert on c# or dotnet core (mostly been working on the frontend) and simplest possible solution would be appreciated. Don't know if I've missed any relevant information. If so, tell me!
Depending on the complexity of your condition, you have a few ways to authorize the user.
If you just want to verify that the user is authenticated, i.e. that they are successfully logged in, regardless of who the user is, then you can just check against User.Identity.IsAuthenticated:
@if (User.Identity.IsAuthenticated)
{
<p>User is signed in.</p>
}
If you want to verify that the user has a specific role, then you can also operate on the User principal object directly and just check for that specific role:
@if (User.IsInRole("role-name"))
{
<p>User is in role <em>role-name</em>.</p>
}
Otherwise, if you want to utilize the full capability of the authorization system in ASP.NET Core, you can also inject the IAuthorizationService and authorize the user against a configured authorization policy:
@inject IAuthorizationService _authorizationService
@if ((await _authorizationService.AuthorizeAsync(User, "policy-name")).Succeeded)
{
<p>User was authorized against policy <em>policy-name</em>.</p>
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With