Monday 23 April 2018

Setup ASP.Net Core 2.0 App with Identity Service - Part 2: Authorization



In a previous post , I have demonstrated how to set up an ASP.Net Core 2.0 application with Identity server for authentication. In this post, I will walk you through how to set up the authorization in an application.

If you like to follow the post with coding, you can find the initial git repo in this location

To prevent unauthorized access to MVC Controllers and Actions, we can simply add the built-in Authorized Attribute. IF we add AllowAnonymous attribute , any user can access the system without special privileges.

If we need to limit the access to a particular controller or action, we can use the ASP.NET Core handles claims authorization with a policy-based model. A policy has one or more requirements that have to be met. This can be the mere the presence of a claim for an identity or checking for specific claim values. To add the Authorization policy , we need to update the  ConfigureServices method in the start up class.

services.AddAuthorization(options => { options.AddPolicy("TeachersOnly",
                                                policy => policy.RequireClaim("TecherId"));
                            });

Next we need to incorporate this defined policy into our controller action. In this example we assume that students can be added only by Teachers. 

We need to add the following attribute to the create GET and POST methods in the students controller. 
 [Authorize(Policy = "TeachersOnly")]

Now if you run your application and try to add a student, you will auto redirected to the login page. This is because you do not have the proper privileges. 

In order to add the required claims, you need to add specific  user's claims to an user account. We can do this during the user registration process as follows. 

if (!string.IsNullOrEmpty(model.TeacherId))
                {
                    user.Claims.Add(new Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserClaim<string>
                    {
                        ClaimType = "TecherId",
                        ClaimValue = model.TeacherId
                    });
                        
                    
                }

 <div class="form-group">
            <label asp-for="TeacherId" class="col-md-2 control-label"></label>
            <div class="col-md-10">
                <input type="text" asp-for="TeacherId" class="form-control" />
            </div>
        </div>


No comments:

Post a Comment