1. What is needed for authentication

In this blog post we will see how to authenticate users with credentials userid and password.
First, we will see how to store encrypted password and how we can verify credentials against the one contained in database.
Then we will see how we can authenticate users while communicating between client (browser) and server with Jwt token.
Lastly we will see how both glued together provide a reliable authentication story.

2. Password encryption and storage

2.1 Storage

To store data I will be using Sqlite via Sqlite net pcl. If you need a tutorial on Sqlite have a look at my previous post.
We first start by defining the table users which will be stored in user_accounts.db.
The users table will contain all the user identity information.

The password will also be stored but we must encrypt it before storing it.

2.2 Encryption

Why do we need to encrypt password?

In the event of data breach, someone may have access to your db. This could be catastrophic for users if the password is stored in plain text because lots of users reuse the same email and password for different websites. So the solution to that is to encrypt passwords.

Salt?

We will use a hashing algorithm via System.Security.Cryptography.Rfc2898DeriveBytes (PBKDF2: Password based key derivation function 2) which produces a key given a password and a salt and a number of iterations.

But It is not as simple as just hashing plain password. Some users use simple passwords which make it easy for attackers to crack by using rainbow tables. Rainbow tables are files containing all the common password together with the hashed value. If we simply hash a password, if the password is simple like Rock123 there is chance for it to be retrievable in a rainbow table.

The answer to that is to use a salt. A salt is a random set of bytes that we append to the password in order to make the final hash different than the hash which would have been generated without it.
The purpose of the salt is to make the hashed password not retrievable in rainbow tables even for simple password.

Algorithm

We will create a cryptography utility with two functions.

1. `Hash`: Hash will take a plain text password and hash it. It serves to hash the password when creating the user account and we will store the hash.
2. `Verify`: Verify will compare a plain text password with a hash password. It will be used to verify a provided password against the hash provided (which will certainly be the hash stored in db).

We first define the salt size, the key length and number of iterations. This will constitute the full hash. So the password size in term of bytes will be:

The hash function will do the following:
First instantiate PBKDF2 with the password, requested salt size and iterations. The more iterations, the longer It will take to break the password but the longer it will take to verify the password too. So the number should balance both. Here we use 10000 iterations.
Once we have that we can extract the salt and the key. We convert the number of iterations to byte. And combine salt + key + iterations to make the hash. Once we have the hash we can then converted to string with Convert.ToBase64String and we will be able to store this hash as text.

For the verify function, as a first step we can verify if the length of the password is the same as the one we use by converting back the hashedPassword to bytes and comparing it with the hash size. If it is different we can fail quickly.
If it is the same we need to extract the salt and iterations from the hash and then instantiate PBKDF2 given the provided password with salt and iterations and compare the result with the actual key from the hash. We do a byte by byte comparaison if both byte sequences are identical the password is valid.

We define an interface which has two main functions Get and Create.Get takes a userid, we need it to retrieve a user and get its hashe password.Create takes all the required information and save it into database.

Note that we take a plain password and use our hash method to hash the password before saving it.

We now have the first part of our story - a way to create users with password, store the users info and retrieve it and verify credentials.
Next we need a way to authenticate user request from the client side.

The algorithm used is HS256 which is a symmetric algorithm meaning the person generating and the person verifying the hash must share the key. In our case both are done by the server, we generate the signature hash on the server and when we get a token, we verify its signature on the server too.

But we won’t have to do all that manually as we will be using Jose-jwthttps://github.com/dvsekhvalnov/jose-jwt which provides an implementation of the Jwt protocol and allows us to use the following functions:

Jose.JWT.Encode
Jose.JWT.Decode

Encode takes a serialized payload with the private key and algorithm (HS256).Decode takes the token with a private key and algorithm expected and returns the serialized payload. It also performs all the necessary signature verification. It will throw an exception which need to be caught if the signature is wrong or the algorithm used is incorrect.

Bearer is the name of the authentication token protocol used. When sending the token, we prefix it with Bearer -> Authorization: Bearer [token] and the server will know what the token is for and how to handle it.

Use the middleware

Now that we have the auth middleware, we can place it before the sitelet.

Here I am passing some configuration which you can find in the source code sample here.

Every call except /token will go through the authentication and when passing a valid token, the middleware below (here our sitelet) will have access to the principal and IsAuthenticated will return true.

In a SPA context, all GET requests for pages will not need to be secured but all API calls for data will be done through Ajax queries and will need authentication.

All we need to do now is to glue it all together.

5. Glue it all together

In the previous sections we did the following:

1. Created a user accounts registry with password stored
2. Created a JWT middleware

Now what we need to do is to have simple register page and a simple login page.
Once we login, we will receive the token which we can either store in cookie or in token storage.

WebSharper RPC

One of the best feature of WebSharper is RPC which allows us to call server functions from the clientside code and let WebSharper handle all the serialization/deserialization in the background.
But since are authentication is token based, we need to add the token in the header. To do so we can replace the default remoting module:

Congratulation! We build together a full end to end authentication story. There are more to do, like renew token for example for the JWT and for password we must allow reset password but I hope this helped you understand better what pieces are required to build an auth and use it from a WebSharper selfhost application.

Conclusion

In this post, we saw how to create an end to end authentication story with user credentials saved in database and how to implement JWT token for the client-server communication. On the way we learnt some cryptography algorithm and learnt some keywords definition like salt or bearer. We also learnt how JWT works thoroughly.Some people will tell you “don’t implement your own auth because you will fail” and use this as an excuse to not learn anything about authentication or how to implement it. Don’t be one of them. Learn everything you can and especially learn what type of attacks your webapp is vulnerable to.
There are still more to do like refresh token or implement a 2 factor auth (2FA). But I hope this helped you start your project and getting the base authentication setup. Hope you liked this post, if you have any comment leave it here or hit me on Twitter @Kimserey_Lam.
See you next time!

Comments

Post a Comment

Popular posts from this blog

Absolute layout and relative layout Xamarin formsIn Xamarin Forms, layouts are used to position elements in the page.
There are multiple layouts available like stack layout, grid layout, table layout, absolute layout and relative layout.
Stack layout is straight to grasp the concept, we stack elements one by one horizontally or vertically.
Grid layout is also straight forward, we define rows and columns and we place the elements by indicating the row index and column index.
On the other hand, absolute layout and relative layout isn’t that straight forward because in Xamarin it is NOT the same as positions in CSS.So today, we will see how and when we can use absolute layout and/or relative layout in our advantage.
This post is composed by two parts: 1. Absolute layout
2. Relative layout
1. Absolute layoutThe first thing to understand is that absolute layout has nothing to do with CSS absolute position.
In Xamarin Forms. absolute layout allows us to position elements in the page by pre…

Build an accordion view in Xamarin.FormsFew weeks ago I posted about absolute and relative layouts.
Layouts are called Layouts because they contain children which are placed in a particular way.
Xamarin.Forms has a lot of layouts and views to structure pages like grid, table view or list view.Today I would like to show you how we can use some of these basic views to build an Accordion view.Here’s a preview of the Accordion view:Full source code available on GitHub - https://github.com/Kimserey/AccordionView/blob/master/Accordion/AccordionView.csThis post will be composed of four steps:Create a BindablePropertyDefine the accordion expandable sectionDefine the accordion viewUsage sample1. Create a BindablePropertyAs we saw in one of my previous post,
Xamarin.Forms works around data bindings.
View properties are bound to viewmodel properties.Default views like Label, Button, ListView or TableView come with the necessary bindable properties like BackgroundColor, TextColor, ItemsSource, It…

Use Font Awesome from your Xamarin.Forms projectIcons are important in mobile applications where space is limited.
We use icon everywhere to convey action intent like + would be to add an item or a bin would be to delete one.
There are two ways to add icons to our mobile app:with imageswith fontsToday we will see the second option - how we can add Font awesome to our Xamarin.Android project and how we can use it from Xamarin.Forms.
This post will be composed by three parts: 1. Why Font Awesome
2. Add Font Awesome to the Droid project
3. Use with Xamarin.Forms
1. Why Font AwesomeIf you are familiar with Web development, you must have encountered Font awesome http://fontawesome.io/.
It is an icon font containing lots of icon for every type of usage.
The advantaged of using a font is that we can leverage the text options, like text color or text size, to easily update the style of the icon to match our app.Let’s see how we can bring Font Awesome to the Droid project.2. Add Font awesome…