Authentication and Authorization
Authentication and Authorization
Authentication and Authorization
and
Authorization
N I TA L S H A H
Authentication and Authorization
While authentication and authorization are often used interchangeably, they are
separate processes used to protect an organization from cyber-attacks.
As data breaches continue to escalate in both frequency and scope, authentication and
authorization are the first line of defense to prevent confidential data from falling into
the wrong hands.
2
What is Authentication and
Authorization ?
Authentication is the process of validating user credentials and authorization is the process of
checking privileges for a user to access specific modules in an application.
The <authorization> element allows you to configure the user accounts that can access your
site or application. Use authorization in combination with authentication to secure access to
content on your server. Authentication confirms the identity of a user, while authorization
determines what resources users can or cannot access.
Token-based security is commonly used in today’s security architecture. There are several
token-based security techniques.
JWT is one of the more popular techniques. JWT token is used to identify authorized users.
3
Authentication Vs Authorization
So, what is the difference between authentication and authorization? Simply put, authentication is
the process of verifying who someone is, whereas authorization is the process of verifying what
specific applications, files, and data a user has access to. The situation is like that of an airline
that needs to determine which people can come on board. The first step is to confirm the identity
of a passenger to make sure they are who they say they are. Once a passenger’s identity has been
determined, the second step is verifying any special services the passenger has access to,
whether it’s flying first-class economy.
In the digital world, authentication and authorization accomplish these same goals. Authentication
is used to verify that users really are who they represent themselves to be. Once this has been
confirmed, authorization is then used to grant the user permission to access different levels of
information and perform specific functions, depending on the rules established for different types
of users.
4
Common Authentication Methods
While user identity has historically been validated using the combination of a username and password,
today’s authentication methods commonly rely upon three classes of information:
What you know: Most commonly, this is a password. But it can also be an answer to a security question
or a one-time pin that grants user access to just one session or transaction.
What you possess: This could be a mobile device or app, a security token, or digital ID card.
What you are: This is biometric data such as a fingerprint, retinal scan, or facial recognition.
Oftentimes, these types of information are combined using multiple layers of authentication. For
example, a user may be asked to provide a username and password to complete an online purchase.
Once that’s confirmed, a one-time pin may be sent to the user’s mobile phone as a second layer of
security. Combining multiple authentication methods with consistent authentication protocols,
organizations can ensure security as well as compatibility between systems.
5
Common Authorization Methods
Once a user is authenticated, authorization controls are then applied to ensure users can access
the data they need and perform specific functions such as adding or deleting information—based
on the permissions granted by the organization. These permissions can be assigned at the
application, operating system, or infrastructure levels. Two common authorization techniques
include:
Role-based access controls (RBAC): This authorization method gives users access to information
based on their role within the organization. For example, all employees within a company may be
able to view, but not modify, their personal information such as pay, vacation time, and 401K
data. Yet HR managers may be given access to all employees’ HR information with the ability to
add, delete, and change this data. By assigning permissions according to each person’s role,
organizations can ensure every user is productive, while limiting access to sensitive information.
6
Common Authorization Methods ..
Attribute-based access control (ABAC): ABAC grants users permissions on a more granular level
than RBAC using a series of specific attributes.
This may include user attributes such as the user’s name, role, organization, ID, and security
clearance. It may include environmental attributes such as the time of access, location of the
data, and current organizational threat levels. And it may include resource attributes such as the
resource owner, file name, and level of data sensitivity. ABAC is a more complex authorization
process than RBAC designed to further limit access.
For example, rather than allowing all HR managers in an organization to change employees’ HR
data, access can be limited to certain geographical locations or hours of the day to maintain tight
security limits.
7
If you try to access a non-secure page :
You will be presented with an error page, with an HTTP 401
Unauthorized error.
8
OAuth Authentication For Web API
Authentication means verifying the user who is accessing the system. We have available different types
of authentication in .NET programming like Windows Authentication, Forms Authentication, Claim Based
Authentication, Token-Based Authentication, etc.
Token-based Authentication
In token-based authentication, you pass your credentials [user name and password], to the server,
which verifies your credentials and if it is a valid user, then it will return a signed token to the client
system, which has an expiration time. The client can store this token locally using any mechanism like
local storage, session storage, etc. and if the client makes any other call to the server for data, then it
does not need to pass its credentials every time. The client can directly pass the token to the server,
which will be validated by the server and if the token is valid, then you will able to access your data.
9
OAuth
(Open Authorization) is an open standard for token-based authentication and authorization on the
Internet.
OAuth versions : There are two versions of OAuth authorization OAuth 1 (using HMAC-SHA
signature strings) and OAuth 2 (using tokens over HTTPS).
OAuth Tokens : There are two types of tokens involved in OAuth 2, Access Token and Refresh
Token.
The access token is used to for authentication and authorization to get access to the resources
from the resource server. The refresh token normally is sent together with the access token.
The refresh token is used to get a new access token when the old one expires. Instead of the
normal grant type, the client provides the refresh token and receives a new access token.
10
Token Types
Access tokens have a type, which defines how they are constructed.
Bearer Tokens
The bearer tokens use HTTPS security, and the request is not signed or encrypted. Possession of
the bearer token is considered authentication.
MAC Tokens
More secure than bearer tokens, MAC tokens are similar to signatures, in that they provide a way
to have (partial) cryptographic verification of the request.
11
JWT : JSON Web Token Authentication
JSON Web Token (JWT) is a popular user authentication standard, used to securely exchange
information online.
a header that specifies the algorithm used to encrypt the contents of the token; a payload that
contains “claims” (information the token securely transmits); and a signature that can be used to
verify the authenticity of the information.
A JWT is represented as a sequence of URL-safe parts separated by period (’.’) characters. Each
part contains a base64url-encoded value.
12
JWT Token
13
JWT Representation
JSON Web Tokens consist of three parts separated by dots (.), which are: xxxx.yyyy.zzzz
14
Access Secure Site Using JWT Tokens
Please refer to the link for more details about JSON Web
Tokens. https://jwt.io/introduction/
15
Linked Resources
▪ JSON Web Tokens - jwt.io - https://jwt.io
▪ RFC 7519 - JSON Web Token (JWT) - https://tools.ietf.org/html/rfc7519
▪ JSON Web Token Introduction - jwt.io - https://jwt.io/introduction
▪ HMACSHA256 Class (System.Security.Cryptography) | Microsoft Docs -
https://docs.microsoft.com/en-us/dotnet/api/system...
▪ RSA (cryptosystem) - Wikipedia -
https://en.wikipedia.org/wiki/RSA_(cryptosystem)
16
Download Postman
Download Postman | Get Started for Free
We will use, Postman to test API. Postman is one of the most popular software testing tools
which is used for API testing, helps to build, test and modify APIs.
It has the ability to make various types of HTTP requests(GET, POST, PUT, DELETE).
17
Lifecycle of an API - POSTMAN
https://youtu.be/VxY_cz0VQXE
18
Linked Resources
•GET - HTTP | MDN - https://developer.mozilla.org/en-US/docs/Web/HTTP/...
•POST - HTTP | MDN - https://developer.mozilla.org/en-US/docs/Web/HTTP/...
•Introduction to Web | Servlet Tutorial | Studytonight - https://www.studytonight.com/servlet/introduction-...
•HTTP headers - HTTP | MDN - https://developer.mozilla.org/en-US/docs/Web/HTTP/...
19
API : Application Programming Interface
API is the acronym for Application Programming Interface, which is a software intermediate
that allows two applications to talk to each other.
An API is a software or middleman between two applications. In other words, they enable
different applications to communicate or connect with each other. Put simply, an API is a
messenger that relays your request to another application and then delivers their response back
to you.
20
HTTP Methods
API lets a developer make a specific “call” or “request” in order to send or receive information. This
communication is done using a programming language called “JSON.” It can also be used to make a
defined action such as updating or deleting data. There are four basic request methods that can be made
with API:
PUT – Updates
DELETE – (Deleting)
21
HTTP Status Codes
As a response, the HTTP GET Request returns the requested data from the server.
400 Bad Request - May occur if something failed in the request. For example, when the requested
resource does not exist.
401 Unauthorized - This occurs when the server has denied access to the requested resource.
Usually because of User Authentication or Policy.
200 : ok or success
22
ASP.NET Core Web API application
by implementing JWT authentication
Today, we will use SQL server database, to store user credentials .
Download SSMS : Download SQL Server Management Studio (SSMS) - SQL Server Management
Studio (SSMS) | Microsoft Docs (connect to server : (localdb)\MSSqlLocalDb)
We will use, Postman to test API. Postman is one of the most popular software testing tools
which is used for API testing, helps to build, test and modify APIs.
It has the ability to make various types of HTTP requests(GET, POST, PUT, DELETE).
23
JWT Authentication
And Authorization
24
Create ASP.NET Core Web API
choose ASP.NET Core Web API template from Visual Studio 2022.
25
Install 4 libraries
•use NuGet package manger to install the packages.
•Microsoft.EntityFrameworkCore.SqlServer
•Microsoft.EntityFrameworkCore.Tools
•Microsoft.AspNetCore.Identity.EntityFrameworkCore
•Microsoft.AspNetCore.Authentication.JwtBearer
26
appsettings.json
Change the appsettings.json with below values. It has database connection details and other
details for JWT authentication.
27
Create ApplicationDbContext.cs
Create a new folder “Auth” and create “ApplicationDbContext” class in Auth folder. We will add all
the classes related to authentication under the Auth folder.
28
Create UserRoles.cs in Models
folder
29
Create RegisterModel.cs
Create class “RegisterModel” for new user registration.
30
LoginModel.cs
Create class “LoginModel” for user login.
31
Response.cs
We will create a class “Response” for returning the response value after user registration and user
login. It will also return error messages if the request fails.
32
Create AuthenticateController
We can create an API controller “AuthenticateController” inside the “Controllers” folder and add
below code.
We will add three methods “login”, “register”, and “register-admin” inside the controller class.
Register and register-admin are almost same, but the register-admin method will be used to create
a user with admin role.
33
Program.cs
Find code in BB.
We must define all our dependency injection and other configurations inside the Program class.
34
create a database and tables
We must create a database and tables needed before running the application. As we are using
entity framework, we can use below database migration command with package manger console
to create a migration script.
“add-migration Initial”
35
update-database
Use the command below to create database and tables.
“update-database”
If you check the database using SQL server object explorer, you can see that the tables
below are created inside the database.
There are 7 tables created for User, Role and Claims during
the database migration process. This is due to the Microsoft
Identity framework.
36
Add “Authorize” attribute in WeatherForecast”
controller
We can add “Authorize” attribute inside the “WeatherForecast” controller.
37
Run the application
Now, We will run the application and try to access get method in weatherforecast controller from
Postman tool.
38
Register User
39
Now login
We have received a token
after successful login with the
above credentials.
40
Try admin register
41