If you are a long-year software engineer, you surely familiar with implementing Authentication and Authorization for an application. Everyone knows Auth is the most basic and important part of almost all application included User module that help protect informations of specific user from others.
As you know, to implement an Auth Service, you need to do a lot of configurations such as:
- Host a Database to store ID and Password and something like Role if you want to handle Authorization.
- Choose technology to share the resource.
- Choose encryption algorithm to protect password.
- Implement related utilities such as forgot password, invite new user…
You also face with the danger of being attacked by HACKER!!
Have you ever thought of an alternative solution for all above manual tasks to get the Secure Auth?
Yes! My answer is Auth0.
Auth0 is an easy to implement, adaptable authentication and authorization platform.
Besides the conveniences, Auth0 also ensures the security for your user info.
Auth0 has achieved a Level 2 audit Gold CSA Star certification for its cloud service security capabilities. Auth0 is compliant with the Payment Card Industry (PCI) Data Security Standard (DSS) that requires strict security controls and processes for transacting customer payment card data.
Basically, we have a few ways to get Auth from Auth0. But there are two basic way: Server Side Flow and Application Side Flow.
Today, I will introduce the Server Side Flow also known as Authorization Code Flow. Because regular web apps are server-side apps where the source code is not publicly exposed. So instead of proceeding auth from application side, we usually do it in our backend code and only announce for application by using API.
NOTE: I will use Golang as server side programing language through this story.
Prepare a simple server with Golang
Init your Golang project by using following command
go mod init auth0-meow
Then you can push following code into file main.go and run it to start your simple Golang server. The command go mod vendor
will help you pull all related dependencies to run Golang code.
Maybe fine, we will continue on creating an Auth0 Application and related API.
Create Auth0 Application and API
Firstly, go to https://auth0.com
and create one account for your own. After the account is created, you can use this account to login to Auth0 Dashboard and click on Applications > Applications in the left sidebar to see the Applications Management screen like following:
In this place, you can create your application that will help you manage almost all aspects of Auth service. With backend server, we need to choose the type Regular Web Applications and click on create.
After the application is created, you can choose your technology applied in your project and get the guide to quick start by using Session-based Authentication, but I prefer Token-based Authentication. This is also the reason why I write this story.
To continue, We will go to application settings and setup a few stuffs.
Please follow below steps
- Save value of these fields: Domain, Client ID, Client Secret.
- Scroll down and click on Advanced Settings > Grant Types > Tick Password. You can optionally setup OAuth config such as JWT Signature Algorithm in the tab OAuth. Remember save your changes.
- In the tab Connections, you can see the location that user info is stored. Auth0 using connection Username-Password-Authentication by default.
Next, we need to create an Auth0 API to connect to the above application.
What is Auth0 APIs?
An API is an entity that represents an external resource, capable of accepting and responding to protected resource requests made by applications. In the OAuth2 spec, an API maps to the Resource Server.
When an application wants to access an API’s protected resources, it must provide an Access Token. The same Access Token can be used to access the API’s resources without having to authenticate again until it expires.
Briefly, you can take advantage of this API to generate JWT token to use to protect the resources in your Backend Server. So you also need to implement your own middleware work as a JWT validator.
To create new Auth0 API, click Applications > APIs > Create API and fill in all info. Note that Identifier can be any URL. Because we just only use this API as a tool to generate JWT Token, this URL is only an ID here. Remember store this Identifier, we need to when request a token from API.
To connect this API with your Auth0 Application that is generated above, click Machine to Machine Applications, turn off Test Application and turn on your application (for me, it is stuff).
Setup Auth0 successfully, we can try implementing API to Create User and Get JWT Access Token in our Backend Server now without Local Database.
Implement APIs for User module
Register User
Currently, we can easily create an user and store user info on the Auth0 Database by using an this Auth0 API /dbconnections/signup
instead of implementing new once.
To do that, we need a few ENVs from Auth0. I will declare all variables as the const in this code. But in the real product, please add there variables in the secret area.
Then we need to implement a handler for API register user like following code.
Try calling this API by using this cURL
curl --request POST \
--url http://localhost:8080/register \
--header 'Content-Type: application/json' \
--data '{
"email": "vhbien000@gmail.com",
"password": "Bien121212"
}'
You will get the response
{
"_id": "60bb5104bfb8e5006a7ac99f",
"email": "vhbien000@gmail.com",
"email_verified": false
}
In the Local Database, you can create a table to manage user by Auth0 ID and Email without any worry about User info security.
Double check the Auth0 Dashboard, you can see the account already has existed.
After creating user, now, we can implement API to login. We can also understand it is an API include the task calling an Auth0 API to request token.
Login
Similar to create user, just only use another Auth0 API and add a few additional config.
Try with following cURL
curl --request POST \
--url http://localhost:8080/login \
--header 'Content-Type: application/json' \
--data '{
"email": "vhbien000@gmail.com",
"password": "Bien121212"
}'
You can get the response like below
{
"access_token": "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCIsImtpZCI6InlaOFlHWUhrakE1UFZLVE5CekQxVCJ9.eyJpc3MiOiJodHRwczovL2JpZW52aC5hdS5hdXRoMC5jb20vIiwic3ViIjoiYXV0aDB8NjBiYjUyYjZjMWZlYjEwMDZhMzkxM2Q0IiwiYXVkIjpbImh0dHBzOi8vYmllbnZoLmNvbSIsImh0dHBzOi8vYmllbnZoLmF1LmF1dGgwLmNvbS91c2VyaW5mbyJdLCJpYXQiOjE2MjI4ODk4MDgsImV4cCI6MTYyMjk3NjIwOCwiYXpwIjoiclFoWXkzaWpwYjdENmVqZElqQWc2ZU1oa2xNbkdXNjciLCJzY29wZSI6Im9wZW5pZCBlbWFpbCBwcm9maWxlIiwiZ3R5IjoicGFzc3dvcmQifQ.qBiG7BUaHZJuRIcb5zVgE9xQzwOJg71dCmvdnemG1efIgS_kDHZzS9RQE8IZUuIPIlG6K1uNWOuEVdlxmwBKatfmbUzD3yzsEzft8Q9p27YfvLo2yjLLpUa-7nQMOsAfKvE-xm1hZN5sQfEakzUWycXt4BQqmTgTtH5vRZh6UuJzFv5N84sPZCyjSnI6v3qzGe9mHmyPXueKeem1yPLPxvqryX3j2ZzvmBX51WR3jWfSKgKKBG9d2M_O6hHmeu7FKuoGoDxmzW-s12KuWuC_G588ZeZ6kLxzMdF8oXdv_YJza9S65Yqgo0R7XAN6Y6gGL2JjTvaEMpQJU4VvRjPXhQ",
"expires_in": 86400,
"id_token": "mock_token",
"scope": "openid email profile",
"token_type": "Bearer"
}
Now, you can use access_token
as a JWT Token for your Backend Server and your user information will be protected by Auth0.
This story is too long as I expected, so we will discuss the rest in another story that will consider about JWT Middleware, User Utilities provided by Auth0.
Conclusion
I want to use the Conclusion to mention about Auth0 Prod and Cons. Not my own, but I found an opinion on the trustradius.com. In my point, I agree and think it is enough for us. You can see the detail here.
Finally, this is all code that I wrote through this story. You only need to copy code into main.go
, then go mod vendor
and go run main.go
to start the server.
Ah! One more thing. This is not the best practice, just my experience. Please correct me if have any problem in my opinion.
Wish you have a nice working day.