Lab 13

Download as pdf or txt
Download as pdf or txt
You are on page 1of 5

Workshop: Building an Enterprise

Application with ASP.NET Core MVC


Web APP Theme: SIDJEME

Lab13: Securing you application with ASP.NET Identity

Exercise 1: Scaffold Identity in ASP.NET Core projects


Scenario
In this exercise, you will scaffold identity to your Asp.Net Core MVC project.

The scaffolding feature will configure Asp.Net Core Identity and add Razor pages for identity
management.

Task 1: Scaffold identity


1. Open Visual Studio 2019 and in the Get Started Window, select Open Project or Solution
o Location: [Root Repository] \SIDJEME Labs\SIDJEME\SIDJEME.sln
2. Note that the solution contains a newly added class library project named
Ansej.Sidjeme.Identity under the Presentation folder.
3. The project was added to share Identity Models between the Ansej.Sidjeme.Web and
Ansej.Sidjeme.Api projects.
4. Review ApplicationUser.cs an IdentityContext.cs files in the Ansej.Sidjeme.Identity.
5. These files represent the Identity User and Identity DB context used in your application.
6. You can add properties to the ApplicationUser class to change the default identity user schema.
7. Also, you can add other entities to the IdentityContext to change the default identity DBschema.
8. From Solution Explorer, right-click on Ansej.Sidjeme.Web project > Add > New Scaffolded Item.
9. From the left pane of the Add Scaffold dialog, select Identity > Add.
10. In the Add Identity dialog, select the options as following:

o Select an existing layout page: let it empty because the _Layout is configured in the
_ViewStart.cshtml
o Choose files to override: select
 Account\Login
 Account\Logout
 Account\Register
 Account\Manage\Index
 Account\Manage\SetPassword
 Account\Manage\ChangePassword
 Account\Manage\PersonalData

o Data context class: use the select dropdownlist to select IdentityContext


(Ansej.Sidjeme.Identity)
11. In the Add Identity dialog, click Add.
12. You can review the generated razor pages in the Areas/Identity/Pages folder.
13. In the Areas/Identity folder, open IdentityHostingStartup.cs file, and register Identity services as
following:
services.AddDbContext<IdentityContext>(options =>
options.UseSqlServer(

context.Configuration.GetConnectionString("IdentityContextConnection"),
x=>x.MigrationsAssembly("Ansej.Sidjeme.Web")));

services.AddDefaultIdentity<ApplicationUser>(options =>
options.SignIn.RequireConfirmedAccount = false)
.AddEntityFrameworkStores<IdentityContext>();
1. Note the use of a connection string named IdentityContextConnection.
2. In the Ansej.Sidjeme.Web project, open appsettings.json file.
3. Notice that IdentityContextConnection connection string is present.
4. In the Views/Shared folder, remark that two partial views were added,
_CookieConsentPartial.cshtml and _LoginPartial.cshtml. The first renders a partial view to accept
the use of cookies as you see on websites; the second renders its content according to the
authentication information (if anonymous access, it displays connection and registration links if
not displays the information of the logged in user and the logout link).
5. In the Views/Shared/Components folder, open the Default.cshtml view which represents the
application menu.
6. Locate the /*TODO: Embed the _LoginPartial view*/ comment just after the comment
embed the _LoginPartial view using the <partial> tag helper.
7. Open the Startup.cs file and locate the comment //TODO: MapRazorPages, just after it, Map
Razor Pages using the endpoints object.

Task 2: Create the Identity Database schema using migrations


1. Rebuild the Solution and ensure there are no errors.
2. Open the Package Manager Console.
3. In the Default project select Ansej.Sidjeme.Web project.
4. Use the Add-Migration command line with the following options:
a. -Name: CreateIdentitySchema
b. -Context: IdentityContext
5. Review the migration Up method.
6. Use the Update-database command line to create the SidjemeIdentityDB database with the
following options:
a. -Context: IdentityContext
7. Ensure that the command executed successfully.
8. Open SQL Server Management Studio and review the SidjemeIdentityDB tables.
Exercise 2: Adding ASP.NET Core Identity Authentication
Scenario
In this exercise, you will configure Asp.Net Core Authentication.

Task 1: Enable Authentication middleware


1. In the Ansej.Sidjeme.Web project, open Startup.cs.
2. Locate the //TODO: Enable Authentication middleware, just after the comment enable the
Authentication middleware.
3. Build the solution and ensure there are no errors.
4. Run the solution.
5. In the Sidjeme App, confirm that the _LoginPartial view was rendered correctly as the Register
and Login links appears on the header right side.
6. Click Register link and register a new user by adding you email and password.
7. Using SQL Server Management Studio, confirm that the user was added correctly by viewing the
content of the AspNetUsers table in the SidjemeIdentityDB.
8. Return to the Sidjeme App, click login link and try to login using the registered user information.
9. After successful login, note that your username appears on the header right side.
10. Click the username, and browse the different account management pages enabled by the
scaffolding tool.
11. Add phone number to the user in the Profile page. Ensure that the phone number was saved
correctly in the Database using SQL Server Management Studio.
12. Close the browser and stop debugging.

Task 2: Requiring Authenticated user on specific resource (Disabling Anonymous access to resource)
1. In the Ansej.Sidjeme.Web project, open Startup.cs.
2. Locate the //TODO: Enable Authorization middleware, just after the comment enable the
Authorization middleware.
3. Under Controllers folder, open SessionValidationController.cs file.
4. Locate the //TODO: Import Microsoft.AspNetCore.Authorization namespace comment, just
after it import the asked namespace.
5. Locate the comment //TODO: Add the Authorize attribute to disable anonymous access
to this controller; just after it and above the class definition Add [Authorize] attribute.
6. Build the solution and ensure there are no errors.
7. Run the solution.
8. In the Sidjeme App, ensure the user is not logged in (If so, click the logout link).
9. In the main menu click Sessions and ensure that your redirected to the login page. In other
words, the access to this resource is not allowed to anonym user.
10. Login using the user your registered previously, and try to access to the Sessions page; this time
you can access the page.
11. Close the browser and stop debugging.
Exercise 3: Configuring Asp.Net Core Authorization
Scenario
In this exercise, you will configure Asp.Net Core Authorization. Explore different options to secure
access to resources according to roles or policies.

Task 1: Single authorization policy used globally


1. In the Ansej.Sidjeme.Web project, open Startup.cs file.
2. Locate the //TODO: Add Single policy used globally comment, just after it configure MVC
options to use a global Authorize filter as following:
o =>
{
var policy = new AuthorizationPolicyBuilder()
.RequireAuthenticatedUser()
.Build();

o.Filters.Add(new AuthorizeFilter(policy));
}
3. Build the solution and ensure there are no errors.
4. Run the solution.
5. Note that all pages are now inaccessible if you are not authenticated; the only accessible are
those marked with [AllowAnonymous] attribute like Register page, Login Page.
6. Close the browser and stop Debugging.
7. Under Areas/Identity/Pages/Account folder, open the Register.cshtml page then press F7 to
access the page code behind.
8. Comment out the [AllowAnonymous] attribute to disable registering feature for
unauthenticated users.
9. You will, configure the correct access policy later in this exercise.

Task 2: Adding authorization policies


1. Right click the Ansej.Sidjeme.Web project and create a new folder named Policies.
2. In the Policies folder Add a code file named SidjemePolicies.cs.
3. In the SidjemePolicies.cs file add a public enum named SidjemePolicies with the following
values:
 ManageIdentity,
 ManageReferentiels,
 ManageCSVF

Note: the SidjemePolicies enum must be created in the Ansej.Sidjeme.Web namespace.

4. In the Ansej.Sidjeme.Web project, open Startup.cs file.


5. Locate the //TODO: Adding Authorization Policies comment, set the focus just after it and
insert code from file by click the Visual Studio Edit -> Insert File As Text…
6. In the Insert File Dialog, go to [Root Repository] \SIDJEME Labs folder and select the file
Adding_Authorization_Policies.txt then click Open.
7. Review how authorization policies are added and configured using the
AuthorizationPolicyBuilder.
8. Also, notice the requirements of each policy (ManageIdentity, ManageReferentiels and
ManageCSVF).

Task 3: Applying authorization policies


1. In Ansej.Sidjeme.Web project, open GenericReferentielController.cs file under the
controllers folder.
2. In GenericReferentielController.cs file, import the namespace
Microsoft.AspNetCore.Authorization.
3. Locate the comment //TODO: Add Authorize Attribute with ManageReferentiels policy,
just after the comment add an Authorize attribute and set its policy property to
nameof(SidjemePolicies.ManageReferentiels).
4. Open ActiviteController.cs file, import the namespace
Microsoft.AspNetCore.Authorization.
5. Locate the comment //TODO: Add Authorize Attribute with ManageReferentiels policy;
just after the comment add an Authorize attribute and set its policy property to
nameof(SidjemePolicies.ManageReferentiels).
6. Open SessionValidationController.cs file, locate the comment //TODO: Add the Authorize
attribute to disable anonymous access to this controller, change the Authorize
attribute by settings its Policy property to nameof(SidjemePolicies.ManageCSVF).
7. Under Areas/Identity/Pages/Account folder, open the Register.cshtml page then press F7 to
access the page code behind.
8. Just after the commented [AllowAnonymous] attribute, add an Authorize attribute and set its
Policy property to nameof(SidjemePolicies.ManageIdentity).
9.

You might also like