In this Blog Post I demonstrate how to implement Authentication and Authorization using Auth0 in Asp.net Core and Angular 4.
I’ll be using JSON Web Tokens (JWT) and Auth0.
Lets review the traditional authentication architecture for traditional Plain Old MVC Applications with razor views rendered on the server, the authentication in this kind of applications works as follows: when the User logs in we validate their user id and password and if they are valid we then issue an authentication ticket that usually contains a user ID and an expiration date as an encrypted string, then we put this ticket in a cookie and return it to the client and include it in every subsequent valid request.
In Asp.net in order to protect an action we simply apply the Authorize attribute to that action.
When Asp.Net runtime receives a request it checks for the existence of this attribute on an action. If the attribute is the ASP.net will extract the authentication ticket from authentication cookie and then it will decrypt the ticket and if it is valid it will allow access to that action.
When building Single page application with Asp.net Core we have a similar architecture but with a few differences.
First is that instead of authentication tickets we use JSON Web Tokens(JWT).
JSON Web Tokens are basically a JSON object that contains some attributes about the user.
We refer to these attributes as claims about that user. This Web token also contain a digital signature which prevents this token from being hacked.
For example, if a hacker tries to modify the values in this token to represent someone else, the validation process will fail because the signature is created based on the content of the token and the only party that can create the signature is the issuer or the server because in the server we have a private key that is used to generate this digital signature.
One key difference between an authentication ticket and a JSON Web Token is that in a JSON Web Token we can have multiple attributes about the user other that just the ID and with this we don’t have to query the database every time we need this information; we can simply extract these value from the JSON Web Token.
As you probably know cookies are only available in browsers and are not available in Mobile devices, smart TVs, in these cases we can put the JSON Web Token in the header request and send it to the server API.
In terms of Storage, for browser applications we typically store this token in the local storage
of the browser which is a simple database that can store simple key value pairs.
In the case of Mobile applications, we can save this token somewhere on the device.
As you can imagine building all this infrastructure is complicated, really tedious and repetitive work and here is where Auth0 really shines as we can delegate all this to it.
First step is to navigate to https://auth0.com/ and sign up for a new account by following auth0 site instructions