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.
Token based Auth is a two-step process:
- Client sends credentials to the server.
- Server respond backs with a token.
- Later to access the resource only this token is needed.
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.
- Header: This section has Algorithm and type of token.
- Payload: This has the identity and claims information.
- Signature: This section is created using the first two sections (Header, Payload) and Secret key.
Identity identifies the user or entity uniquely. Claims talks about what roles / rights the user has with respect to the system.
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.
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. |
Identity represents a user + roles + claims. Principal encapsulates identity object and can be assigned to a code / thread context.
No. It’s just BASE64
encoded and can be decoded very easily.
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.
Token authenticity is checked in the pipeline. In the startup, we need to add this “JwtBearer
” check in the pipeline.
Below is how to add the same in pipeline.
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.
app.UseAuthentication();
app.UseAuthorization();
JWT Token authentication is only applied to controllers who have Authorize
Attribute decorated.
[Authorize]
public class ValuesController : ControllerBase
{}
Interviewer can ask you in general to talk about the steps as well. Summarizing what we discussed in the last three questions:
- Import the “
Microsoft.AspNetCore.Authentication.JwtBearer
” JWT package. - Create the three sections of the token.
- Add the Bearer Check in the pipeline.
- Apply the
[Authorize]
attribute to controllers which needs to be protected.
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.
Token is sent in the REQUEST HEADER
in standard format defined by W3C as shown below.
“Authorization: Bearer XXTokenXX ” |
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:
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.
$.ajax({
url: 'http://localhost:8080/resourceserver/protected-no-scope',
type: 'GET',
contentType: 'application/json'
headers: { 'Authorization': 'Bearer <token>'
},
success: function (result) {
},
error: function (error) {
}
});
Angular code looks something like this:
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.
Use a refresh token.
Refresh token is a separate token by which you can get a new JWT token.
Access tokens ( JWT Token) are tokens which helps you to access a secured resource while Refresh tokens helps to get new JWT token.
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.
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.
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.
You can extract “Principal
” and “Token
” by using “TokenHandler
” class.
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.
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.
OpenId
, OAuth
and OpenIdConnect
are protocols while JWTToken
is just a token.
OpenId
is all about authentication. OAUTH
is all about authorization. OpenId
connect has both of them.
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.
Identity server is a free opensource server which helps to implement openId connect and OAuth.
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.
Scope is nothing but roles.
For further reading, do watch the below interview preparation videos and step by step video series.