Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / web / ASP.NET

ASP.NET Interview Questions and Answers on JWT Token Security

3.06/5 (5 votes)
20 Dec 2023CPOL7 min read 15K  
In this article, we break down some most asked interview questions on Security part in ASP.NET MVC.
This article discusses some of the questions on Security part in ASP.NET MVC that are most likely to be asked in an interview.

Contents

Watch 25 ASP.NET MVC Core Interview Questions explained with practical answers.

How Does Token Based Authentication Works?

Token based Auth is a two-step process:

  1. Client sends credentials to the server.
  2. Server respond backs with a token.
  3. Later to access the resource only this token is needed.

Why is it called JWT Token?

JWT stands for (JSON Web based Token). JSON stands for JavaScript object notation. JSON is a data format with name and value as shown in the below figure. Because we receive the token in JSON format, it’s termed as JWT Token.

Image 1

Explain the Three Sections of JWT Token?

  1. Header: This section has Algorithm and type of token.
  2. Payload: This has the identity and claims information.
  3. Signature: This section is created using the first two sections (Header, Payload) and Secret key.

Image 2

What are Identity and Claims?

Identity identifies the user or entity uniquely. Claims talks about what roles / rights the user has with respect to the system.

Differentiate between Authentication VS Authorization?

Authentication ensures that the user exists in the system. Authorization talks about the roles and rights of the users. Authentication talks about WHO the user is and Authorization talks about WHAT the user can do with your system.

Claims vs Roles?

Roles

Claims

Role classifies user types (Admin, User, Superuser) and to these user types roles are assigned. Claims can have permissions but it talks more about the Subject.

Claims can have roles but not all Claims can be roles. Some claims which can not be roles are :-
Browser =Chrome , Senior Citizen=true, Lang Known=English.

Roles are assigned to a user type. Claims are assigned to the actual USER.

Principal vs Identity

Identity represents a user + roles + claims. Principal encapsulates identity object and can be assigned to a code / thread context.

Can We Put Critical Information in JWT Token?

No. It’s just BASE64 encoded and can be decoded very easily.

How Do You Create JWT Token in MVC?

Step 1: Import “Microsoft.AspNetCore.Authentication.JwtBearer” package from Nuget.

Step 2: Use the package for generating the token.

Below is the sample code for generating token. Now remember that this is an interview so it's difficult to explain code in detail and that too verbally. So the best would be map the code with the three sections of the token structure and explain the same.

This will make the interviewers life easy in understanding what you are speaking.

  • First step is to select the algorithm. Interviewer can ask you name of the algorithm. Does not hurt to remember HMACSHA256.
  • Next step is creating the claims collection. Remember there are standard claims and you can add your own.
  • Last step is to use the Algorithm, use claims and generate token.

Image 3

Where is Token Checked in ASP.NET MVC ?

Token authenticity is checked in the pipeline. In the startup, we need to add this “JwtBearer” check in the pipeline.

Image 4

Below is how to add the same in pipeline.

JavaScript
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidateAudience = true,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
ValidIssuer = "Questpond",
ValidAudience = "BrowserClients",
ClockSkew = TimeSpan.Zero,
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("victoriasecret@123456"))
};
});

You also need to call “UseAuthentication” and “UseAthorization” in the same sequence first Authentication and then Authorization as shown in the below code.

JavaScript
app.UseAuthentication();
app.UseAuthorization();

What is the Use of Authorize Attribute?

JWT Token authentication is only applied to controllers who have Authorize Attribute decorated.

JavaScript
[Authorize]
public class ValuesController : ControllerBase
{}

How Did You Implement JWT Token Security ?

Interviewer can ask you in general to talk about the steps as well. Summarizing what we discussed in the last three questions:

  1. Import the “Microsoft.AspNetCore.Authentication.JwtBearer” JWT package.
  2. Create the three sections of the token.
  3. Add the Bearer Check in the pipeline.
  4. Apply the [Authorize] attribute to controllers which needs to be protected.

What HTTP Status Code Do You Send for Unauthorized Access?

HTTP 401 is the status code which represents UnAuthorized access. Many developers answer 500, please note 500 stands for internal server error which represents validation or technical issues. And yes 200 is when everything is ok.

How Do We Send Tokens From Client Side?

Token is sent in the REQUEST HEADER in standard format defined by W3C as shown below.

Authorization: Bearer XXTokenXX

From JavaScript, JQuery, Angular, etc. How is Token Passed?

Whichever technology you use, the most important thing is you will need to follow the W3C structure, i.e.,

Authorization: Bearer XXTokenXX

Below is code using simple FETCH API:

JavaScript
fetch('http://localhost:8080/resourceserver/protected-no-scope', {
method: 'GET',
headers: new Headers({ 'Authorization': 'Bearer <token>',
'Content-Type': 'application/x-www-form-urlencoded'
})
});

JQuery Code again same you will need to stick to the structure.

JavaScript
$.ajax({
url: 'http://localhost:8080/resourceserver/protected-no-scope',
type: 'GET',
contentType: 'application/json'
headers: { 'Authorization': 'Bearer <token>'
},
success: function (result) {
// CallBack(result);
},
error: function (error) {
}
});

Angular code looks something like this:

JavaScript
var headers_object = new HttpHeaders();
headers_object.append('Content-Type', 'application/json');
headers_object.append("Authorization", "Bearer " + tokenvar);
const httpOptions = {headers: headers_object};
this.http.post(
'http://localhost:8000/api/role/Post', httpOptions
).subscribe(resp => {
this.roles = console.log(resp)
}
);

So whatever framework you are working on, you can talk about that code but make sure you stick to structure of JWT token.

Increase UX Experience in Mobile Apps to Avoid Relogin?

Use a refresh token.

What Is a Refresh Token?

Refresh token is a separate token by which you can get a new JWT token.

Differentiate Between Access Tokens and Refresh Tokens?

Access tokens ( JWT Token) are tokens which helps you to access a secured resource while Refresh tokens helps to get new JWT token.

How Does Refresh Token Work ?

Step 1: Credentials sent access token + refresh token is generated.

Step 2: Using access token clients can now access resource.

Step 3: Access token expires.

Step 4: Client uses refresh tokens and generates new access tokens plus refresh tokens and continues with Step 2.

Image 5

Whose Expiry Time is More Access Tokens or Refresh Tokens?

Expiry time of Refresh token is more than Access token. Access token expiry time should be less so that if someone gets access to Access token, he has a very small window to make an attack.

Explain Revocation of Refresh Token?

Revocation of Refresh token means expiring / invalidating the token for creating any more JWT token. User needs to freshly authenticate to get new Refresh token.

How to Extract Principal from a Token?

You can extract “Principal” and “Token” by using “TokenHandler” class.

Image 6

What is the Best Practice to Store Tokens at Client Side?

n-memory: Using the application variable, we can store the token when the application is running.

Cookie: If you still want to store, cookie is a good place.

IndexedDB, Session storage and local storage are prone to XSS attacks.

If We Store JWT in Cookie, How to Save from XX Attacks?

Create cookie using HTTP only. By doing so, this cookie cannot be read using JavaScript “document.cookie”. In other words, cookie is safe from XSS attacks.

OAUTH vs OpenID vs OpenIdConnect vs JWTToken ?

OpenId, OAuth and OpenIdConnect are protocols while JWTToken is just a token.

  1. OpenId is all about authentication.
  2. OAUTH is all about authorization.
  3. OpenId connect has both of them.

When Should We Use What?

  • OpenId (Who?): You want to just know if the user exists in the system or not. Like shopping sites, mobile applications, single sign on, etc.
  • OAUTH (What?): When third party application tries to access resources.
  • OpenIDConnect: When you want to authenticate and authorize as well like intranet websites.

What is Identity Server?

Identity server is a free opensource server which helps to implement openId connect and OAuth.

How to Implement Single Sign on?

For single sign, on the authentication / authorization server should be separate. The websites who want to belong to a common federation get into trust with this centralized Authentication / Authorization server.

Many developers use IdentityServer for single sign on.

What is a Scope in IdentityServer ?

Scope is nothing but roles.

For further reading, do watch the below interview preparation videos and step by step video series.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)