User Authentication in ASP.NET WEB API 2 with RSA-signed JWT Tokens (part 1)

Android Development, iOS Development, Tutorials

Are you working on a web or mobile app and looking for the easiest solution for a safe user authorization? If so, you can use JSON Web Token. Keep on reading to find out how it works and see examples of a user authentication in an ASP.NET WEB API 2 application.

When programming a web app, we need to take great care about its security. We want to make sure access to its resources is available only for authorized users. If our app is based on a REST interface, then it uses an HTTP stateless protocol. Therefore, the identifier which authorizes the access must be included in every request that is sent to the server. That is the perfect scenario for using a token.

A token can be a random character string, include some kind of information about the user, be encoded and have limited validation time. A JSON Web Token stores specific user data e.g.: id, roles, access rights. This makes it possible to verify and also identify a specific user.

JSON Web Token structure

JSON Web Token (JWT) is an open standard (RFC 7519) which defines a compact way to send information in JSON format. Data can be encoded with RSA or HMAC algorithms, to keep data verified and safe.

JWT’s short and concise structure makes sending tokens quick and comfortable: we can place it in an HTTP header or a URL address. At the same time the token structure itself lets us verify a user.

The main task of a JWT token is user authentication. It works as follows: after every correct login, a user receives a unique token which is placed in the HTTP header and validated by the server each time a request is sent. In signed tokens we can safely send any type of information.

The information structure in JSON Web Token is as follows:

  • Header
  • Payload
  • Signature

Each of these parts must be coded and separated by a dot (e.g. xxxxx.yyyyy.zzzzz).

Header

The header is composed of two values: an encoding algorithm (e.g. HMAC, SHA256 or RSA) and the type (e.g. JWT).


{
"alg": "HS256",
"typ": "JWT"
}

Payload

This includes claims which mostly are information about a user. We distinguish three types of claims:

  • Reserved claims: unneeded, predefined claims, which are useful when included in Token because they can be really helpful e.g. iss (issuer), exp (expiration time), aud (audience).
  • Public claims: can be defined by the ones who use JWT Tokens. To prevent a collision they should be defined in IANA JSON Web Token Registry or have such a name which won’t interfere with others.
  • Private claims: non-standard claims defined by us and used only when two sides that are interacting with each other know about it.

For example:


{
"sub": "1234567890",
"name": "John Doe",
"admin": true
}

Signature

Prior to creating a signature, you have to encode a header and token payload.

We also need a key to sign the data. Here’s an example on how to do it using HMAC SHA256:


HMACSHA256(
  base64UrlEncode(header) + "." +
  base64UrlEncode(payload),
  secret)

The signature is used to verify the token sender and check if a message hasn’t been modified in the meantime.

Putting all together

By joining all three parts of the token, encoding them with Base64 and separating them by dots we are gaining a compact message, which we can easily send in an HTTP header or in a URL address. As you can see, it’s very short when comparing with other types of such solutions.

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWV9.TJVA95OrM7E2cBab30RMHrHDcEfxjoYZgeFONFh7HgQ

On the official JWT website you can test your tokens (i.e. generate, decode and verify them).

Sending JWT tokens

When the user wants to gain access to protected data, the request has to include an identifier. The JWT Token is usually placed in the HTTP header using the Bearer scheme, just like that:

Authorization: Bearer

The authorization is performed in the same way as the stateless one, this means that the status of a logged in user isn’t saved on the server. The token contains some coded claims, which can be downloaded only once: the first time the user logs in. With each request, the server reads the token and unambiguously identifies the user. This significantly speeds up the authentication process.

web api 2 jwt authentication

The JWT Token authentication process (source: jwt.io)

Once we’re familiar with the basic JSON Web Token structure, its usage and delivery, we can move on to next steps. In the next part of the article I will describe a basic user authentication in ASP.NET WEB API 2 with RSA-signed JWT Tokens.

Sources:

 

Michał Zawadzki Back-end Developer

Michał is at the Back-end site of our software team, specializing in .NET web apps. Apart from being an excellent table tennis player, he’s very much into sci-fi literature and computer games.

Popular posts

Enhancing API Testing Efficiency with JavaScript in Postman

Enhancing API Testing Efficiency with JavaScript in Postman

API testing is essential for good software, and Postman has made it easier by letting us use JavaScript to check our work. In this article, we'll see how using JavaScript in Postman helps us make sure our software is working right, saving us time and making our testing process smoother.

Read more
Flutter application template with GitHub Actions

Flutter application template with GitHub Actions

This article explains how to create Flutter application template with GitHub Actions to save yourself time and nerves.

Read more
Augmented Reality as a trend in Mobile Development

Augmented Reality as a trend in Mobile Development

3D maps, realistic games, virtual showrooms and fitting rooms, interactive participation in a conference or concert, visiting museums and exhibitions. These are just a few examples of where Augmented Reality can be used. Applications created with the help of AR effectively combine the real world with the virtual one. Can your business also benefit from […]

Read more
Mobile Apps

Get your mobile app in 3 easy steps!

1

Spec out

with the help of our
business analyst

2

Develop

design, implement
and test, repeat!

3

Publish

get your app out
to the stores


back to top