JWT Authentication to authenticate many parties (Asp.Net example)
JWT or Json Web Token is a simple and flexible way (standard) for authentication based on json and HTTP.
I don’t want to made it complex so i will go directly through simple definition about JWT and how to use it and then there is an example on how to authenticate many parties using it.
First, We want to understand some simple words:
1- Authorization Server: In Auth world it will be preferred if we can delegate the Auth role to a stand alone server. This server will be responsible for 2 main roles:
- Generating security tokens (In our case JWT).
- Works as a UserService and UserStore for example having the logic of Register, Sign-In, Sign-Out, change user password etc. and also having the database that contains the users info.
2- Resource server: This is any party you want to authenticate or you want to protect it’s data. For example a service that contains some Web-APIs end points, Web site, Micro-service and etc.
3- Resource Owner: This is the owner that request the token, It may be human or machine.
4- In some already existing systems, you may find one of the resource servers have the role of authorization server also so it have resources you want to protect and also it will be the protector :)
5- Some times we called Resource servers, an audience.
6- Claims: Claims meaning it self can be formed as a lot of things based on the way or authentication type but as a general meaning we can think of claims as metadata or some peace of information about users or systems for example user email, user birthday or expiration date of the token.
7- Scopes: We use this terminology in authentication world generally to specify a scopes to manage access restriction in order to ensure a safe relationship between a users and resource servers.
7- JWT: JSON Web Token is our topic and it is an open, industry standard RFC 7519 method for representing claims securely between two parties.
8- OAuth 2: Is an authorization framework that enables applications to obtain limited access to user accounts on an HTTP service, such as Facebook. It works by delegating user authentication to the service that hosts the user account, and authorizing third-party applications to access the user account. OAuth 2 provides authorization flows for web and desktop applications, and mobile devices.
9- OpenID: OpenID Connect is a simple identity layer on top of the OAuth 2.0 protocol. It allows Clients to verify the identity of the End-User based on the authentication performed by an Authorization Server, as well as to obtain basic profile information about the End-User in an interoperable and REST-like manner.
10- OAuth2 vs JWT: JWT is standard while OAuth2 is framework and in OAuth2 we can use the JWT standard.
11- Bearer vs Basic Token: Bearer token used with the Authorization header to provide access token to the audience while basic token provided as encoded username and password so you may consider bearer token is a way you send access token to the audience (resource server).
12- Reference token vs Self Contained JWT token:
JWT token is a type of Self Contained tokens. It may consider as offline token so you can validate it without return back to the authorization server so it’s self contained.
There are another type of tokens which is called reference token . Those tokens are just identifiers for a token stored on the token service. The token service stores the contents of the token in some data store, associates it with an infeasible-to-guess id and passes the id back to the client. The recipient then needs to open a back-channel to the token service, send the token to a validation endpoint, and if valid, retrieves the contents as the response.
Practical intro on JWT:
1- JWT practically consists of two parts:
- How to generate it (This is the Authorization Server role)
- How to consume it (This is the Resource Server role)
2- The main idea about JWT issimple: It’s a token consists of 3 parts like the below:
3- If any user want to access any protected resources he should request token from the authorization server.
4- Authorization server will return base64 encoded token to the user, and the user will use this token to access the protected resource and if the token valid, User gain access to this resource.
5- The key point about JWT is how to validate it, The idea simply is that any resource server should have it’s own secret key and the authorization server must know all this secret key.
For example if we have 2 audience A and B so:
- A: have client-id : a and secret-Key: s1
- B: have client-id: b and secret-Key: s2
Authorization server have this info and when the authorization server generate token for the first client (A) it encode the secret key as base64 then signed it using signing algorithm so the token can be verified and trusted because it is digitally signed.
JWTs can be signed using a secret (with the HMAC algorithm) or a public/private key pair using RSA.
This signed part is the last part of the token as we said before token in JWT consists of 3 parts.
A Full Scenario in simple steps:
- user x request token to contact client A.
- Authorization server generating a signed token and send the token to the user.
- User x request a protected data from client A.
- Client A, validate the token, and return the protected data to user.
Token Structure and How the token generates:
JWT is a standard based on JSON which means that it have a standard way of generating it.
JSON Web Tokens consist of three parts separated by dots [.], which are:
The header is an JSON object consist of 2 values
- The type of the token, which is JWT.
- The hashing algorithm being used, such as HMAC SHA256 or RSA.
Then, this JSON is Base64Url encoded to form the first part of the JWT.
Payload is the 2nd part of the token and it is also a Base64Url encoded JSON object contains 3 types of claims:
- Reserved claims:
It’s some pre-defined claims that specify the issuer, audience, token generation and expiration date and etc.
- Public claims: Let’s escape this now.
- Private Claims: Custom claims created to share information between parties that agree on using them for example: user_email, role.
Example of payload:
Then, this JSON is Base64Url encoded to form the second part of the JWT.
The signature part is the digitally signed part.
You will take the encoded header, the encoded payload and the audience secret, then apply the specified algorithm in the header on it.
base64UrlEncode(header) + "." + base64UrlEncode(payload),
Then we put the 3 parts together separated by [.] for example:
Howthe token used:
- When any user/machine want to access any protected resource, it request a token from the authorization server.
- Then it put the token as Bearer token in the authorization header within the autorized request to the resource server.
How the generation done:
As we talk before, Authorization Server generate the token as 3 parts then combine the parts together with a [.]
How the validation done:
- Resource Server applying the same signing algorithm to his own secret key and then compare it with the signed key in the token. If the signatures match, then that means the JWT is valid which indicates that the API call is coming from an secured source.
I Used Visual Studio 2015:
First i will create the Authorization Server part:
Create Asp.Net Web Application with individual user account template.
Now we want to allow the application to generate JWT token:
Now when we try to talk to the /token end point, it generate JWT token as expected.
Now we will create resource server which is a simple Asp.Net WebAPI:
Create Asp.Net Web Application with no authentication template.
Now we can use this middleware for token validation and put it in the first order in the OWIN pipeline.
Also we can create our custom Middle Ware with a simple logic to validate the token.
Now let’s test our work:
… to be continue in 2 days