0% found this document useful (0 votes)
2 views

Unit-8 Securing in ASP

The document outlines the processes of authentication and authorization in ASP.NET Core applications, detailing how to implement user identity management using ASP.NET Core Identity. It provides instructions for adding authentication to applications using CLI commands, creating a web app with individual user accounts, and configuring services and middleware for authentication and authorization. Additionally, it explains role-based authorization, claims, and how to restrict access to controllers and actions based on user roles.

Uploaded by

amittimalsina999
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Unit-8 Securing in ASP

The document outlines the processes of authentication and authorization in ASP.NET Core applications, detailing how to implement user identity management using ASP.NET Core Identity. It provides instructions for adding authentication to applications using CLI commands, creating a web app with individual user accounts, and configuring services and middleware for authentication and authorization. Additionally, it explains role-based authorization, claims, and how to restrict access to controllers and actions based on user roles.

Uploaded by

amittimalsina999
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 16

Securing in ASP.

NET Core Application


Authentication—The process of
determining who made a request.

Authorization—The process of
determining whether the requested
action is allowed.
Authentication

Authentication is a process of confirming / recognizing a user’s identity. It is a set of


actions, used to verify the user’s credentials against the ones in the database. For
the user to be able to provide credentials, An application requires a Login page
with a set of fields for the user to interact with.
ASP.NET Core Identity

ASP.NET Core Identity is a membership system which allows you


to add login functionality to your application. Users can create an
account and login with a user name and password or they can use an
external login providers such as Facebook, Google, Microsoft
Account, Twitter and more.You can configure ASP.NET Core Identity
to use a SQL Server database to store user names, passwords, and
profile data. Alternatively, you can use your own persistent store to
store data in another persistent storage.

ASP.NET Core Identity:


• Is an API that supports user interface (UI) login functionality.
• Manages users, passwords, profile data, roles, claims, tokens, email
confirmation, and more.
Adding authentication to Apps(CLI)
The quickest way to add authentication to ASP .NET Core App is to use one of
the pre-built templates with one of the Authentication options.
• None: No authentication
• Individual: Individual authentication
• IndividualB2C: Individual authentication with Azure AD B2C
• SingleOrg: Organizational authentication for a single tenant
• MultiOrg: Organizational authentication for multiple tenants
• Windows: Windows authentication

The CLI Commands for MVC, Razor Pages and Blazor (Server), respectively:
> dotnet new mvc --auth Individual -o MVCDemo
> dotnet new webapp --auth Individual -o PageDemo
> dotnet new blazorserver --auth Individual -o BlazorDemo

The dotnet new command is followed by the template name (mvc, webapp,
blazorserver).
The –auth option allows you to specify the authentication type, e.g. Individual
The -o option is an optional parameter that provides the output folder name for the
Create a Web App with Authentication

Create an ASP.NET Core Web Application project with Individual User Accounts.

• Select File > New > Project.


• Select ASP.NET Core Web Application. Name the project DemoApp to have the
same namespace as the project download. Click OK.
• Select an ASP.NET Core Web Application, then select Change Authentication.
• Select Individual User Accounts and click OK.

The generated project provides ASP.NET Core Identity as a Razor Class Library. The
Identity Razor Class Library exposes endpoints with the Identity area. For example:

/Identity/Account/Login
/Identity/Account/Logout
/Identity/Account/Manage
Install required packages listed below.
Microsoft.AspNetCore.Identity.EntityFrameworkCore
Microsoft.EntityFrameworkCore
Microsoft.EntityFrameworkCore.SqlServer
Microsoft.EntityFrameworkCore.Tools

Configure Connection inside appsettings.json file


"ConnectionStrings": {
"default": "Data Source=?????;Initial Catalog=DemoStore;Integrated
Security=True;TrustServerCertificate=True;"
}
Apply migrations
Apply the migrations to initialize the database.
Run the following command in the Package Manager Console (PMC):

PM> Update-Database

Test Register and Login


Run the app and register a user. Depending on your screen
size, you might need to select the navigation toggle button
to see the Register and Login links.

View the Identity database


From the View menu, select SQL Server Object Explorer
(SSOX).
Navigate to (localdb)MSSQLLocalDB(SQL Server 14).
Right-click on dbo.AspNetUsers > View Data:
Identity service configurations
Services are added in ConfigureServices method in the startup class. The typical
pattern is to call all the Add{Service} methods, and then call all the services.Configure{Service}
methods.

public void ConfigureServices(IServiceCollection services)


{
services.AddDbContext<DemoAppDbContext>(options =>
{
options
.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"),
assembly =>
assembly.MigrationsAssembly
(typeof(DemoAppDbContext).Assembly.FullName));
});

services.AddDefaultIdentity<IdentityUser>(options => options.SignIn.RequireConfirmedAccount = true)


.AddEntityFrameworkStores<DemoAppDbContext>();
}
Identity is enabled by calling UseAuthentication. UseAuthentication adds authentication
middleware to the request pipeline.

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)


{
.....
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();

app.UseEndpoints(endpoints =>
{
endpoints.MapRazorPages();
});
}
The template-generated app doesn't use authorization. app.UseAuthorization is included to
ensure it's added in the correct order should the app add authorization. UseRouting,
UseAuthentication, UseAuthorization, and UseEndpoints must be called in the order shown in
the preceding code.
Authorization

The ASP.NET Core framework


has authorization built in, so
you can use it anywhere in your
app, but it’s most common to
apply authorization as part of
MVC. For both traditional web
apps and web APIs, users
execute actions on your
controllers. Authorization occurs
before these actions execute, as
shown in figure, This lets you
use different authorization
requirements for different
action methods.
Authorization occurs as part of MvcMiddleware, after AuthenticationMiddeware has
authenticated the request.Authorization occurs as part of the MVC filter pipeline, in
the authorization filters.
When you think about authorization, you typically think about checking whether a particular user has
permission to execute an action. In ASP.NET Core, you’d achieve this by checking whether a user has
a particular claim.
To achieve basic level of authorization by using the [Authorize] attribute, You can apply this attribute
to your actions, as shown in the following listing, to restrict them to authenticated (logged-in) users
only. If an unauthenticated user tries to execute an action protected with the [Authorize] attribute in
this way, they’ll be redirected to the login page.

public class HomeController : Controller


{
public IActionResult Index()
{
return View();
}

[Authorize]
public IActionResult AuthedUsersOnly()
{
return View();
}
}
Authorization: Roles, Claims and Policies
When an identity is created it may belong to one or more roles. For
example, Tracy may belong to the Administrator and User roles whilst
Scott may only belong to the User role. How these roles are created and
managed depends on the backing store of the authorization process. Roles
are exposed to the developer through the IsInRole method on the
ClaimsPrincipal class.
Role
Role-based authorization checks are declarative—the developer embeds them within their code,
against a controller or an action within a controller, specifying roles which the current user
must be a member of to access the requested resource.

For example, the following code limits access to any actions on the
AdministrationController to users who are a member of the Administrator role:

[Authorize(Roles = "Administrator")]
public class AdministrationController : Controller
{
}
You can specify multiple roles as a comma separated list:

[Authorize(Roles = "HRManager,Finance")]
public class SalaryController : Controller
{
}
This controller would be only accessible by users who are members of the HRManager role or the
Finance role.
If you apply multiple attributes then an accessing user must be a member of all the roles
specified; the following sample requires that a user must be a member of both the Employee
and Teacher role.

[Authorize(Roles = “Employee")]
[Authorize(Roles = “Teacher")]
public class ReportController : Controller
{
}
You can further limit access by applying additional role authorization attributes at the action level
[Authorize(Roles = "Parent, Teacher")]
public class ProgressReportController : Controller
{
public ActionResult View()
{
}
[Authorize(Roles = "Teacher")]
public ActionResult Download()
{
}
}
In the previous code snippet members of the Parent role or the Teacher role can access
the controller and the view action, but only members of the Teacher role can access
the download action.

You can also lock down a controller but allow anonymous, unauthenticated access to
individual actions.
[Authorize]
public class TimeTableController : Controller
{
[AllowAnonymous]
public ActionResult View()
{
}
[Authorize(Roles = "Teacher")]
public ActionResult Download()
{
}
}

You might also like