Authentication & Authorization in ASP.Net Core - Part 1

This series is based on Raw coding, and it can be considered a written version of the video.

satish1v
.Net Programming
2 min readJan 18, 2021

--

Let’s start with an empty asp.net Core application with a Home controller and a couple of actions(Index, Secret). As the name suggests, I want to protect the remote endpoint, and a simple way to do the same is the [Authorize] attribute.

So if you run the application you will be able to bring both the Home view and Secret. So how do we stop the secret view?

Authorization

To make the authorized attribute work you need to add the relevant middleware and the magic happens in the Startup class.

app.UseAuthorization();

After adding the change and when you try to hit the endpoint (home/secret) you will see the following error.

This error states that you have asked for authorizing the endpoint without authentications. So the framework is expecting you to authenticate first before authorization.

Authentication

A simple way to understand the problem here is to understand the meaning of authentication vs Authorization

Authentication → Who you are

Authorization → What you can do

Since we have not defined a way to find who you are it's not able to find what you can do with the same.

So let's define authentication. This can be done by adding the

services.AddAuthentication()
.AddCookie(“cookieAuth”, config =>
{
config.Cookie.Name = “default”;
config.LoginPath = “/home/authenticate”;
});

The above line uses the cookie which comes in the request to validate the user and the cookie should be of name default.

Also if the user is not authenticated, Authenticate him using the Authenticate action in the Home controller.

Let's write the authentication logic

Here I have used Claim based authentication which provides the cookie. The main logic here revolves around the settings of the user details(user-principal) variable in the SignInAsync() method which allows the sign-in to happen.

More about claim-based Authentication will be in the next post.

Reference :

Next blog on series: https://satish1v.medium.com/authentication-in-asp-net-core-mental-model-e23ba1b34764

--

--