Tech Point Fundamentals

Friday, September 30, 2022

SQL Interview Questions and Answers - Part 19

SQL Interview Questions and Answers - Part 19

sql-interview-questions-answers

Are you preparing for the SQL Interview? If yes, then you are at the right place. This is the SQL Interview Questions and Answers article series. Here we will see the Top 100+ SQL Interview Questions with Answers. 

Please visit our YouTube Channel for Interviews and other videos by below link:




Please read the complete Design Pattern, C#, MVC, WebAPI, and .Net Framework Interview Questions and Answers article series here.




Introduction


This is the 19th part of the SQL Interview Questions and Answers article series. Each part contains eight to ten SQL Interview Questions with Answers. Please read all the SQL Interview Questions list here.

I will highly recommend to please read the previous parts over here before continuing the current part:





SQL Interview Questions and Answers - Part 19


Q171. What is LOCK in SQL? Why locking is important in SQL if it causes performance overheads? 

Locking is a mechanism used by the Database Engine to synchronize access by multiple users to the same piece of data at the same time. A lock is a way to ensure data consistency

SQL Server locks objects when the transaction starts. When the transaction is completed, SQL releases the locked object. This lock mode can be changed according to the SQL process type and isolation level

Each transaction requests locks of different types on the resources, such as rows, pages, or tables, on which the transaction is dependent. The locks block other transactions from modifying the resources in a way that would cause problems for the transaction requesting the lock. 

Locks are held on SQL Server resources, such as rows read or modified during a transaction, to prevent concurrent use of resources by different transactions.
Minimizing locks increases concurrency, which can improve performance

Before a transaction acquires a dependency on the current state of a piece of data, such as by reading or modifying the data, it must protect itself from the effects of another transaction modifying the same data. The transaction does this by requesting a lock on the piece of data. 



Lock vs RowVersioning:

Locking and row versioning prevent users from reading uncommitted data and prevent multiple users from attempting to change the same data at the same time. Without locking or row versioning, queries executed against that data could produce unexpected results by returning data that has not yet been committed in the database.

If a transaction requests a lock mode that conflicts with a lock that has already been granted on the same data, the instance of the Database Engine will pause the requesting transaction until the first lock is released.

When a transaction modifies a piece of data, it holds the lock protecting the modification until the end of the transaction. All locks held by a transaction are released when the transaction completes (either commits or rolls back).

Applications do not typically request locks directly. Locks are managed internally by a part of the Database Engine called the lock manager. The query processor determines what types of locks are required to protect each resource based on the type of access and the transaction isolation level setting. The query processor then requests the appropriate locks from the lock manager. 



Q172. What is the Locking Hierarchy in SQL? What are the different resources that can have a lock?

SQL Server has a lock hierarchy that acquires lock objects in this hierarchy. The lock hierarchy starts with the database at the highest hierarchy level and down via table and page to the row at the lowest level. 

Locks will always be acquired from the top to the bottom as in that way SQL Server is preventing a so-called Race Condition to occur. 

Database => Table => Page => Record Row



Essentially, there is always a shared lock on the database level that is imposed whenever a transaction is connected to a database. The shared lock on a database level is imposed to prevent the dropping of the database or restoring a database backup over the database in use.

For example, when a SELECT statement is issued to read some data, a shared lock (S) will be imposed on the database level, an intent shared lock (IS) will be imposed on the table and on the page level, and a shared lock (S) on the row itself

Similarly, in the case of a DML statement (insert, update, delete) a shared lock (S) will be imposed on the database level, an intent exclusive lock (IX) or intent update lock (IU) will be imposed on the table, and on the page level, and an exclusive or update lock (X or U) on the row



Resource Types: 

The SQL Server Database Engine has multi-granular locking that allows different types of resources to be locked by a transaction. Locking at a smaller granularity, such as rows, increases concurrency but has a higher overhead because more locks must be held if many rows are locked. 

Locking at a larger granularity, such as tables, are expensive in terms of concurrency because locking an entire table restricts access to any part of the table by other transactions. However, it has a lower overhead because fewer locks are being maintained.

The Database Engine often has to acquire locks at multiple levels of granularity to fully protect a resource. This group of locks at multiple levels of granularity is called a lock hierarchy. 



lock-resporce




Q173. What are the different types of lock modes in SQL?

The SQL Server Database Engine locks resources using different lock modes that determine how the resources can be accessed by concurrent transactions. 

  1. Shared Locks (S) Mode
  2. Exclusive Locks (X) Mode
  3. Update Locks (U) Mode
  4. Intent locks (I) Mode
  5. Schema Locks (Sch) Mode
  6. Bulk Update Locks (BU) Mode
  7. Key-Range Locks Mode



Q174. What is Shared Lock (S) in SQL?

Shared Locks(S):

It is used for data read operations that do not change or update data, such as a SELECT statement. This lock type occurs when the object needs to be read. 

When a shared lock is imposed, it reserves a page or row to be available only for reading, which means that any other transaction will be prevented to modify the locked record as long as the lock is active. In addition, a shared lock will allow write operations, but no DDL changes will be allowed.

Shared (S) locks allow concurrent transactions to read (SELECT) a resource under pessimistic concurrency control. No other transactions can modify the data while shared (S) locks exist on the resource. 

Shared (S) locks on a resource are released as soon as the read operation completes unless the transaction isolation level is set to repeatable read or higher, or a locking hint is used to retain the shared (S) locks for the duration of the transaction.

However, a shared lock can be imposed by several transactions at the same time over the same page or row, and in that way, several transactions can share the ability for data reading since the reading process itself will not affect anyhow the actual page or row data.



Q175. What is Exclusive Lock (X) in SQL?

Exclusive Locks (X):

When an exclusive lock is imposed, it will ensure that a page or row will be reserved exclusively for the transaction that imposed the exclusive lock, as long as the transaction holds the lock. When this lock type occurs, it occurs to prevent other transactions to modify or access a locked object.

The exclusive lock will be imposed by the transaction when it wants to modify the page or row data, which is in the case of DML statements DELETE, INSERT and UPDATE. If an exclusive (X) lock is held on a row within a table by a transaction, no other transaction can modify that row until the lock is released.



Exclusive (X) lock prevents access to a resource by concurrent transactions. With an exclusive lock, no other transactions can modify data at all. Read operations can take place only with the use of the NOLOCK hint or read uncommitted isolation level.

An exclusive lock can be imposed on a page or row only if there is no other shared or exclusive lock imposed already on the target. So only one exclusive lock can be imposed on a page or row, and once imposed no other lock can be imposed on locked resources.

Data modification statements, such as INSERT, UPDATE, and DELETE combine both modifications and read operations. The statement first performs read operations to acquire data before performing the required modification operations. Data modification statements, therefore, typically request both shared locks and exclusive locks. 



Q176. What is Update Lock (U) in SQL?

Update Locks (U):

An update lock can be imposed on a record that already has a shared lock. It is similar to an exclusive lock (X) but is designed to be more flexible in a way. 

An update operation happens basically in two different phases: read phase and write phase. During the read phase, SQL Server does not want other transactions to have access to this object to be changed. 

For this reason, SQL Server uses the update lock. Once the transaction that holds the Update Lock (U) is ready to change the data, the update lock (U) will be transformed into an exclusive lock (X).

It is important to understand that the update lock (U) is asymmetrical in regard to shared locks. While the update lock can be imposed on a record that has the shared lock, the shared lock cannot be imposed on the record that already has the update lock.

Update (U) locks prevent a common form of deadlock. Only one transaction can obtain an update (U) lock to a resource at a time. If a transaction modifies a resource, the update (U) lock is converted to an exclusive (X) lock.



Q177. What is Intent Lock (I) in SQL? What are the different types of Intent Lock?

Intent locks (I):

This lock is used by a transaction to inform another transaction about its intention to acquire a lock. The purpose of an intent lock (I) is to ensure data modification to be executed properly by preventing another transaction to acquire a lock on the next in the hierarchy object. 

Basically, when a transaction wants to acquire a lock on the row, it will acquire an intent lock on a table, which is a higher hierarchy object. By acquiring the intent lock, the transaction will not allow other transactions to acquire the exclusive lock on that table.

The Database Engine uses intent locks to protect placing a shared (S) lock or exclusive (X) lock on a resource lower in the lock hierarchy. 

Intent locks are named intent locks because they are acquired before a lock at the lower level, and therefore signal intent to place locks at a lower level.



Purpose/Use of Intent Lock:

An intent lock is an important lock type from the performance aspect. Intent locks improve performance because the Database Engine examines intent locks only at the table level to determine if a transaction can safely acquire a lock on that table. 

This removes the requirement to examine every row or page lock on the table to determine if a transaction can lock the entire table. Intent locks serve two purposes:

  • To prevent other transactions from modifying the higher-level resource in a way that would invalidate the lock at the lower level.
  • To improve the efficiency of the Database Engine in detecting lock conflicts at a higher level of granularity.

For example, a shared intent lock is requested at the table level before shared (S) locks are requested on pages or rows within that table. 

Setting an intent lock at the table level prevents another transaction from subsequently acquiring an exclusive (X) lock on the table containing that page. 



Types of Intent Locks:

There are basically two categories of Intent Locks i.e  regular intent locks and conversion locks:

1. Regular Intent Locks: There are three sub-types of the Regular Intent Locks in SQL.

Intent Exclusive Lock (IX):

When an intent exclusive lock (IX) is acquired it indicates to SQL Server that the transaction has the intention to modify some of the lower hierarchy resources by acquiring exclusive (X) locks individually on those lower hierarchy resources.

IX lock protects requested or acquired exclusive locks on some (but not all) resources lower in the hierarchy. It also protects requesting shared locks on lower-level resources.



Intent Shared Lock (IS):

When an intent shared lock (IS) is acquired it indicates to SQL Server that the transaction has the intention to read some lower hierarchy resources by acquiring shared locks (S) individually on those resources lower in the hierarchy.

IS lock protects requested or acquired shared locks on some (but not all) resources lower in the hierarchy.

Intent Update Lock (IU):

The intent update lock (IU) can be acquired only at the page level and as soon as the update operation takes place, it converts to the intent exclusive lock (IX)

IU lock protects requested or acquired update locks on all resources lower in the hierarchy. 
IU locks are used only on page resources. IU locks are converted to IX locks if an update operation takes place.



2. Conversion Intent Locks: There are three sub-types of the Conversion Intent Locks in SQL.

Shared with Intent Exclusive Lock (SIX):

A SIX lock is basically the combination of intent exclusive lock (IX) and exclusive lock (X). So once the transaction acquires a SIX lock on the table, it will acquire an intent exclusive lock (IX) on the modified pages and an exclusive lock (X) on the modified rows.

When the SIX lock is acquired, this lock indicates that the transaction intends to read all resources at a lower hierarchy and thus acquire the shared lock on all resources that are lower in the hierarchy, and in turn, to modify part of those, but not all. For doing so, it will acquire an intent exclusive (IX) lock on those lower hierarchy resources that should be modified. 

Only one shared with intent exclusive lock (SIX) can be acquired on a table at a time and it will block other transactions from making updates, but it will not prevent other transactions to read the lower hierarchy resources they can acquire the intent shared (IS) lock on the table.

A SIX lock protects requested or acquired shared locks on all resources lower in the hierarchy and intent exclusive locks on some (but not all) of the lower-level resources. Concurrent Intent Shared (IS) locks at the top-level resource are allowed. 



Shared with Intent Update Lock (SIU):

It is a combination of the shared (S) and intent update (IU) locks, as a result of acquiring these locks separately and simultaneously holding both locks. 

For example, a transaction executes a query with the PAGLOCK hint and then executes an update operation. The query with the PAGLOCK hint acquires the S lock, and the update operation acquires the IU lock.

Update with Intent Exclusive Lock (UIX):

It is a combination of U and IX locks, as a result of acquiring these locks separately and simultaneously holding both locks.

When update lock (U) and intent exclusive (IX) locks are acquired at lower hierarchy resources in the table simultaneously, the update with intent exclusive lock (UIX) will be acquired at the table level as a consequence.



Q178. What is Schema Lock (Sch) in SQL?

Schema Locks (Sch):

The SQL Server database engine uses two types of schema locks: Schema Modification lock (Sch-M) and Schema Stability lock (Sch-S).

1. Schema Modification Lock (Sch-M):

The Database Engine uses schema modification (Sch-M) locks during a table data definition language (DDL) operation, such as adding a column or dropping a table.

In order to modify a table, a transaction must wait to acquire a Sch-M lock on the target object. Once it acquires the schema modification lock (Sch-M), the transaction can modify the object, and after the modification is completed and the lock will be released. 



During the time that it is held, the Sch-M lock prevents concurrent access to the table. This means the Sch-M lock blocks all outside operations until the lock is released.

ASch-M lock will be acquired when a DDL statement is executed, and it will prevent access to the locked object data as the structure of the object is being changed. 
SQL Server allows a single schema modification lock (Sch-M) lock on any locked object. 

Some data manipulation language (DML) operations, such as table truncation, use Sch-M locks to prevent access to affected tables by concurrent operations.

The index rebuild is also a table modification process, so it also uses the Sch-M lock on the table. Once the index rebuild ID is issued, a schema modification lock (Sch-M) will be acquired on that table and will be released only after the index rebuild process is completed. 



2. Schema Stability Lock (Sch-S):

The Database Engine uses schema stability (Sch-S) locks when compiling and executing queries. The  Sch-S locks do not block any transactional locks, including exclusive (X) locks.

Therefore, other transactions, including those with X locks on a table, continue to run while a query is being compiled. However, concurrent DDL operations, and concurrent DML operations that acquire Sch-M locks, cannot be performed on the table.

An Sch-S lock will be acquired while a schema-dependent query is being compiled and executed and an execution plan is generated. This particular lock will not block other transactions to access the object data and it is compatible with all lock modes except with the schema modification lock (Sch-M). 

Essentially, Schema stability locks will be acquired by every DML and select query to ensure the integrity of the table structure which ensures that table doesn’t change while queries are running.



Q179. What is Bulk Update Lock (BU) in SQL?

Bulk Update Locks (BU):

Bulk update (BU) locks allow multiple threads to bulk load data concurrently into the same table while preventing other processes that are not bulk-loading data from accessing the table. So A bulk update lock is designed to be used by bulk import operations.

When a bulk update lock is acquired, other processes will not be able to access a table during the bulk load execution. However, a bulk update lock will not prevent another bulk load to be processed in parallel. But keep in mind that using TABLOCK on a clustered index table will not allow parallel bulk importing.



The Database Engine uses bulk update (BU) locks only when:

  • You use the T-SQL BULK INSERT statement or the OPENROWSET(BULK) function, or you use one of the Bulk Insert API commands such as .NET SqlBulkCopy, OLEDB Fast Load APIs, or the ODBC Bulk Copy APIs to bulk copy data into a table.
  • The TABLOCK hint is specified or the table lock on the bulk load table option is set using sp_tableoption.

Unlike the BULK INSERT statement, which holds a less restrictive Bulk Update lock, INSERT INTO…SELECT with the TABLOCK hint holds an exclusive (X) lock on the table. This means that you cannot insert rows using parallel insert operations.



Q180. What is the Key Range Lock in SQL?

Key-Range Locks:

Range locks are obtained on index keys to prevent phantoms when you execute transactions under serializable isolation. 

A key-range lock is placed on an index, specifying a beginning and ending key value. This lock blocks any attempt to insert, update, or delete any row with a key value that falls in the range because those operations would first have to acquire a lock on the index. 

The serializable isolation level requires that any query executed during a transaction must obtain the same set of rows every time it is executed during the transaction.

A key range lock protects this requirement by preventing other transactions from inserting new rows whose keys would fall in the range of keys read by the serializable transaction.

Key-range locks protect a range of rows implicitly included in a record-set being read by a Transact-SQL statement while using the serializable transaction isolation level. 

Key-range locking prevents phantom reads by protecting the ranges of keys between rows, it also prevents phantom insertions or deletions into a record-set accessed by a transaction.



To Be Continued Part-20...


Recommended Articles






Thanks for visiting this page. Please follow and join us on LinkedInFacebookTelegramQuoraYouTubeTwitterPinterestTumbler, and VK  for regular updates.

    

Sunday, September 25, 2022

.Net Core Interview Questions and Answers - Part 04

ASP.Net Core Interview Questions and Answers - Part 04

AspDotNetCoreInterviewQuestionsAndAnswers

Are you preparing for the .Net Core Interview? If yes, then you are at the right place. This is the ASP.Net Core Interview Questions and Answers article series. Here we will see the Top 150+ .Net Core Interview Questions with Answers. 

Please visit our YouTube Channel for Interviews and other videos by below link:




Please read the complete Design Pattern, C#, MVC, WebAPI, and .Net Framework Interview Questions and Answers article series here.




Introduction


This is the 4th part of the .Net Core Interview Questions and Answers article series. Each part contains ten .Net Core Interview Questions. Please read all the .Net Interview Questions list here.

I will highly recommend to please read the previous parts over here before continuing the current part:






ASP.Net Core Interview Questions and Answers - Part 04


Q033. What is Blazor? What are the advantages of Blazor?

Blazor is a free and open-source web framework developed by Microsoft that enables developers to create web apps using C# and HTML. Blazor is Microsoft’s latest web framework technology for building interactive client-side web UI with .NET. 

It is a new framework introduced with .Net Core 3.0. We generally use the C# code on the server side only, but with Blazor we can use C# code on the client side as well.

Blazor lets you build interactive web UIs using C# instead of JavaScript. Blazor apps are composed of reusable web UI components implemented using C#, HTML, and CSS. Both client and server code is written in C#, allowing you to share code and libraries.



Use of Blazor: With Blazor you can:

  1. Create rich interactive UIs using C# instead of JavaScript
  2. Share server-side and client-side app logic written in .NET.
  3. Render the UI as HTML and CSS for wide browser support, including mobile browsers.
  4. Integrate with modern hosting platforms, such as Docker.
  5. Build hybrid desktop and mobile apps with .NET and Blazor.

Blazor apps are based on components. A component in Blazor is an element of UI, such as a page, dialog, or data entry form. Components are .NET C# classes built into .NET assemblies that define flexible UI rendering logic or Handle user events.



Advantages of .Net in Blazor for Client-Side Web Development:

  1. Write code in C# instead of JavaScript.
  2. Leverage the existing .NET ecosystem of .NET libraries.
  3. Benefit from .NET's performance, reliability, and security.
  4. Share app logic across server and client.
  5. Stay productive on Windows, Linux, or macOS with a development environment, such as Visual Studio or Visual Studio Code.



blazor
Source: Microsoft Doc

With the release of .NET 5, Blazor has stopped working on Internet Explorer and the legacy version of Microsoft Edge.



Q034. What is the difference between Blazor Server and Blazor WebAssembly?

There are five different editions of Blazor apps have been announced - Blazor Server, Blazor WebAssembly, Blazor PWA, Blazor Hybrid, and Blazor Native.

Blazor Server and Blazor WebAssembly have several differences. Blazor WebAssembly is also known as Blazor Wasm.



Blazor Server:

Blazor Server provides support for hosting Razor components on the server in an ASP.NET Core app. UI updates are handled over a SignalR connection. Blazor Server was released as a part of .NET Core 3. Blazor Server uses ASP.Net Core application and we can use entity framework to connect with SQL Databases.

Blazor Server apps render content differently than traditional models for rendering UI in ASP.NET Core apps using Razor views or Razor Pages. Blazor Server produces a graph of components to display similar to an HTML or XML DOM. 

The component graph includes states held in properties and fields. Blazor evaluates the component graph to produce a binary representation of the markup, which is sent to the client for rendering. 

When an update occurs, the component graph is rerendered, and a UI diff (difference) is calculated. This diff is the smallest set of DOM edits required to update the UI on the client. The diff is sent to the client in a binary format and applied by the browser.



Blazor WebAssembly (Blazor Wasm):  

Blazor WebAssembly is a single-page app (SPA) framework for building interactive client-side web apps with .NET. Blazor WebAssembly uses open web standards without plugins or recompiling code into other languages. Blazor WebAssembly works in all modern web browsers, including mobile browsers. Blazor Wasm works on the browser and downloads the Blazor application on the client side. 

Running .NET code inside web browsers is made possible by WebAssembly (wasm). WebAssembly is a compact bytecode format optimized for fast download and maximum execution speed. WebAssembly is an open web standard and is supported in web browsers without plugins.

WebAssembly code can access the full functionality of the browser via JavaScript, called JavaScript interoperability, often shortened to JavaScript interop or JS interop. .NET code executed via WebAssembly in the browser runs in the browser's JavaScript sandbox with the protections that the sandbox provides against malicious actions on the client machine.



Single-page apps that are downloaded to the client's web browser before running. The size of the download is larger than for Blazor Server, depending on the app, and the processing is entirely done on the client's hardware. However, this app type enjoys rapid response time. As its name suggests, this client-side framework is written in WebAssembly, as opposed to JavaScript (while they can be used together).

blazor-webassembly
Source: Microsoft Doc


Blazor PWA supports progressive web apps (PWA) and Blazor Hybrid is a platform-native framework but still renders the user interface using web technologies. Blazor Hybrid is in preview and not recommended for production workloads. 

Blazor Native is a platform-native framework that renders a platform-native user interface. It has also been considered but has not reached the planning stage yet.



Q035. What is the use of the UseDeveloperExceptionPage() in .Net Core?

The UseDeveloperExceptionPage() method belongs to the Microsoft.AspNetCore.Builder namespace of UseDeveloperExceptionPage Extensions static class. 

The purpose of this function is to capture synchronous and asynchronous System.Exception instances from the pipeline and generates HTML error responses. 

It returns a reference to the app after the operation is completed. We use the UseDeveloperException() extension method to render the exception during the development mode.



This should only be enabled in the Development environment because detailed exception information shouldn't be displayed publicly when the app runs in the Production environment.

If you want your application to display a page that shows detailed information about the unhandled exception, then you need to configure the Developer Exception Page middleware in the request processing pipeline. To do so, modify the Configure() method of the Startup class:

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
}



We need to configure the UseDeveloperExceptionPage() Middleware as early as possible in the application’s request processing pipeline so that it can handle the unhandled exception and then display the Developer Exception Page with detailed information about the exception.

The Developer Exception Page displays detailed information about unhandled request exceptions. ASP.NET Core apps enable the developer exception page by default when running in the Development environment. 

The developer exception page runs early in the middleware pipeline so that it can catch unhandled exceptions thrown in the middleware that follows. The Developer Exception Page can include the following information about the exception and the request:

  1. Stack trace 
  2. Query string parameters, if any
  3. Cookies, if any
  4. Headers
The Developer Exception Page isn't guaranteed to provide any information, so please use Logging for complete error information.




Q036. What is Transfer-Encoding in .Net Core?

Transfer encoding is used to transfer the entity to the user. It is set to Chunked indicating that Chunked transfer encoding data transfer mechanism of the HTTP Protocol is initiated in which data is sent in a series of "chunks".

The HttpResponseHeaders.TransferEncodingChunked Property is used to Get or Set a value that indicates if the Transfer-Encoding header for an HTTP response contains chunked. It is true if the Transfer-Encoding header contains chunked, otherwise false.

Basically, ASP.NET Core HttpClient sends requests chunked by default. This was not the case for .NET Framework. This can cause some issues with compatibility.

ASP.NET transfers the data to the client in chunked encoding (Transfer-Encoding: chunked), if you prematurely flush the Response stream for the HTTP request and the Content-Length header for the Response is not explicitly set by you. You need to explicitly set the Content-Length header for the Response to prevent ASP.NET from chunking the response on flushing.




Q037. What is ASP.Net Core Identity?

ASP.NET Core Identity is an API that supports user interface (UI) login functionality. It manages users, passwords, profile data, roles, claims, tokens, email confirmation, and more. 

ASP.Net Core Identity provides a wide range of helper functions to perform essential core features related to user identity management.

Users can create an account with the login information stored in Identity or they can use an external login provider like Facebook, Google, Microsoft Account, and Twitter.

Identity is typically configured using a SQL Server database to store user names, passwords, and profile data. Alternatively, another persistent store can be used, for example, Azure Table Storage. ASP.NET Core Identity adds user interface (UI) login functionality to ASP.NET Core web apps.



IdentityInCore
Source: Microsoft Docs

ASP.NET Core Identity is a membership system that adds user registration and login capabilities to an ASP.NET Core web UI. The membership system handles both authentication and authorization concerns. 

Authentication is concerned with who you are. Authorization is concerned with what you're allowed to do. Authentication is therefore a prerequisite for authorization.




Q038. What is the difference between Stateful and Stateless authentication in .Net Core?

Stateful Authentication or Session-Based Authentication:

Stateful Authentication is a way to verify a user by having the server or backend store session information, such as user properties. 

Stateful authentication is also called session-based authentication or cookie-based authentication for the session information the server must store on the user.

After successful authentication, the application generates a random token to send back to the client and then creates a client-authenticated session in memory or an internal database. 

When a client tries to access the application with a given token, the application tries to retrieve session data from session storage, checks if the session is valid and then decides whether the client has access to the desired resource or not.

It is simpler to implement than Stateless or Token-Based Authentication but it is resource-intensive causing the server to perform lookups for every request. Stateful authentication is straightforward and easy to implement however its drawbacks include a lack of scalability.



Stateless Authentication or Token Based Authentication:

Stateless Authentication is a way to verify users by having much of the session information such as user properties stored on the client side. Stateless authentication is efficient, scalable, and interoperable.

Stateless authentication uses tokens, most often a JSON Web Token (JWT) or OpenID Connect, that contain the user and client information. A popular form of stateless or token-based authentication is Security Assertion Markup Language (SAML) as well.

After successful authentication, the application generates a token with all necessary data, signs it with a public key, and sends it back to a client. There is a standard for token generation, it is JWT (JSON Web Token). 

When a client tries to access the application with a token, the application verifies the token sign with a private key, checks if the token is expired, retrieves all session data from the token, and makes a decision if a client has access to the desired resource.

Stateless authentication stores the user session data on the client-side (browser). Since the user session is stored on the client side, the server only has to verify its validity by checking whether the payload and the signature match.



Stateful Authentication vs Stateless Authentication:

In stateful authentication, it is impossible to steal session information from the session identifier because it is just an identifier associated with the session. But in Stateless authentication Session identifier contains all authentication information and it is possible to steal sensitive information, it is not encrypted.

In stateful authentication, it is possible to revoke a session at any time but it is not possible in stateless authentication since the session token contains an expiration date, it is impossible to revoke the authentication session.

In stateful authentication, it is possible to modify any session data in session data storage. But it is not possible in stateless authentication because the session token contains all session data, it is not possible to modify it.



In stateful authentication when retrieving session information, the service always gets access to session storage which causes additional resource consumption. But this is not the case for stateless as the session identifier contains all session information.

When stateful session information is stored in an external database, there is a need to implement session database persistence. In the case of a stateless since the Session identifier contains all session information, there is no need to implement additional functionality.

In stateful authentication the authentication token is just an identifier, so session data does not affect its size. But in stateless authentication, if an authentication session contains a large amount of data, the authentication token also becomes large, which can cause additional load on a network.

In stateful authentication, only the authentication system is able to retrieve session information from an authentication token, so there are no more vulnerabilities. But in other cases to decrypt session information from a token, all parts of the system should share the same key. And, if at least one system is compromised, all parts of the system are under the threat.




Q039. What is the difference between OpenID, OAuth, and SAML?

OAuth vs OpenID vs SAML:

OAuth 2.0 is a framework that controls authorization to a protected resource such as an application or a set of files, while OpenID Connect and SAML are both industry standards for federated authentication

Using either OpenID Connect or SAML independently, enterprises can achieve user authentication and deploy single sign-on. Though they both deal with logins, they have different strengths and weaknesses.

The OpenID is used for authentication while OAuth is used for authorization.



OpenID Connect is built on top of OAuth 2.0 protocol and uses an additional JSON Web Token (JWT), called an ID token, to standardize areas that OAuth 2.0 leaves up to choices, such as scopes and endpoint discovery. It is specifically focused on user authentication and is widely used to enable user logins on consumer websites and mobile apps.

On the other hand, SAML is independent of OAuth, relying on an exchange of messages to authenticate in XML SAML format, as opposed to JWT. It is more commonly used to help enterprise users sign in to multiple applications using a single login.

OpenID was created for federated authentication, meaning that it lets a third-party application authenticate users for you using accounts that you already have. In contrast, OAuth was created to remove the need for users to share their passwords with third-party applications.



OAuth:

The OAuth provides secure delegated access. An application can take action or access resources from a server on behalf of the user, without them having to share their credentials. 

It does this by allowing the identity provider (IdP) to issue tokens to third-party applications with the user’s approval.

For example when you ever signed up to a new application and agreed to let it automatically source (import) new contacts via Facebook or your phone contacts. So OAuth is an open standard for access delegation deals with authorization 

The OAuth 2.0 protocol provides API security through scoped access tokens. OAuth 2.0 enables you to delegate authorization, while OIDC enables you to retrieve and store authentication information about your end-users. OIDC extends OAuth 2.0 by providing user authentication and single sign-on (SSO) functionality.



OpenID Connect(OIDC):

OpenID Connect is an open standard that organizations use to authenticate users. IdPs use this so that users can sign in to the IdP, and then access other websites and apps without having to log in or share their sign-in information. 

For example using a Google account to sign in to applications like YouTube, Facebook, or any online shopping cart website to log into.

The OpenID Connect is an authentication standard built on top of OAuth 2.0. It adds an additional token called an ID token.  

When a client uses OAuth, a server issues an access token to a third party, the token is used to access a protected resource, and the source validates the token. Notice, that at no point is the identity of the owner of the token verified.



SAML(Security Assertion Markup Language):

SAML is an XML-based standard for exchanging authentication and authorization data between IdPs and service providers to verify the user’s identity and permissions, then grant or deny their access to services.

SAML authentication is used in the work environment. For example, it enables you to log into your corporate intranet or IdP and then access numerous additional services, such as Salesforce, Box, or Workday, without having to re-enter your credentials.



Q040. What is the Ok() helper method in ASP.NET Core?

Ok helper method return Status 200 OK response. This status code is returned when requested data is found. If you want you can return the data as well like Ok(object).

It is defined in Microsoft.AspNetCore.Mvc namespace.



Q041. What is NotFound() helper method in ASP.NET Core?

NotFound() helper method return  Status 404 NotFound response. This status code return when requested data is not found.

You can also use NotFound(object) which creates a NotFound ObjectResult that produces a Status404NotFound response.

It is also defined in Microsoft.AspNetCore.Mvc namespace.



Q042. What is BadRequest() helper method in ASP.NET Core?

BadRequest() helper method return Status 400 BadRequest response. This status code returned when data provided in the request failed the validation.

You can also use BadRequest(ModelStateDictionary) which creates an BadRequestObjectResult that produces a Status400BadRequest response and BadRequest(Object) which creates an BadRequestObjectResult that produces a Status400BadRequest response.

It is also defined in Microsoft.AspNetCore.Mvc namespace.




To Be Continued Part-05...


Recommended Articles






Thanks for visiting this page. Please follow and join us on LinkedInFacebookTelegramQuoraYouTubeTwitterPinterestTumbler, and VK for regular updates.