Select theme:
Radzen Blazor Studio allows you to easily add security based on ASP.NET Core Identity to your Blazor application. A mandatory requirement is an existing database connection - MSSQL, Oracle, MySQL or Postgres.
To add ASP.NET Core Identity security to your app:
When security is enabled Radzen Blazor Studio will allow you to specify which users can access a page. If a user doesn’t have access to certain page it will not appear in the application navigation. If the user enters that page URL manually in the browser they will see a generated unauthorized page.
By default pages created in Radzen Blazor Studio allow access to Everyone - both authenticated and anonymous users.
To specify who can access a page:
The code generated for this example is:
@attribute [Authorize(Roles="Administrator")]
To specify multiple roles via code separate them with a comma: @attribute [Authorize(Roles="Role1,Role2")]
.
If multiple roles are specified a member of either role can view the page.
Important: Do not remove the Anonymous access from the
Login
page. If you do that your users won't be able to log in.
During development you can use a special account for testing. Log in with admin as both username and password.
This account is available only during development (when the ASPNETCORE_ENVIRONMENT
environment variable is set to Development
).
The test admin account belongs to all roles defined in the application and has full access as a result.
Important: After deployment the admin account is no longer available! Be sure to either allow user registration or create at least one user account during development.
An authorized user can add roles from the Roles page accessible from the top-right application menu.
By default all authenticated users have access to the role management pages. Make sure you restrict the access to those pages before deploying to a production environment. Create an Administrator role and allow only member of this role to access the role management pages.
A Blazor application created by Radzen Blazor Stydio starts with no users apart from the development-only admin account mentioned above.
There are two ways to add users to an application
By default all authenticated users have access to the user management pages. Make sure you restrict the access to those pages before deploying to a production environment. Create an Administrator role and allow only member of this role to access the role management pages.
Radzen Blazor Studio applications use various controllers to access data over HTTP - AccountController for login, registration, ApplicationUsersController and ApplicationRolesController to manage users and roles. Blazor WASM expose a database as a OData controller. By default only ApplicationRolesController and ApplicationUsersController disallow anonymous access.
To require authorized access you need to decorate the controllers with the Authorize attribute.
To disable anonymous access and allow any logged-in user edit the controller code and add [Authorize]
before the class declaration.
/* snip */
using Microsoft.AspNetCore.Authorization;
namespace [Namespace].Server.Controllers.[Database]
{
[Authorize] // -> Allow any authenticated user. Disallow anonymous access.
[Route("odata/Northwind/Orders")]
public partial class OrdersController : ODataController
{
/* snip */
}
}
Important: Do not add the
Authorize
attribute to the AccountController class as it will effectively disable login and registration.
To allow only certain roles specify the Roles property during decoration:
/* snip */
using Microsoft.AspNetCore.Authorization;
namespace [Namespace].Server.Controllers.[Database]
{
[Authorize(Roles="Administrator,Sales")] // -> Allow only members of the Administrator or Sales role
[Route("odata/Northwind/Orders")]
public partial class OrdersController : ODataController
{
/* snip */
}
}
Instead of adding the Authorize
attribute to every controller you can apply a global filter policy to all routes in the applications.
Open Program.cs
or Server\Program.cs
(WASM).
Import the following namespaces.
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Authorization;
Add this code just before var app = builder.Build();
builder.Services.Configure<MvcOptions>(options =>
{
var policy = new AuthorizationPolicyBuilder()
.AddAuthenticationSchemes(IdentityConstants.ApplicationScheme)
.RequireAuthenticatedUser();
.Build();
options.Filters.Add(new [Namespace].Filters.ApplicationAuthorizeFilter(policy));
});
The ApplicationAuthorizeFilter
allows anonymous access only to AccountController
and the Login
page.
public class ApplicationAuthorizeFilter : AuthorizeFilter
{
public ApplicationAuthorizeFilter(AuthorizationPolicy policy): base(policy)
{
}
public override Task OnAuthorizationAsync(AuthorizationFilterContext context)
{
if (context.HttpContext.Request.Path.StartsWithSegments("/Account") || context.HttpContext.Request.Path.StartsWithSegments("/Login"))
{
return Task.CompletedTask;
}
return base.OnAuthorizationAsync(context);
}
}
Radzen Blazor Studio generates a service called SecurityService
and makes it available in all pages as the Security
property. This service allows you to:
The User
property is an instance of the ApplicationUser
class.
var name = Security.User.Name;
The IsInRole
method checks if the current user is a member of the specified role(s).
var isAdmin = Security.IsInRole("Administrator");
var isUserOrAdministartor = Security.IsInRole("Administrator", "User");
The IsAuthenticated
method checks if the current user is authenticated (has logged in).
var isAuthenticated = Security.IsAuthenticated();
The Logout
method redirects to the /Account/Logout
action which logs the current user out and redirects to the login page.
Security.Logout();
Two-factor authentication provides an extra layer of security by sending a one-time code to the user email after login. The user must enter the code in order to complete the login.
You can enable two-factor email authentication from the Identity security settings. A working email server configuration is required.
Important: Two-factor authentication is enabled per user during login and is persisted in the
AspNetUsers
table. This means that users who have logged in via two-factor authentication would still need it even if you later decide to turn that option off for your application. You can use theuserManager.SetTwoFactorEnabledAsync()
method to enable or disable two-factor authentication per user inAccountController.cs
:
await userManager.SetTwoFactorEnabledAsync(user, true /* false */);
You can change the two-factor email contents by editing AccountController.cs
.
Before deploying your Blazor application that has ASP.NET Core Identity security enabled make sure that:
This could happen if:
http
and your server isn't configured to redirect automatically to https
.The login may still work as expected during development as it relies on the development SSL certificate installed by the .NET runtime or Visual Studio.
This would happen if there isn't a valid development certificate installed. You may also see the following exception:
The ASP.NET Core developer certificate is not trusted
Follow the official Microsoft documentation for further instructions.
This would happen if the Login page does not have anonymous access - the Access property must be set to Everyone
and
it should not contain code such as @attribute [Authorize]
.
The admin account is available during development only. Make sure you have created some users or enabled user registration before deploying your application.
Radzen is free to use. You can also test the premium features for 15 days.
Download NowSelect theme: