Role based Authorization for Razor Pages - asp.net-core

In asp.net core it is very easy to define the razor pages authorization for pages and folders as follows:
services.AddMvc()
.AddRazorPagesOptions(options =>
{
options.Conventions.AuthorizePage("/Contact");
options.Conventions.AuthorizeFolder("/Private");
options.Conventions.AllowAnonymousToPage("/Private/PublicPage");
options.Conventions.AllowAnonymousToFolder("/Private/PublicPages");
});
My problem is that I want to use roles in my project but I can not find a way to define which roles are allowed to view the contents of the page.
I tried to use the Authorize attribute but it does not work with Razor Pages.
The AuthorizePage can take a second parameter which can be used in order to define the policy which will be used in order to determine if the current use can see the specified page or not. I used it as follows:
services.AddAuthorization(options =>
{
options.AddPolicy("RequireAdministratorRole", policy => policy.RequireRole("Admin"));
});
services.AddMvc()
.AddRazorPagesOptions(options =>
{
options.Conventions.AuthorizePage("/Index", "RequireAdministratorRole");
});
The problem is that it still does noe work. It acts like I have not defined the policy. When I am logged I can see the page and when I am not logged it redirects me to the loggin form.
Is something else that I have to do in order to make it work?

I found what is wrong. In order to apply the changes after I remove the user from the role, I have to logout and login again so that the framework will refresh what the user allows to view.
This is really a problem because if a User has the admin role and for some reason we want to stop him from accessing sensitive data, we cannot stop him until he logs off.
Is there a way to refresh the user’s permissions when I remove a role from his account?
Restarting the application did not remove his permission. The only way to refresh his permissions is when he logs out.

This is due to the user's cookie still being valid. Here is more explanation to it here with a solution. Although it is in ASP.NET, the same concepts should apply for your Razor Pages project:
Refresh current user's role when changed in ASP.NET identity framework?

As to your latest question of
Is there a way to refresh the user’s permissions when I remove a role
from his account?
Yes you can refresh your logged in user using the SignInManager RefreshSignIn method.
As per the official documentation the method will
Signs in the specified user, whilst preserving the existing AuthenticationProperties of the current signed-in user like rememberMe, as an asynchronous operation.

Related

Blazor Authentication via existing database table

I want to build a Blazor server application that has user authentication. The only experience I have with Blazor was a simple app for work that used AD authentication and made various api calls to get the data necessary.
I have an existing sql table containing: userId, username, permissionLevel
Basically I want to be able to make a new table with the username and a hashed password that when matched will return an object containing userid, username, and permissionlevel that will be used for authentication in the Blazor server app.
Is this possible and are there any resources pointing me in the right direction for this? I have searched but have not come up with anything I am looking for. I am looking for examples of how to display certain options based on PermissionLevel.
Blazor Server supports Policy based authorization (https://learn.microsoft.com/en-us/aspnet/core/blazor/security/?view=aspnetcore-6.0#authorize-attribute) - Example:
#page "/"
#attribute [Authorize(Policy = "PermissionLevel.5")]
<p>You can only see this if you satisfy the 'PermissionLevel.5' policy.</p>
You can register all policies (PermissionLevels) in Startup.cs, example:
services.AddAuthorization(options =>
{
options.AddPolicy("PermissionLevel.5",
policy => policy.RequireClaim("Permission", "PermissionLevel.5"));
});
Unlike with Role based authorization, only a single policy can be applied inside any Authorize attribute, or AuthorizeView component. You can however evaluate multiple requirements for a single policy (such as if PermissionLevel must be '5' or higher) by customising your own AuthorizationHandler (see MS Docs for some good examples: https://learn.microsoft.com/en-us/aspnet/core/security/authorization/policies?view=aspnetcore-6.0#use-a-handler-for-multiple-requirements - You can also refer to my last link below for a detailed example using Role Claims, by #pacificoder).
If you use ASP.NET Identity (such as with a Blazor Project's Individual User Accounts), the AspNetUserClaims table is created for you (see https://learn.microsoft.com/en-us/aspnet/core/security/authentication/customize-identity-model?view=aspnetcore-6.0#entity-types), which contains all the user-claim pairs. Claims can be assigned to users during runtime by using UserManager.AddClaimAsync().
This would be sufficient if you do not have many claims - However the more permissions and roles a user has, the larger the access token becomes (and you could get an "Access token must not be longer than 4K" error - I started getting this after adding 5+ claims to a role, but not sure how easy it is to exceed 4K with user claims only...).
If you consider using Policy-based authorization, I would recommend taking a look at this answer by #pacificoder: https://stackoverflow.com/a/49539930/13678817 - Although this relates to Role based policies, the same approach can be used for user based policies, and I also liked the way Enums are used to create and add all the permissions/policies.

How do I enforce 2FA in .Net Core Identity?

Question: How can I enforce existing users to set up 2FA in .Net Core 3.1 Identity?
I have seen a couple of answers here already, but I have issues with them as follows:
Redirect user to set up 2FA page on login if they do not have it set up. Problem with this is that the user can simply jump to a different url to avoid this, therefore it is not actually enforced.
Have some on executing filter that checks if the user has 2FA enbaled or not and if not redirect them to MFA set up page. The issue I have with this is that on every single navigation the server must go to the database to check whether the user has this field enabled, thus creating a significant performance hit on each request. I know one trip to the database may not sound like much but I have worked with applications where this was the norm and other things used this method, causing a pile up of pre action db queries. I want to avoid this kind of behavior unless absolutely necessary.
My current idea is to on login:
Check the users credentials but NOT log them in
userManager.CheckPasswordAsync(....)
If the credentials pass, check if the user has 2FA enabled or not. If they do, continue through login flow, if not:
Generate a user token:
userManager.GenerateUserTokenAsync(.......)
and store this along with the username in a server side cache. Then pass a key to the cached items with a redirect to the 2FA setup page, which will not have the [authorize] attribute set, allowing users not logged in to access it.
Before doing anything on the 2FA set up page, retrieve the cached items with the provied key andverify the token and username:
userManager.VerifyUserTokenAsync(......)
If this doesn't pass, return Unauthorized otherwise continue and get the current user from the supplied UserName in the url that was passed via a cache key. Also dump the cached items and key so that should the url be snatched by a dodgy browser extension it can't be used again.
Continue to pass a new cache key to new user tokens and usernames to each 2FA page to authenticate the user as they navigate.
Is this an appropriate use of user tokens? And is this approach secure enough? I'm concerned that having the user not logged in presents security issues, but I think it is necessary in order to avoid the previously mention problem of going to the database on every request to check 2FA, as with this method trying to navigate away will just redirect to login.
I implemented this via a Filter Method
I have a BasePageModel which all my pages inherit
public override async Task OnPageHandlerExecutionAsync(PageHandlerExecutingContext context, PageHandlerExecutionDelegate next)
{
if (!User.Identity.IsAuthenticated)
{
await next.Invoke();
return;
}
var user = await UserManager.GetUserAsync(User);
var allowedPages = new List<string>
{
"Areas_Identity_Pages_Account_ConfirmEmail",
"Areas_Identity_Pages_Account_ConfirmEmailChange",
"Areas_Identity_Pages_Account_Logout",
"Areas_Identity_Pages_Account_Manage_EnableAuthenticator",
"Areas_Identity_Pages_Account_ResetPassword",
"Pages_AllowedPageX",
"Pages_AllowedPageY",
"Pages_Privacy"
};
var page = context.ActionDescriptor.PageTypeInfo.Name;
if (!user.TwoFactorEnabled && allowedPages.All(p => p != page))
{
context.Result = RedirectToPage("/Account/Manage/EnableAuthenticator", new { area = "Identity" });
}
else
{
await next.Invoke();
}
}
I then changed both the Disable2fa and ResetAuthenticator pages to redirect to the main 2fa page
public IActionResult OnGet() => RedirectToPage("./TwoFactorAuthentication");
And removed the reset/disable links from that page
I chose to implement a more modern and OAuth friendly solution (which is inline with .Net Core Identity).
Firstly, I created a custom claims principal factory that extends UserClaimsPrincipalFactory.
This allows us to add claims to the user when the runtime user object is built (I'm sorry I don't know the official name for this, but its the same thing as the User property you see on controllers).
In here I added a claim 'amr' (which is the standard name for authentication method as described in RFC 8176). That will either be set to pwd or mfa depending on whether they simply used a password or are set up with mfa.
Next, I added a custom authorize attribute that checks for this claim. If the claim is set to pwd, the authorization handler fails. This attribute is then set on all controllers that aren't to do with MFA, that way the user can still get in to set up MFA, but nothing else.
The only downside with this technique is the dev needs to remember to add that attribute to every non MFA controller, but aside from that, it works quite well as the claims are stored in the users' cookie (which isn't modifiable), so the performance hit is very small.
Hope this helps someone else, and this is what I read as a base for my solution:
https://damienbod.com/2019/12/16/force-asp-net-core-openid-connect-client-to-require-mfa/
https://learn.microsoft.com/en-us/aspnet/core/security/authentication/mfa?view=aspnetcore-5.0#force-aspnet-core-openid-connect-client-to-require-mfa

How to restrict access some part of module in ZendFramework 2 (i.e. only administrator can do some actions)

so!
I have a question: how to allow access some part of module only for adminisitrator, for example.
For example, I have module album. It has controllers index, delete, add, edit, full. I want full and index controller be available for all roles, but edit, delete and add action only for administrators.
What module I have to use to do that? I found Zend\Authentification.
Table is: username, password, role.
How to authentificate user?:
// do the authentication
$auth = Zend_Auth::getInstance();
$result = $auth->authenticate($authAdapter);
if ($result->isValid()) {
// success: store database row to auth's storage
// system. (Not the password though!)
$data = $authAdapter->getResultRowObject(null, 'password');
$auth->getStorage()->write($data);
$this->_redirect('/');
} else {
// failure: clear database row from session
$this->view->message = 'Login failed.';
}
After that I will get access to user data, for example, by:
Zend_Auth::getInstance()->getIdentity()->username;
So, in action, in which I want to restrict access I just need to use:
if(Zend_Auth::getInstance()->getIdentity()->role == admin) {
redirect("auth/login");
}
Right?
The questions:
Is my suggestion about how to check user role in each contoller correct?
Do I understand correctly how to work with Zend\Authentification and restrict access to some actions? So in future I will just use same for each action, right?
Additional question: Does Aclmodule uses for managing permissions? So Acl is needed to help Zend_Auth with permissions, right?
To be able to do this you have to build or implement an ACL (Access Control List). You can also use a third party solution in combination with the earlier mentioned Zend_Auth (or any other authentication module). You can read more on Zend ACL here: Zend ACL introduction
You could for example also take a look at BjyAuthorize. This ACL module provides a complete authorization solution for your application but depends on ZfcUser for user authentication and registration. It might be a good way to get started.
If you are done building or implementing BjyAuthorize you can easily tie your access permission checking to your routes (but there are many other ways). You can see how this works here on the BjyAuthorize GitHub page
These modules will teach you a lot about how authentication and authorization can be build into your Zend Framework 2 application.

How to propagate an administrator's changes to a user's claims

Situation
Let's say an administrator of a site removes a user from the Admin role and adds her to the Contributor role. According to the site's database, that user has been demoted and should no longer have access to Admin-only features. Now the user comes back to the site some time after that change, but had logged in sometime before the change and is still logged in. So long as that user does not log out, she will continue to have claims that say she is in the Admin role. If she logs out, or gets logged out, she loses the claim that she belongs to the Admin role and when she signs back in receives the new claim of belonging to the Contributor role.
Desire
What I would like to happen, perhaps the next time the user requests a page from the site after the administrator made the change, is have that user transparently lose the Admin role claim and gain the Contributor role claim without them having to sign out or do anything special. In fact, I would prefer they are unaware of the change, except that her menu has changed a little because she can no longer perform Admin-only activities.
How would you handle this situation in a way that is invisible to the affected user?
My thoughts
I am using ASP.NET MVC 5 and ASP.NET Identity, but it seems like a solution to this could be easily generalized to other claims based frameworks that utilize cookies. I believe that ASP.NET Identity stores claims in the user's cookies by default in MVC 5 apps.
I have read the following post along with many others on SO and it comes closest to answering this question but it only addresses the case where the user updates herself, not when someone else like an administrator makes the change to her account: MVC 5 current claims autorization and updating claims
There is a feature in Identity 2.0 which addresses this, basically you will be able to do something like this which adds validation at the cookie layer which will reject users who's credentials have changed so they are forced to relogin/get a new cookie. Removing a role should trigger this validation (note that it only does this validation check after the validationInterval has passed, so the cookie will still be valid for that smaller timespan.
app.UseCookieAuthentication(new CookieAuthenticationOptions {
AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
LoginPath = new PathString("/Account/Login"),
Provider = new CookieAuthenticationProvider {
// Enables the application to validate the security stamp when the user logs in.
// This is a security feature which is used when you change a password or add an external login to your account.
OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser>(
validateInterval: TimeSpan.FromMinutes(30),
regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))
}
});

SimpleMembershipProvider roles not accessible

I have MVC4 application which uses SimpleMEmbershipProvider for authentication mechanism.
Everything works fine, apart of when I return to the application and authenticate using persistant cookie.
I am authenticated fine, but cannot access roles that I am assigned to. Effectively, cannot access roles at all:
string.Join(",", Roles.GetRolesForUser(User.Identity.Name))
returns empty string
What might be causing that?
This can happen when the SimpleMembershipProvider hasn't been initialized. The example MVC forms authentication template assumes that you'll be allowing anonymous access to your site and doesn’t initialize the membership provider until you go to the login page. However, a more common security technique is to require a login for any site access and to define menu choices in the _layout page to be determined by roles. But, if you use the persistent cookie, you don’t revisit the login page so the roles for the authenticated user aren’t loaded from the membership database.
What you want to do is initialize the provider when the user enters the site so that values get loaded. To do this, you want to add the following filter in the RegisterGlobalFilters method of the FilterConfig class in the App_Start folder
filters.Add(new YourAppNameSpace.Filters.InitializeSimpleMembershipAttribute());
This will cause the user data to be loaded from the database when a cookie authenticated user enters the site.
Another alternative technique is to add the [InitializeSimpleMembership] decorator to any controller method that cookie autheticated users might enter directly. This is kind of messy though if you have to put it on a lot of controllers. Therefore, putting it in the global filter is better in most cases.