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.
[Link] Core Identity
[Link] 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 [Link] can configure [Link] 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.
[Link] 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 [Link] Core Web Application project with Individual User Accounts.
• Select File > New > Project.
• Select [Link] Core Web Application. Name the project DemoApp to have the
same namespace as the project download. Click OK.
• Select an [Link] Core Web Application, then select Change Authentication.
• Select Individual User Accounts and click OK.
The generated project provides [Link] 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.
[Link]
[Link]
[Link]
[Link]
Configure Connection inside [Link] 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 [Link] > 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 [Link]{Service}
methods.
public void ConfigureServices(IServiceCollection services)
{
[Link]<DemoAppDbContext>(options =>
{
options
.UseSqlServer([Link]("DefaultConnection"),
assembly =>
[Link]
(typeof(DemoAppDbContext).[Link]));
});
[Link]<IdentityUser>(options => [Link] = true)
.AddEntityFrameworkStores<DemoAppDbContext>();
}
Identity is enabled by calling UseAuthentication. UseAuthentication adds authentication
middleware to the request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
.....
[Link]();
[Link]();
[Link]();
[Link]();
[Link]();
[Link](endpoints =>
{
[Link]();
});
}
The template-generated app doesn't use authorization. [Link] 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 [Link] 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 [Link] 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 [Link] 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()
{
}
}