Understanding the Different Methods of Authentication and Authorization

Shiva Rad
21 min readApr 30, 2023

--

Authentication and authorization play a crucial role in any project that requires secure access control. However, these terms are often mistakenly used interchangeably. Additionally, many methods have been introduced for implementing them, which can lead to confusion and frustration among developers trying to implement them correctly.

If you’re one of the developers struggling to understand the differences between authentication and authorization and the various implementation methods, don’t worry — you’re not alone. In this article, we will clarify the distinctions between AuthN and AuthZ and provide you with the knowledge you need to know about their different methods.

Authentication:

Authentication (AuthN) is a crucial process to confirm that someone or something is who or what they claim to be. Identity authentication is the process of verifying the identity of a user or service. Authentication processes typically use one of three methods to verify an individual’s identity:

something the user knows (such as passwords and security questions), something the user has (such as physical devices like USB security tokens or mobile phones), something the user is (such as biometric authentication or certification-based authentication).

Authorization:

Authorization is a security process that determines the level of access granted to a user or service. It is used in technology to give permission for accessing data or performing a specific action. Authentication and authorization both rely on identity.

Authentication verifies the identity before granting access, while authorization uses the verified identity to control access.

There are several types of authorization mechanisms.

1. Role-based authorization: grants access to resources based on the role or position of the user within an organization. For example, an employee with the role of manager may have access to certain resources and data that are not available to other employees.

2. Attribute-based authorization: grants access to resources based on a set of attributes associated with the user or resource. For example, access to a file may be granted only to users who have a specific security clearance level or who are members of a particular department.

3. Rule-based authorization: grants access to resources based on a set of predefined rules. For example, a rule may specify that only users who are currently logged in during business hours can access a particular resource.

4. Context-based authorization: grants access to resources based on the context in which the request is made. For example, access to a resource may be granted only if the request is made from a specific location or device.

AuthN methods:

Now that we have clarified the differences between authorization and authentication, let’s delve into various methods of authentication. Some commonly used authentication strategies include:

Basic Authentication

Basic Authentication is a simple method of authentication where the user provides their username and password in the HTTP header of each request. The server verifies the credentials and grants access if they are valid. This HTTP-based approach uses a Base64 format to encode usernames and passwords, which are stored in the HTTP header. However, sensitive credentials can travel between systems unencrypted, making it necessary to use Secure Sockets Layer (SSL) and Transport Layer Security (TLS) channels when sharing data between multiple web applications.

With Basic Authentication, login credentials are sent in the request headers with each request. Usernames and passwords are concatenated together using a : symbol to form a single string, which is then encoded using base64. This method is stateless and suitable for API calls along with simple auth workflows that do not require persistent sessions.

Pros:

Faster authentication due to fewer operations involved.

Easy to implement.

Supported by all major browsers.

Cons:

Base64 is not the same as encryption and can be easily decoded since it’s sent in plain text. HTTPS/SSL is essential.

Credentials must be sent with every request.

Users can only be logged out by rewriting the credentials with an invalid one.

Here’s how Basic Authentication works:

USER -> SERVER: GET /protected-resource
USER <- SERVER: 401 Unauthorized, WWW-Authenticate: Basic realm="Restricted Area"
USER -> SERVER: GET /protected-resource, Authorization: Basic base64(username:password)
USER <- SERVER: 200 OK
USER -> SERVER: GET /other-resource
USER <- SERVER: 401 Unauthorized, WWW-Authenticate: Basic realm="Restricted Area"
USER -> SERVER: GET /other-resource, Authorization: Basic base64(username:password)
USER <- SERVER: 200 OK

In the diagram, the user requests a protected resource from the server (“/protected-resource”).

The server responds with a 401 Unauthorized status code and a WWW-Authenticate header that indicates the use of Basic Authentication.

The user sends a second request for the same resource, including an Authorization header with their base64-encoded username and password.

The server verifies the credentials and grants access to the protected resource with a 200 OK status code.

If the user requests a different protected resource (“/other-resource”), the server will respond with a 401 Unauthorized status code and a WWW-Authenticate header, and the user must include the Authorization header with their credentials for each protected resource they request.

Note that this is a simplified example, and the actual flow of Basic Authentication can vary depending on the implementation and additional security measures employed such as HTTPS.

Session-Based Authentication

Session-based authentication is introduced to address the problem of HTTP protocol being stateless, which requires the user to authenticate themselves repeatedly for each new request. In session-based authentication, the server generates a unique token upon successful authentication and sends it to the client, which stores it in a cookie and sends it back with each subsequent request. The server uses this token to authenticate the user and returns the requested data. Logging out involves deleting the session ID stored in the cookie.

Pros:

Simple implementation: Session-based authentication is relatively simple to implement and does not require complex cryptographic operations.

Scalability: Sessions can be scaled horizontally across multiple servers in a load-balanced environment, making it easy to handle large numbers of simultaneous users.

Security: By using a session ID stored in a cookie, session-based authentication can protect against cross-site request forgery (CSRF) attacks, which occur when an attacker sends unauthorized requests to a website on behalf of an authenticated user.

Logout functionality: Session-based authentication makes it easy to implement a logout functionality as it only requires deleting the session ID stored in the cookie.

Cons:

Session fixation attacks: Session fixation attacks occur when an attacker sets the session ID before the user logs in, thereby allowing the attacker to hijack the user’s session.

Session hijacking attacks: Session hijacking attacks occur when an attacker steals the user’s session ID and uses it to gain unauthorized access to the user’s account. To mitigate this risk, developers should use secure cookies and implement measures to prevent session hijacking, such as IP tracking and reauthentication after a certain period of inactivity.

Session management: Managing user sessions can be a challenge, especially when the server is required to maintain a session store to keep track of authenticated users.

Stateful servers: Session-based authentication requires servers to be stateful, which means that they need to store session information on the server-side. This can be a performance bottleneck for high-traffic applications.

Mobile applications: Session-based authentication can be challenging to implement in mobile applications, where cookies are not always supported, and it is difficult to prevent unauthorized access to session information stored on the device.

Session-based authentication has scalability limitations, especially with regards to session management as sessions are usually stored in memory. When servers are replicated to multiple instances, all user sessions must also be replicated to each server, making it challenging to handle a large number of concurrent users. To overcome this issue, developers often use specialized session management tools or third-party services to centralize session management and distribute session data across multiple servers. Distributed caching technologies such as Redis or Memcached can also be used to store session data in a centralized cache accessible by multiple servers, reducing the need for replication and simplifying session management. However, having a dedicated server for session management may not always be feasible for small to mid-sized applications. In such cases, developers should consider other authentication methods that better suit their needs. Therefore, developers should carefully evaluate the scalability requirements of their application and choose an appropriate authentication method accordingly.

Here’s the diagram:

USER -> SERVER: GET /
USER <- SERVER: 200 OK, HTML form for login
USER -> SERVER: POST /login, username=john, password=secret
USER <- SERVER: 302 Found, Set-Cookie: session_id=abc123, Location: /dashboard
USER -> SERVER: GET /dashboard, Cookie: session_id=abc123
USER <- SERVER: 200 OK, HTML page with user's dashboard
USER -> SERVER: GET /settings, Cookie: session_id=abc123
USER <- SERVER: 200 OK, HTML page with user's settings
USER -> SERVER: POST /settings, Cookie: session_id=abc123, new_email=john@example.com
USER <- SERVER: 200 OK, HTML page with updated user's settings
USER -> SERVER: POST /logout, Cookie: session_id=abc123
USER <- SERVER: 302 Found, Set-Cookie: session_id=; expires=Thu, 01-Jan-1970 00:00:01 GMT, Location: /
USER -> SERVER: GET /
USER <- SERVER: 200 OK, HTML form for login

In this updated diagram, the user starts by sending a GET request to the server for the root URL (“/”). The server responds with an HTML form for login.

The user then sends a POST request to the server with their login credentials, and the server responds with a redirect to the user’s dashboard page, along with a session ID in a cookie.

The user sends subsequent requests for protected resources (“/dashboard” and “/settings”) with the session ID in the cookie. The server verifies the session ID and grants access to the requested resources.

When the user updates their settings, they send a POST request to the server with the updated data, and the server responds with a confirmation message.

Finally, when the user logs out, they send a POST request to the server, and the server responds with a redirect to the login page, along with a request to delete the session ID from the cookie.

Token-Based Authentication

Token-based authentication is a popular method, particularly with the emergence of single-page applications, web APIs, and IoT devices. This authentication method is stateless, meaning that no user information needs to be stored on the server-side. Instead of usernames and passwords, tokens are used for authentication. When a user provides their credentials, the server generates a token which can be exchanged between the client and server to authenticate the user. Tokens contain a unique identifier for the user and an expiration date/time. They do not need to be saved on the server-side as they can be validated using their signature, making requests faster without the need for database lookups.

Token-based authentication works well for microservices architecture, where multiple services require authentication. It’s easy to configure how each service handles the token and token secret. Despite its benefits, there are some downsides to token-based authentication. Storing the token on the client-side can lead to XSS attacks via localStorage or CSRF attacks via cookies. Tokens cannot be deleted, only expired. If leaked, an attacker can misuse the token until it expires. To mitigate these risks, it’s important to set short expiry times and use refresh tokens that automatically issue new tokens at expiry. A blacklisting database can also be created to delete tokens, but this adds extra overhead and introduces state to the microservice architecture.

JSON Web Tokens (JWT) are the most commonly used tokens for this mechanism because of their versatility and ease of use. Other examples of token-based authentication include SWT (Simple Web Tokens), OAuth, SAML, and OpenID.

Overall, token-based authentication offers improved security, scalability, and flexibility over traditional authentication methods. However, it’s essential to consider the potential risks and implement proper measures to avoid security breaches.JWT Authentication.

Here are two diagrams of token based auth, the second one includes refresh tokens:

USER -> SERVER: GET /protected-resource
USER <- SERVER: 401 Unauthorized, WWW-Authenticate: Bearer realm="Restricted Area"
USER -> SERVER: POST /login, username=john, password=secret
USER <- SERVER: 200 OK, { "access_token": "abc123" }
USER -> SERVER: GET /protected-resource, Authorization: Bearer abc123
USER <- SERVER: 200 OK
USER -> SERVER: GET /other-resource
USER <- SERVER: 401 Unauthorized, WWW-Authenticate: Bearer realm="Restricted Area"
USER -> SERVER: GET /other-resource, Authorization: Bearer abc123
USER <- SERVER: 200 OK

In this diagram, the user sends a request to the server for a protected resource (“/protected-resource”). The server responds with a 401 Unauthorized status code and a WWW-Authenticate header that indicates the use of bearer token authentication.

The user then sends a POST request to the server to authenticate with their username and password. The server responds with a 200 OK status code and an access token.

The user includes the access token in the Authorization header of subsequent requests to protected resources (“/protected-resource” and “/other-resource”). The server verifies the token and grants access to the requested resources.

If the user requests a different protected resource (“/other-resource”), the server will again respond with a 401 Unauthorized status code and a WWW-Authenticate header. The user must include the access token in the Authorization header for each protected resource they request.

Note that this is a simplified example, and the actual flow of token-based authentication can vary depending on the specific implementation and the use of additional security measures such as token expiration and refresh.

USER -> SERVER: GET /protected-resource
USER <- SERVER: 401 Unauthorized, WWW-Authenticate: Bearer realm="Restricted Area"
USER -> SERVER: POST /login, username=john, password=secret
USER <- SERVER: 200 OK, { "access_token": "abc123", "expires_in": 3600, "refresh_token": "def456" }
USER -> SERVER: GET /protected-resource, Authorization: Bearer abc123
USER <- SERVER: 200 OK
… user interacts with protected resource …
USER -> SERVER: GET /other-resource
USER <- SERVER: 401 Unauthorized, WWW-Authenticate: Bearer realm="Restricted Area"
USER -> SERVER: POST /token, grant_type=refresh_token, refresh_token=def456
USER <- SERVER: 200 OK, { "access_token": "ghi789", "expires_in": 3600, "refresh_token": "jkl012" }
USER -> SERVER: GET /other-resource, Authorization: Bearer ghi789
USER <- SERVER: 200 OK

In this diagram, after the user successfully logs in and receives an access token, the server also returns an expiration time and a refresh token.

The user interacts with the protected resource for a period of time, until the access token expires. When the user requests a new resource (“/other-resource”), the server responds with a 401 Unauthorized status code and a WWW-Authenticate header.

The user then sends a POST request to the server with the refresh token, and the server responds with a new access token and a new refresh token. The user can use the new access token to access the protected resource (“/other-resource”), and the new refresh token can be used in the future to obtain a new access token.

Note that this is just one possible implementation of token expiration and refresh, and different systems may use different methods or parameters.

SWT and JWT

Simple Web Tokens (SWT) and JSON Web Tokens (JWT) are two token-based authentication protocols used to securely exchange information between web applications and services. SWT is specifically designed for lightweight, web-based scenarios and does not support payload encryption or digital signatures like JWT does. The format of an SWT token consists of three parts: a header, a payload, and a signature. The header contains metadata about the token, the payload includes claims about the authenticated user or client, and the signature is a cryptographic hash signed with a shared secret or asymmetric key.

There are some key differences between SWT and JWT:

  1. Token Format: SWT and JWT have different token formats. SWT tokens are a simple key-value pair format with three parts: header, payload, and signature. JWT tokens are a JSON format with three parts: header, payload, and signature.
  2. Payload Encryption: SWT does not support payload encryption, while JWT can encrypt the payload using JSON Web Encryption (JWE). This allows JWT to provide an extra layer of security for sensitive information in the token payload.
  3. Signature: SWT and JWT use different algorithms to generate the signature. SWT uses the HMAC algorithm, which requires a shared secret between the token issuer and the recipient. JWT supports both HMAC and asymmetric key algorithms, such as RSA or ECDSA.
  4. Standardization: JWT is a standardized protocol, with a defined set of rules for token format, claims, and algorithms. SWT, on the other hand, is not a standardized protocol and has limited support compared to JWT.
  5. Use Cases: SWT was designed specifically for use in web-based scenarios, such as web services and APIs, while JWT has broader applications beyond web-based use cases.

SWT can be useful in scenarios where a lightweight and simple token format is sufficient for authentication and authorization, and where payload encryption is not required. An example of such a scenario is a company that provides a web API allowing third-party developers to access its services. The API uses SWT as the token format for authentication. When a user or client requests access to the API, the API issues an SWT token containing information about the user or client, such as their identity, authorization level, and access rights. The user or client then includes the SWT token in each subsequent request to the API, allowing the API to verify the token signature and authenticate the user or client. The API can use the claims in the token payload to authorize the user or client to access the requested services.

Overall, SWT is a lightweight, simple token format useful in specific web-based scenarios where payload encryption is not required. JWT provides more flexibility and security features, making it a more versatile choice for a wide range of use cases. SWT can be used in combination with other web authentication protocols, such as OAuth, to provide a secure and efficient way to transmit user and client credentials between services.

You can see the difference between SWT and JWT tokens structure in following picture:

The diagram for an SWT (first one) token consists of three parts: HMAC, Payload, and Signature. The HMAC is a hash-based message authentication code that is used to verify the integrity of the message. It is calculated by applying a secret key and a cryptographic hash function to the Payload. The Payload contains the claims about the authenticated user or client, such as their identity, authorization level, and access rights. Finally, the Signature is a cryptographic hash of the HMAC and Payload, signed with a shared secret or asymmetric key. The result is a compact, JSON-based token format that provides a simple way to exchange claims between parties.

The diagram for a JWT(second one) token also consists of three parts: Header, Payload, and Signature. The Header contains metadata about the token, such as the algorithm used to sign it. It is a Base64 URL encoded JSON object. The Payload contains the claims about the subject of the token, such as their identity, authorization level, and access rights. It is also a Base64 URL encoded JSON object. Finally, the Signature is a Base64 URL signature using a secret or public key. It is used to verify the authenticity of the message and ensure its integrity.

SSO (Single Sign-On)

Single sign-on (SSO) is a modern technology that enables users to access multiple applications or systems by logging in with a single set of credentials. With SSO, users are not required to enter their username and password for each application they use. Instead, they can sign in once and automatically access all authorized applications without having to re-enter their credentials. This reduces the need for remembering multiple usernames and passwords, enhancing user experience and efficiency when working with multiple applications.

An SSO process flow example involves the following steps:

1. The user accesses the first Google product and receives a Google Accounts-generated cookie.

2. When the user navigates to another Google product, they are redirected to Google Accounts.

3. Google Accounts sees that the user already has an authentication-related cookie, so it redirects them to the requested product.

Simply put, SSO can be described as “user logs in once and gains access to all systems without being prompted to log in again at each of them”. This relies on three different entities who trust each other directly and indirectly — the user, identity provider (IdP), and service provider (SP).

To gain access to an SP, a user enters a password (or some other authentication method) to their IdP. The user trusts the IdP, while the SP trusts the IdP. Therefore, the SP can also trust the user.

There are several methods of implementing SSO, including:

1. Federated SSO: In this method, a trusted third party called an identity provider (IdP) is used to authenticate users and share their credentials with the applications or services that they need to access. The IdP acts as a broker between the user and the applications, and the user only needs to sign in to the IdP once to access all the applications that they are authorized to use. A common example of federated SSO is when you log in to a third-party application or service using your Google, Facebook, or Microsoft account. In this case, the third-party application is the service provider, and Google, Facebook, or Microsoft acts as the identity provider, sharing your authentication data with the service provider.

2. Enterprise SSO: This method is used within an organization to provide SSO functionality across different applications and services that are used within the organization. The user signs in to the SSO system once and is then able to access all the applications and services that they need to use. Many organizations use enterprise SSO solutions to provide their employees with seamless access to different applications and services. For example, an employee may log in to their organization’s SSO portal using their network credentials and then be automatically signed in to their email, intranet, HR portal, and other applications that they have access to.

3. Web SSO: This method is used for web-based applications and services. A user logs in to a central authentication server or portal, and from there, they can access any of the web-based applications or services that they are authorized to use. Web SSO is commonly used for accessing web-based applications and services. For example, when you log in to your online banking account, you may be redirected to a central authentication server or portal where you enter your credentials. Once authenticated, you are then able to access your account and any other related services without having to re-enter your credentials.

4. Kerberos SSO: Kerberos is a network authentication protocol that provides SSO functionality for networks of computers. In this method, users are authenticated once by the Kerberos server and can then access any of the services or applications within the network without having to re-enter their credentials. Kerberos is commonly used in large enterprise networks to provide SSO functionality for users. For example, a user may log in to their computer using their network credentials, and once authenticated, they are automatically granted access to all the applications and services that they are authorized to use within the network.

5. Mobile SSO: This method is used for mobile applications and services. Users sign in once and are then able to access all authorized mobile applications without having to re-enter their credentials. Mobile SSO is commonly used in mobile applications, such as social media apps or banking apps. For example, you may log in to your banking app using your fingerprint or facial recognition, and once authenticated, you are able to access your account information and complete transactions without having to enter your credentials again.

SAML
SAML (Security Assertion Markup Language) is a widely-used standard for implementing federated SSO. It is an XML-based framework for exchanging authentication and authorization data between an identity provider (IdP) and a service provider (SP). In the SAML framework, the user initiates the authentication process by attempting to access a protected resource on the service provider’s website. The service provider then redirects the user to the identity provider, where the user is prompted to enter their credentials. Once the identity provider authenticates the user, it generates a SAML response containing an assertion that contains information about the user’s identity and permissions. This assertion is then sent back to the service provider, which uses it to grant the user access to the requested resource.

SAML supports different types of assertions, including authentication, attribute, and authorization assertions, allowing for fine-grained control over access to resources. It is widely used for implementing SSO in enterprise environments and is supported by many popular identity and access management solutions.

OAUTH

OAuth (Open Authorization) is a protocol that allows users to grant third-party applications access to their resources without sharing their credentials such as username and password. It provides users with a secure way to authorize applications to access their resources on their behalf. OAuth is widely used in web and mobile applications to provide access to APIs, social media platforms, and other web-based services.

Here’s how it works:

1. A user attempts to access a protected resource on a service provider’s website or app using a third-party application, initiating the OAuth process.

2. The third-party application requests authorization from the user to access specific resources such as profile data, email address, or photos on their behalf.

3. If the user agrees, the third-party application receives an authorization grant, which represents the user’s permission to access the requested resources.

4. The third-party application uses the authorization grant to obtain an access token from the service provider’s authorization server.

5. The access token is then used by the third-party application to access the user’s resources on the service provider’s behalf.

A real-life example of OAuth in action is when a user wants to sign up for a new web application using their Google account. Here’s how the flow would work:

1. The user attempts to sign up for the new application using their Google account credentials through the client (the new application).

2. The client redirects the user to Google’s authorization endpoint to obtain permission for accessing the user’s Google account data.

3. The user authenticates with Google and grants permission for the client to access their profile data.

4. The client requests an access token from Google’s authorization server using the authorization grant obtained from the previous step.

5. Google issues an access token and refresh token to the client, which can be used to access the user’s Google account data on behalf of the user.

With this access token, the client can then access the user’s Google account data, such as their name, email address, or contacts, without having to store or share the user’s Google account credentials. This makes it more secure and convenient for users who want to use their existing accounts to sign up for new applications.

OAuth has gone through several versions, each with different features and improvements. OAuth 1.0 was the first version released in 2007, which uses a signature-based authentication mechanism that requires the client to sign each request with a shared secret key. OAuth 1.0a was released in 2009, which addressed some security issues and added new features, such as support for mobile devices. OAuth 2.0 is the current version and was released in 2012. It has a simpler and more flexible architecture compared to previous versions, allowing developers to use new authorization flows, such as implicit and client credentials flows. However, OAuth 2.0 has been criticized for being less secure than OAuth 1.0, as it allows for the use of bearer tokens, which can be stolen and used to access user data.

OAuth 2.1 is the latest version of the OAuth 2.0 specification, which was released in September 2021. It is a refinement of the OAuth 2.0 protocol and aims to improve the security, privacy, and usability of OAuth 2.0. Some key changes in OAuth 2.1 include more prescriptive security guidance for implementers, elimination of insecure practices, stronger client authentication methods, and improved user consent.

Some popular apps that use OAuth include Twitter (OAuth 1.0a), Facebook, Google, LinkedIn, and Microsoft (OAuth 2.0).

Open-ID

OpenID is an open standard that allows users to authenticate themselves to different web applications and services using their existing online identities. OpenID enables users to log in to an application using their preferred online identity, such as their Google, Facebook, or Twitter account, rather than creating a new account specifically for the application.

Let’s say you want to sign in to an online marketplace using your Facebook account. The marketplace can use OpenID to authenticate you and retrieve your basic profile information from Facebook, such as your name and profile picture.

Here’s how it works:

1. You click the “Sign in with Facebook” button on the marketplace’s login page.

2. The marketplace redirects you to Facebook’s authentication server, where you are prompted to log in to your Facebook account.

3. If you successfully log in, Facebook generates an ID token and sends it back to the marketplace.

4. The marketplace can then use the ID token to authenticate you and retrieve your basic profile information, such as your name and profile picture, on your behalf.

OpenID is built on top of OAuth2.0, which provides the authorization framework for accessing protected resources. OpenID Connect is the latest version of OpenID, which provides additional authentication features and improvements over the original protocol.

In summary OAUTH2.0 is an authorization framework, while Open ID is mainly used for authentication.

OAuth enables third-party clients to access protected resources (eg. Facebook or Google contacts) with the resource owner’s consent through the use of access tokens issued by an authorization server (Facebook or Google Auth server). OpenID, on the other hand, allows users to use their login credentials from an OpenID provider (eg. Google) to log in to another application through the use of an ID token.

MFA and 2FA
MFA (Multi-Factor Authentication) and 2FA (Two-Factor Authentication) are security measures that require users to provide multiple forms of authentication in order to access an account or system. Both MFA and 2FA add an extra layer of security beyond just a username and password, which can be easily compromised.

MFA typically requires the user to provide at least two different types of authentication factors from three categories:

something the user knows (such as a password), something the user has (such as a mobile phone or token generator), something the user is (such as a fingerprint or facial recognition).

2FA is a type of MFA that requires the user to provide two different types of authentication factors from two categories. Typically, this involves something the user knows (such as a password) and something the user has (such as a mobile phone or token generator).

Here’s how 2FA typically works:

1. The user enters their username and password to log in to an account.

2. The system then prompts the user to enter a second authentication factor such as a code generated by a mobile app or sent via SMS.

3. The user enters the code to complete the login process.

The advantage of 2FA is that even if someone else obtains or guesses the user’s password, they would still need to have access to the second authentication factor in order to gain access to the account.

--

--

No responses yet