Authentication And Authorization (Part 3)
Adding Authorization
We can determine if a
user is authenticated, but we also need to know if they have the rights to use
a specific feature. This is the essence of authorization. Fortunately, the
available built-in functions accommodate this, even if we need to implement some
code to achieve it. The server side contains all the tables required to assign
roles to our users, but there are currently no user interfaces accessible for
this purpose.
Adding Roles From The Server
Execute the following
steps to add roles from the server:
- In the MyBlogWebAssembly.Server project, open the Startup.cs file.
- In the ConfigureServices method, add options to .AddApiAuthorization and remove the default claim mapping.
- Add roles to Services.AddDefaultIdentity.
- Add the namespace-
using
Microsoft.AspNetCore.Identity;
using
System.IdentityModel.Tokens.Jwt;
The server will now send the roles over to the client,
but the client won't be listening.
Adding Roles To The Client
For the client to pick up the roles, we need to parse
them from the access token:
- Right-click in the MyBlogWebAssembly.Client project, then click Add | New folder. Name the folder Authentication.
- Right-click on the Authentication
folder and select Add | Class, then name the class RoleAccountClaimsPrincipalFactory.cs.
- Replace the content of the file with the code from GitHub here-
https://github.com/PacktPublishing/Web-Development-with-Blazor/
blob/master/Chapter08/MyBlog/MyBlogWebAssembly/Client/
Authentication/RoleAccountClaimsPrincipalFactory.cs.
- Now we need to add that
to the dependency injection pipeline. Open program.cs and replace builder.Services.AddApiAuthorization();
with the following-builder.Services.AddApiAuthorization()
.AddAccountClaimsPrincipalFactory>();
- Add this to the namespace-
using MyBlogWebAssembly.Client.Authentication;
Adding A Role To The Database
To add data to our
database, we can use a tool called DB Browser for SQLite:
- Download DB Browser for SQLite from https://sqlitebrowser.org/.
- Open MyBlog.db in DB Browser; there should be 15 tables there.
- Click the Browse data tab and select the AspNetRoles table.
- Now create a role. You can
call it Administrator.
- Change table to AspNetUsers and copy the ID of your user (a GUID).
- Change table to AspNetUserRoles and click on the Insert new row into the current table button (a document with a small +), then paste in the ID of the user and the ID of the role.
Now, we have
authentication and authorization working.
Conclusion
We learnt how to add
authentication to our existing site.
Comments
Post a Comment