SlideShare a Scribd company logo
How to Implement
Golang JWT
Authentication and
Authorization
www.bacancytechnology.com
What is JSON Web Token?
How does JSON Web Token look like?
What does JSON Web Token
comprise?
Table of Content
1. Introduction
2. Exploring JSON Web Token
3. Implementing Golang JWT
Authentication and Authorization
4. Conclusion
Introduction
Would you let anyone enter your
house without knowing the person’s
identity? The answer would be –
Obviously No! So, we have the same
scenario with our web applications
too. It’s necessary to authenticate a
user’s identity before making requests
using APIs. And this authentication
takes place with the help of JWT .i.e.,
JSON Web Token. Now you might
wonder what is JWT in Golang and JWT
authentication. Don’t panic if you are
unaware of how to implement Golang
JWT authentication. Here’s a tutorial
where I will make you understand how
to implement Golang JWT
Authentication and Authorization. So
let’s get started.
Exploring JSON
Web Token
Under this section, we will
comprehensively understand what is JWT,
how does JSON Web token look like, and
what JSON web token consists of.
What is a JSON
Web Token?
A JWT token is a cryptographically
signed token which the server
generates and gives to the client. The
client uses JWT for making various
requests to the server. The token can
be signed using two algorithms:
HMAC or SHA256. SHA256 hashes the
message without the need of any
external input. It guarantees only
message integrity.
HMAC needs a private key in order to
hash the message. It guarantees
message integrity and authentication.
How Does a JSON
Web Token look
like?
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1
c2VyaWQiOiIxZGQ5MDEwYy00MzI4LTRoZj
NiOWU2LTc3N2Q4NDhlOTM3NSIsImF1dGhv
cml6ZWQiOmZhbHNlfQ.vI7thh64mzXp_WM
KZIedaKR4AF4trbvOHEpm2d62qIQ
The above token is invalid. It cannot be used
for production.
What comprises
a JSON Web
Token?
A JSON Web Token consists of three parts which are
separated using .(dot) :
Header: It indicates the token’s type it is and
which signing algorithm has been used.
Payload: It consists of the claims. And claims
comprise of application’s data( email id,
username, role), the expiration period of a
token (Exp), and so on.
Signature: It is generated using the secret
(provided by the user), encoded header, and
payload.
We can set the expiration period for any JSON
Web Token. Here in this application, we will
consider Access Token and Refresh Token.
Let’s see the difference.
To test the token, you can go to
https://jwt.io/.
Access Token: An access token is used for
authenticating the requests sent to the
server. We add the access token in the header
of the request. It is recommended that an
access token should have a short lifespan (say
15 minutes) for security purposes. Giving an
access token for a brief period can prevent
severe damages.
Refresh Token: A refresh token has a longer
lifespan( usually 7 days) compared to an
access token. Whenever an access token is
expired, the refresh token allows generating a
new access token without letting the user
know.
Implementing
Golang JWT
Authentication
and
Authorization
Follow these steps for Golang JWT
Authentication and Authorization-
Create a directory
Create a directory called jwt-practice.
mkdir jwt-practice
cd jwt-practice
Initializing with go.mod
Initialize it with go.mod, for
dependency management, using
–
go mod init jwt-practice
Create a main.go
Create a main.go file in the root directory of
the project. For simplicity, I will the entire
code in main.go
Copy and paste the following code snippets,
which I will show you in the coming steps.
func main() {
}
mux for routing and handling HTTP
requests
GORM as ORM tool
crypto for password hashing
Postgres for the database
Downloading dependencies
Next, we will download the required
dependencies.
We will use
$ go get github.com/gorilla/mux
$ go get github.com/jinzhu/gorm
$ go get github.com/lib/pq
$ go get golang.org/x/crypto/bcrypt
Downloading jwt-package
Download the jwt package using this command-
go get github.com/dgrijalva/jwt-go
Create Router and initialize the routes
In this step, we will create a router and
initialize routes. Add this code in your
main.go
var router *mux.Router
func CreateRouter() {
router = mux.NewRouter()
}
func InitializeRoute() {
router.HandleFunc("/signup",
SignUp).Methods("POST")
router.HandleFunc("/signin",
SignIn).Methods("POST")
}
func main() {
CreateRouter()
InitializeRoute()
}
Create some Structures
Let’s get our hands on to create some structs.
type User struct {
gorm.Model
Name string `json:"name"`
Email string `gorm:"unique" json:"email"`
Password string `json:"password"`
Role string `json:"role"`
}
type Authentication struct {
Email string `json:"email"`
Password string `json:"password"`
}
type Token struct {
Role string `json:"role"`
Email string `json:"email"`
TokenString string `json:"token"`
}
User is for storing User details.
Authentication is for login data.
Token is for storing token information for
correct login credentials.
Connecting to Database
The best practice would be to add the
code related to the Database connection
to your .env file but for simplicity
purpose, I have implemented it in
main.go itself.
As said before, I’ll be using the Postgres
database. Add the following code to
establish a database connection.
func GetDatabase() *gorm.DB {
databasename := "userdb"
database := "postgres"
databasepassword := "1312"
databaseurl := "postgres://postgres:" +
databasepassword + "@localhost/" +
databasename + "?sslmode=disable"
connection, err := gorm.Open(database,
databaseurl)
if err != nil {
log.Fatalln("wrong database url")
}
sqldb := connection.DB()
err = sqldb.Ping()
if err != nil {
log.Fatal("database connected")
}
fmt.Println("connected to database")
return connection
}
func InitialMigration() {
connection := GetDatabase()
defer Closedatabase(connection)
connection.AutoMigrate(User{})
}
func Closedatabase(connection *gorm.DB) {
sqldb := connection.DB()
sqldb.Close()
}
Sign Up process
The SignUp function opens the database
connection, receives user data from the form, and
checks if the user already exists in the database or
not. If the user is already present in the database, it
returns an error, otherwise hash the user password
and creates a new database entry. Copy-paste the
below-mentioned code in your file.
func SignUp(w http.ResponseWriter, r
*http.Request) {
connection := GetDatabase()
defer Closedatabase(connection)
var user User
err :=
json.NewDecoder(r.Body).Decode(&user)
if err != nil {
var err Error
err = SetError(err, "Error in reading body")
w.Header().Set("Content-Type",
"application/json")
json.NewEncoder(w).Encode(err)
return
}
var dbuser User
connection.Where("email = ?",
user.Email).First(&dbuser)
//checks if email is already register or not
if dbuser.Email != "" {
var err Error
err = SetError(err, "Email already in use")
w.Header().Set("Content-Type",
"application/json")
json.NewEncoder(w).Encode(err)
return
}
user.Password, err =
GeneratehashPassword(user.Password)
if err != nil {
log.Fatalln("error in password hash")
}
//insert user details in database
connection.Create(&user)
w.Header().Set("Content-Type",
"application/json")
json.NewEncoder(w).Encode(user)
}
Use GeneratehashPassword for hashing the
password.
func GeneratehashPassword(password
string) (string, error) {
bytes, err :=
bcrypt.GenerateFromPassword([]byte(
password), 14)
return string(bytes), err
}
So, we are done with the fundamental
set up in our main. go. It’s time to start
coding for the Authentication and
Authorization part. But, before that let
me brief you regarding the difference
between the two processes.
Authentication vs Authorization
Authentication can be defined as validating
the users of any particular application. And
that’s why it is said to be the crucial and
foremost step in developing an application.
It directly concerns security issues.
Allowing someone to make a request to the
server is a basic example of authentication.
Authorization is a process of where the
user roles are being managed. It can be
briefed as giving a user some specific
permissions for accessing particular
resources.
First, we will begin the process of
authentication.
Generate JWT
Write the following function to create
Golang JWT:
The GenerateJWT() function takes email
and role as input. Creates a token by
HS256 signing method and adds
authorized email, role, and exp into
claims. Claims are pieces of information
added into tokens.
func GenerateJWT(email, role string)
(string, error) {
var mySigningKey = []byte(secretkey)
token :=
jwt.New(jwt.SigningMethodHS256)
claims := token.Claims.(jwt.MapClaims)
claims["authorized"] = true
claims["email"] = email
claims["role"] = role
claims["exp"] =
time.Now().Add(time.Minute * 30).Unix()
tokenString, err :=
token.SignedString(mySigningKey)
if err != nil {
fmt.Errorf("Something Went Wrong: %s",
err.Error())
return "", err
}
return tokenString, nil
}
Sign In Process
The SignIn function checks if the user is already
present in the database. If the user is not present,
then redirect the user to the login page. If the user
is present in the database, then hash the password
the user gave in the login form and compare that
hashed password with the stored hashed password.
If both the hashed passwords are the same, then
generate a new Golang JWT authentication and give
it back to the user or redirect the user to the login
page.
func SignIn(w http.ResponseWriter, r
*http.Request) {
connection := GetDatabase()
defer Closedatabase(connection)
var authdetails Authentication
err :=
json.NewDecoder(r.Body).Decode(&authd
etails)
if err != nil {
var err Error
err = SetError(err, "Error in reading body")
w.Header().Set("Content-Type",
"application/json")
json.NewEncoder(w).Encode(err)
return
}
var authuser User
connection.Where("email = ?",
authdetails.Email).First(&authuser)
if authuser.Email == "" {
var err Error
err = SetError(err, "Username or
Password is incorrect")
w.Header().Set("Content-Type",
"application/json")
json.NewEncoder(w).Encode(err)
return
}
check :=
CheckPasswordHash(authdetails.Passwor
d, authuser.Password)
if !check {
var err Error
err = SetError(err, "Username or Password
is incorrect")
w.Header().Set("Content-Type",
"application/json")
json.NewEncoder(w).Encode(err)
return
}
validToken, err :=
GenerateJWT(authuser.Email,
authuser.Role)
if err != nil {
var err Error
err = SetError(err, "Failed to generate
token")
w.Header().Set("Content-Type",
"application/json")
json.NewEncoder(w).Encode(err)
return
}
var token Token
token.Email = authuser.Email
token.Role = authuser.Role
token.TokenString = validToken
w.Header().Set("Content-Type",
"application/json")
json.NewEncoder(w).Encode(token)
}
CheckPasswordHash() function compares the
plain password with a hashed password.
func CheckPasswordHash(password, hash
string) bool {
err :=
bcrypt.CompareHashAndPassword([]byte
(hash), []byte(password))
return err == nil
}
Now let’s start the process of authorization.
Writing MiddleWare function
IsAuthorized() function verifies the token,
and if the token is valid, it will extract the
role from the token. And based on the role,
the user will be redirected to the appropriate
page.
There are two roles: Admin and User.
Now, finally, it’s time to write the
middleware function. Copy-paste the below-
mentioned code.
func IsAuthorized(handler
http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r
*http.Request) {
if r.Header["Token"] == nil {
var err Error
err = SetError(err, "No Token Found")
json.NewEncoder(w).Encode(err)
return
}
var mySigningKey = []byte(secretkey)
token, err := jwt.Parse(r.Header["Token"][0],
func(token *jwt.Token) (interface{}, error) {
if _, ok := token.Method.
(*jwt.SigningMethodHMAC); !ok {
return nil, fmt.Errorf("There was an error in
parsing")
}
return mySigningKey, nil
})
if err != nil {
var err Error
err = SetError(err, "Your Token has been
expired")
json.NewEncoder(w).Encode(err)
return
}
if claims, ok := token.Claims.
(jwt.MapClaims); ok && token.Valid {
if claims["role"] == "admin" {
r.Header.Set("Role", "admin")
handler.ServeHTTP(w, r)
return
} else if claims["role"] == "user" {
r.Header.Set("Role", "user")
handler.ServeHTTP(w, r)
return
}
}
var reserr Error
reserr = SetError(reserr, "Not
Authorized")
json.NewEncoder(w).Encode(err)
}
}
Source code for the entire demo application is
here – Github Repository
Verifying Golang JWT
After all the coding, let’s verify whether the
Golang JWT authentication is working as
expected.
Thus, you are done with generating the Golang
JWT. Further, for your frontend side, you can
store this token in your local storage and use it
in different API requests. Refer to the below
images-
(1) Signed In successfully and receiving Golang
JWT in the response. You can see the “role”:
“user” which satisfies the authorization part. It
means that only specific resources will be
accessible to the user role.
(2) Storing Golang JWT in the local storage so
that you can use this token for different API
calls.
Conclusion
I hope this blog has helped you with Golang
JWT Authentication and Authorization. The
process of authentication and authorization
is crucial step for developing any web
application. If you are looking for a helping
hand to implement Golang JWT, then hire
Golang developer to leverage our top-of-
the-line Golang development expertise.
Thank You
www.bacancytechnology.com

More Related Content

What's hot

HtmlElements – естественное расширение PageObject
HtmlElements – естественное расширение PageObjectHtmlElements – естественное расширение PageObject
HtmlElements – естественное расширение PageObject
SQALab
 
JSON-(JavaScript Object Notation)
JSON-(JavaScript Object Notation)JSON-(JavaScript Object Notation)
JSON-(JavaScript Object Notation)
Skillwise Group
 
DOM and Events
DOM and EventsDOM and Events
DOM and Events
Julie Iskander
 
AJAX
AJAXAJAX
Lesson 202 02 oct13-1800-ay
Lesson 202 02 oct13-1800-ayLesson 202 02 oct13-1800-ay
Lesson 202 02 oct13-1800-ay
Codecademy Ren
 
J2EE jsp_03
J2EE jsp_03J2EE jsp_03
J2EE jsp_03
Biswabrata Banerjee
 
How to build twitter bot using golang from scratch
How to build twitter bot using golang from scratchHow to build twitter bot using golang from scratch
How to build twitter bot using golang from scratch
Katy Slemon
 
Java Svet - Communication Between Android App Components
Java Svet - Communication Between Android App ComponentsJava Svet - Communication Between Android App Components
Java Svet - Communication Between Android App Components
Aleksandar Ilić
 
[DSBW Spring 2009] Unit 07: WebApp Design Patterns & Frameworks (3/3)
[DSBW Spring 2009] Unit 07: WebApp Design Patterns & Frameworks (3/3)[DSBW Spring 2009] Unit 07: WebApp Design Patterns & Frameworks (3/3)
[DSBW Spring 2009] Unit 07: WebApp Design Patterns & Frameworks (3/3)
Carles Farré
 
Dojo1.0_Tutorials
Dojo1.0_TutorialsDojo1.0_Tutorials
Dojo1.0_Tutorials
tutorialsruby
 
Il n'y a pas que Polymer dans la vie… - RennesJS - 2017-06-27
Il n'y a pas que Polymer dans la vie… - RennesJS - 2017-06-27Il n'y a pas que Polymer dans la vie… - RennesJS - 2017-06-27
Il n'y a pas que Polymer dans la vie… - RennesJS - 2017-06-27
Horacio Gonzalez
 
Spring Data JPA from 0-100 in 60 minutes
Spring Data JPA from 0-100 in 60 minutesSpring Data JPA from 0-100 in 60 minutes
Spring Data JPA from 0-100 in 60 minutes
VMware Tanzu
 
Event handling using jQuery
Event handling using jQueryEvent handling using jQuery
Event handling using jQuery
Iban Martinez
 
Java Development with MongoDB
Java Development with MongoDBJava Development with MongoDB
Java Development with MongoDB
Scott Hernandez
 
Integrating services with OAuth
Integrating services with OAuthIntegrating services with OAuth
Integrating services with OAuth
Luca Mearelli
 
Struts 2 + Spring
Struts 2 + SpringStruts 2 + Spring
Struts 2 + Spring
Bryan Hsueh
 

What's hot (16)

HtmlElements – естественное расширение PageObject
HtmlElements – естественное расширение PageObjectHtmlElements – естественное расширение PageObject
HtmlElements – естественное расширение PageObject
 
JSON-(JavaScript Object Notation)
JSON-(JavaScript Object Notation)JSON-(JavaScript Object Notation)
JSON-(JavaScript Object Notation)
 
DOM and Events
DOM and EventsDOM and Events
DOM and Events
 
AJAX
AJAXAJAX
AJAX
 
Lesson 202 02 oct13-1800-ay
Lesson 202 02 oct13-1800-ayLesson 202 02 oct13-1800-ay
Lesson 202 02 oct13-1800-ay
 
J2EE jsp_03
J2EE jsp_03J2EE jsp_03
J2EE jsp_03
 
How to build twitter bot using golang from scratch
How to build twitter bot using golang from scratchHow to build twitter bot using golang from scratch
How to build twitter bot using golang from scratch
 
Java Svet - Communication Between Android App Components
Java Svet - Communication Between Android App ComponentsJava Svet - Communication Between Android App Components
Java Svet - Communication Between Android App Components
 
[DSBW Spring 2009] Unit 07: WebApp Design Patterns & Frameworks (3/3)
[DSBW Spring 2009] Unit 07: WebApp Design Patterns & Frameworks (3/3)[DSBW Spring 2009] Unit 07: WebApp Design Patterns & Frameworks (3/3)
[DSBW Spring 2009] Unit 07: WebApp Design Patterns & Frameworks (3/3)
 
Dojo1.0_Tutorials
Dojo1.0_TutorialsDojo1.0_Tutorials
Dojo1.0_Tutorials
 
Il n'y a pas que Polymer dans la vie… - RennesJS - 2017-06-27
Il n'y a pas que Polymer dans la vie… - RennesJS - 2017-06-27Il n'y a pas que Polymer dans la vie… - RennesJS - 2017-06-27
Il n'y a pas que Polymer dans la vie… - RennesJS - 2017-06-27
 
Spring Data JPA from 0-100 in 60 minutes
Spring Data JPA from 0-100 in 60 minutesSpring Data JPA from 0-100 in 60 minutes
Spring Data JPA from 0-100 in 60 minutes
 
Event handling using jQuery
Event handling using jQueryEvent handling using jQuery
Event handling using jQuery
 
Java Development with MongoDB
Java Development with MongoDBJava Development with MongoDB
Java Development with MongoDB
 
Integrating services with OAuth
Integrating services with OAuthIntegrating services with OAuth
Integrating services with OAuth
 
Struts 2 + Spring
Struts 2 + SpringStruts 2 + Spring
Struts 2 + Spring
 

Similar to How to implement golang jwt authentication and authorization

Nk API - examples
Nk API - examplesNk API - examples
Nk API - examples
nasza-klasa
 
Ajax for dummies, and not only.
Ajax for dummies, and not only.Ajax for dummies, and not only.
Ajax for dummies, and not only.
Nerd Tzanetopoulos
 
Android ui layouts ,cntls,webservices examples codes
Android ui layouts ,cntls,webservices examples codesAndroid ui layouts ,cntls,webservices examples codes
Android ui layouts ,cntls,webservices examples codes
Aravindharamanan S
 
MongoDB Stitch Tutorial
MongoDB Stitch TutorialMongoDB Stitch Tutorial
MongoDB Stitch Tutorial
MongoDB
 
Intoduction to Play Framework
Intoduction to Play FrameworkIntoduction to Play Framework
Intoduction to Play Framework
Knoldus Inc.
 
huhu
huhuhuhu
Geb qa fest2017
Geb qa fest2017Geb qa fest2017
Geb qa fest2017
Sviatkin Yaroslav
 
Cross Domain Web
Mashups with JQuery and Google App Engine
Cross Domain Web
Mashups with JQuery and Google App EngineCross Domain Web
Mashups with JQuery and Google App Engine
Cross Domain Web
Mashups with JQuery and Google App Engine
Andy McKay
 
2016 pycontw web api authentication
2016 pycontw web api authentication 2016 pycontw web api authentication
2016 pycontw web api authentication
Micron Technology
 
5 easy steps to understanding json web tokens (jwt)
5 easy steps to understanding json web tokens (jwt)5 easy steps to understanding json web tokens (jwt)
5 easy steps to understanding json web tokens (jwt)
Amit Gupta
 
Building an api using golang and postgre sql v1.0
Building an api using golang and postgre sql v1.0Building an api using golang and postgre sql v1.0
Building an api using golang and postgre sql v1.0
Frost
 
[CB16] Esoteric Web Application Vulnerabilities by Andrés Riancho
[CB16] Esoteric Web Application Vulnerabilities by Andrés Riancho[CB16] Esoteric Web Application Vulnerabilities by Andrés Riancho
[CB16] Esoteric Web Application Vulnerabilities by Andrés Riancho
CODE BLUE
 
ajax_pdf
ajax_pdfajax_pdf
ajax_pdf
tutorialsruby
 
ajax_pdf
ajax_pdfajax_pdf
ajax_pdf
tutorialsruby
 
Category theory, Monads, and Duality in the world of (BIG) Data
Category theory, Monads, and Duality in the world of (BIG) DataCategory theory, Monads, and Duality in the world of (BIG) Data
Category theory, Monads, and Duality in the world of (BIG) Data
greenwop
 
Php & Web Security - PHPXperts 2009
Php & Web Security - PHPXperts 2009Php & Web Security - PHPXperts 2009
Php & Web Security - PHPXperts 2009
mirahman
 
Pascarello_Investigating JavaScript and Ajax Security
Pascarello_Investigating JavaScript and Ajax SecurityPascarello_Investigating JavaScript and Ajax Security
Pascarello_Investigating JavaScript and Ajax Security
amiable_indian
 
GDG Cloud Taipei: Meetup #52 - Istio Security: API Authorization
GDG Cloud Taipei: Meetup #52 - Istio Security: API AuthorizationGDG Cloud Taipei: Meetup #52 - Istio Security: API Authorization
GDG Cloud Taipei: Meetup #52 - Istio Security: API Authorization
KAI CHU CHUNG
 
Landscape
LandscapeLandscape
Landscape
Amit Gupta
 
How to Develop Slack Bot Using Golang.pdf
How to Develop Slack Bot Using Golang.pdfHow to Develop Slack Bot Using Golang.pdf
How to Develop Slack Bot Using Golang.pdf
Katy Slemon
 

Similar to How to implement golang jwt authentication and authorization (20)

Nk API - examples
Nk API - examplesNk API - examples
Nk API - examples
 
Ajax for dummies, and not only.
Ajax for dummies, and not only.Ajax for dummies, and not only.
Ajax for dummies, and not only.
 
Android ui layouts ,cntls,webservices examples codes
Android ui layouts ,cntls,webservices examples codesAndroid ui layouts ,cntls,webservices examples codes
Android ui layouts ,cntls,webservices examples codes
 
MongoDB Stitch Tutorial
MongoDB Stitch TutorialMongoDB Stitch Tutorial
MongoDB Stitch Tutorial
 
Intoduction to Play Framework
Intoduction to Play FrameworkIntoduction to Play Framework
Intoduction to Play Framework
 
huhu
huhuhuhu
huhu
 
Geb qa fest2017
Geb qa fest2017Geb qa fest2017
Geb qa fest2017
 
Cross Domain Web
Mashups with JQuery and Google App Engine
Cross Domain Web
Mashups with JQuery and Google App EngineCross Domain Web
Mashups with JQuery and Google App Engine
Cross Domain Web
Mashups with JQuery and Google App Engine
 
2016 pycontw web api authentication
2016 pycontw web api authentication 2016 pycontw web api authentication
2016 pycontw web api authentication
 
5 easy steps to understanding json web tokens (jwt)
5 easy steps to understanding json web tokens (jwt)5 easy steps to understanding json web tokens (jwt)
5 easy steps to understanding json web tokens (jwt)
 
Building an api using golang and postgre sql v1.0
Building an api using golang and postgre sql v1.0Building an api using golang and postgre sql v1.0
Building an api using golang and postgre sql v1.0
 
[CB16] Esoteric Web Application Vulnerabilities by Andrés Riancho
[CB16] Esoteric Web Application Vulnerabilities by Andrés Riancho[CB16] Esoteric Web Application Vulnerabilities by Andrés Riancho
[CB16] Esoteric Web Application Vulnerabilities by Andrés Riancho
 
ajax_pdf
ajax_pdfajax_pdf
ajax_pdf
 
ajax_pdf
ajax_pdfajax_pdf
ajax_pdf
 
Category theory, Monads, and Duality in the world of (BIG) Data
Category theory, Monads, and Duality in the world of (BIG) DataCategory theory, Monads, and Duality in the world of (BIG) Data
Category theory, Monads, and Duality in the world of (BIG) Data
 
Php & Web Security - PHPXperts 2009
Php & Web Security - PHPXperts 2009Php & Web Security - PHPXperts 2009
Php & Web Security - PHPXperts 2009
 
Pascarello_Investigating JavaScript and Ajax Security
Pascarello_Investigating JavaScript and Ajax SecurityPascarello_Investigating JavaScript and Ajax Security
Pascarello_Investigating JavaScript and Ajax Security
 
GDG Cloud Taipei: Meetup #52 - Istio Security: API Authorization
GDG Cloud Taipei: Meetup #52 - Istio Security: API AuthorizationGDG Cloud Taipei: Meetup #52 - Istio Security: API Authorization
GDG Cloud Taipei: Meetup #52 - Istio Security: API Authorization
 
Landscape
LandscapeLandscape
Landscape
 
How to Develop Slack Bot Using Golang.pdf
How to Develop Slack Bot Using Golang.pdfHow to Develop Slack Bot Using Golang.pdf
How to Develop Slack Bot Using Golang.pdf
 

More from Katy Slemon

React Alternatives Frameworks- Lightweight Javascript Libraries.pdf
React Alternatives Frameworks- Lightweight Javascript Libraries.pdfReact Alternatives Frameworks- Lightweight Javascript Libraries.pdf
React Alternatives Frameworks- Lightweight Javascript Libraries.pdf
Katy Slemon
 
Data Science Use Cases in Retail & Healthcare Industries.pdf
Data Science Use Cases in Retail & Healthcare Industries.pdfData Science Use Cases in Retail & Healthcare Industries.pdf
Data Science Use Cases in Retail & Healthcare Industries.pdf
Katy Slemon
 
How Much Does It Cost To Hire Golang Developer.pdf
How Much Does It Cost To Hire Golang Developer.pdfHow Much Does It Cost To Hire Golang Developer.pdf
How Much Does It Cost To Hire Golang Developer.pdf
Katy Slemon
 
What’s New in Flutter 3.pdf
What’s New in Flutter 3.pdfWhat’s New in Flutter 3.pdf
What’s New in Flutter 3.pdf
Katy Slemon
 
Why Use Ruby On Rails.pdf
Why Use Ruby On Rails.pdfWhy Use Ruby On Rails.pdf
Why Use Ruby On Rails.pdf
Katy Slemon
 
How Much Does It Cost To Hire Full Stack Developer In 2022.pdf
How Much Does It Cost To Hire Full Stack Developer In 2022.pdfHow Much Does It Cost To Hire Full Stack Developer In 2022.pdf
How Much Does It Cost To Hire Full Stack Developer In 2022.pdf
Katy Slemon
 
How to Implement Middleware Pipeline in VueJS.pdf
How to Implement Middleware Pipeline in VueJS.pdfHow to Implement Middleware Pipeline in VueJS.pdf
How to Implement Middleware Pipeline in VueJS.pdf
Katy Slemon
 
How to Build Laravel Package Using Composer.pdf
How to Build Laravel Package Using Composer.pdfHow to Build Laravel Package Using Composer.pdf
How to Build Laravel Package Using Composer.pdf
Katy Slemon
 
Sure Shot Ways To Improve And Scale Your Node js Performance.pdf
Sure Shot Ways To Improve And Scale Your Node js Performance.pdfSure Shot Ways To Improve And Scale Your Node js Performance.pdf
Sure Shot Ways To Improve And Scale Your Node js Performance.pdf
Katy Slemon
 
IoT Based Battery Management System in Electric Vehicles.pdf
IoT Based Battery Management System in Electric Vehicles.pdfIoT Based Battery Management System in Electric Vehicles.pdf
IoT Based Battery Management System in Electric Vehicles.pdf
Katy Slemon
 
Understanding Flexbox Layout in React Native.pdf
Understanding Flexbox Layout in React Native.pdfUnderstanding Flexbox Layout in React Native.pdf
Understanding Flexbox Layout in React Native.pdf
Katy Slemon
 
The Ultimate Guide to Laravel Performance Optimization in 2022.pdf
The Ultimate Guide to Laravel Performance Optimization in 2022.pdfThe Ultimate Guide to Laravel Performance Optimization in 2022.pdf
The Ultimate Guide to Laravel Performance Optimization in 2022.pdf
Katy Slemon
 
New Features in iOS 15 and Swift 5.5.pdf
New Features in iOS 15 and Swift 5.5.pdfNew Features in iOS 15 and Swift 5.5.pdf
New Features in iOS 15 and Swift 5.5.pdf
Katy Slemon
 
How to Hire & Manage Dedicated Team For Your Next Product Development.pdf
How to Hire & Manage Dedicated Team For Your Next Product Development.pdfHow to Hire & Manage Dedicated Team For Your Next Product Development.pdf
How to Hire & Manage Dedicated Team For Your Next Product Development.pdf
Katy Slemon
 
Choose the Right Battery Management System for Lithium Ion Batteries.pdf
Choose the Right Battery Management System for Lithium Ion Batteries.pdfChoose the Right Battery Management System for Lithium Ion Batteries.pdf
Choose the Right Battery Management System for Lithium Ion Batteries.pdf
Katy Slemon
 
Flutter Performance Tuning Best Practices From the Pros.pdf
Flutter Performance Tuning Best Practices From the Pros.pdfFlutter Performance Tuning Best Practices From the Pros.pdf
Flutter Performance Tuning Best Practices From the Pros.pdf
Katy Slemon
 
Angular Universal How to Build Angular SEO Friendly App.pdf
Angular Universal How to Build Angular SEO Friendly App.pdfAngular Universal How to Build Angular SEO Friendly App.pdf
Angular Universal How to Build Angular SEO Friendly App.pdf
Katy Slemon
 
How to Set Up and Send Mails Using SendGrid in NodeJs App.pdf
How to Set Up and Send Mails Using SendGrid in NodeJs App.pdfHow to Set Up and Send Mails Using SendGrid in NodeJs App.pdf
How to Set Up and Send Mails Using SendGrid in NodeJs App.pdf
Katy Slemon
 
Ruby On Rails Performance Tuning Guide.pdf
Ruby On Rails Performance Tuning Guide.pdfRuby On Rails Performance Tuning Guide.pdf
Ruby On Rails Performance Tuning Guide.pdf
Katy Slemon
 
Uncovering 04 Main Types and Benefits of Salesforce ISV Partnerships.pdf
Uncovering 04 Main Types and Benefits of Salesforce ISV Partnerships.pdfUncovering 04 Main Types and Benefits of Salesforce ISV Partnerships.pdf
Uncovering 04 Main Types and Benefits of Salesforce ISV Partnerships.pdf
Katy Slemon
 

More from Katy Slemon (20)

React Alternatives Frameworks- Lightweight Javascript Libraries.pdf
React Alternatives Frameworks- Lightweight Javascript Libraries.pdfReact Alternatives Frameworks- Lightweight Javascript Libraries.pdf
React Alternatives Frameworks- Lightweight Javascript Libraries.pdf
 
Data Science Use Cases in Retail & Healthcare Industries.pdf
Data Science Use Cases in Retail & Healthcare Industries.pdfData Science Use Cases in Retail & Healthcare Industries.pdf
Data Science Use Cases in Retail & Healthcare Industries.pdf
 
How Much Does It Cost To Hire Golang Developer.pdf
How Much Does It Cost To Hire Golang Developer.pdfHow Much Does It Cost To Hire Golang Developer.pdf
How Much Does It Cost To Hire Golang Developer.pdf
 
What’s New in Flutter 3.pdf
What’s New in Flutter 3.pdfWhat’s New in Flutter 3.pdf
What’s New in Flutter 3.pdf
 
Why Use Ruby On Rails.pdf
Why Use Ruby On Rails.pdfWhy Use Ruby On Rails.pdf
Why Use Ruby On Rails.pdf
 
How Much Does It Cost To Hire Full Stack Developer In 2022.pdf
How Much Does It Cost To Hire Full Stack Developer In 2022.pdfHow Much Does It Cost To Hire Full Stack Developer In 2022.pdf
How Much Does It Cost To Hire Full Stack Developer In 2022.pdf
 
How to Implement Middleware Pipeline in VueJS.pdf
How to Implement Middleware Pipeline in VueJS.pdfHow to Implement Middleware Pipeline in VueJS.pdf
How to Implement Middleware Pipeline in VueJS.pdf
 
How to Build Laravel Package Using Composer.pdf
How to Build Laravel Package Using Composer.pdfHow to Build Laravel Package Using Composer.pdf
How to Build Laravel Package Using Composer.pdf
 
Sure Shot Ways To Improve And Scale Your Node js Performance.pdf
Sure Shot Ways To Improve And Scale Your Node js Performance.pdfSure Shot Ways To Improve And Scale Your Node js Performance.pdf
Sure Shot Ways To Improve And Scale Your Node js Performance.pdf
 
IoT Based Battery Management System in Electric Vehicles.pdf
IoT Based Battery Management System in Electric Vehicles.pdfIoT Based Battery Management System in Electric Vehicles.pdf
IoT Based Battery Management System in Electric Vehicles.pdf
 
Understanding Flexbox Layout in React Native.pdf
Understanding Flexbox Layout in React Native.pdfUnderstanding Flexbox Layout in React Native.pdf
Understanding Flexbox Layout in React Native.pdf
 
The Ultimate Guide to Laravel Performance Optimization in 2022.pdf
The Ultimate Guide to Laravel Performance Optimization in 2022.pdfThe Ultimate Guide to Laravel Performance Optimization in 2022.pdf
The Ultimate Guide to Laravel Performance Optimization in 2022.pdf
 
New Features in iOS 15 and Swift 5.5.pdf
New Features in iOS 15 and Swift 5.5.pdfNew Features in iOS 15 and Swift 5.5.pdf
New Features in iOS 15 and Swift 5.5.pdf
 
How to Hire & Manage Dedicated Team For Your Next Product Development.pdf
How to Hire & Manage Dedicated Team For Your Next Product Development.pdfHow to Hire & Manage Dedicated Team For Your Next Product Development.pdf
How to Hire & Manage Dedicated Team For Your Next Product Development.pdf
 
Choose the Right Battery Management System for Lithium Ion Batteries.pdf
Choose the Right Battery Management System for Lithium Ion Batteries.pdfChoose the Right Battery Management System for Lithium Ion Batteries.pdf
Choose the Right Battery Management System for Lithium Ion Batteries.pdf
 
Flutter Performance Tuning Best Practices From the Pros.pdf
Flutter Performance Tuning Best Practices From the Pros.pdfFlutter Performance Tuning Best Practices From the Pros.pdf
Flutter Performance Tuning Best Practices From the Pros.pdf
 
Angular Universal How to Build Angular SEO Friendly App.pdf
Angular Universal How to Build Angular SEO Friendly App.pdfAngular Universal How to Build Angular SEO Friendly App.pdf
Angular Universal How to Build Angular SEO Friendly App.pdf
 
How to Set Up and Send Mails Using SendGrid in NodeJs App.pdf
How to Set Up and Send Mails Using SendGrid in NodeJs App.pdfHow to Set Up and Send Mails Using SendGrid in NodeJs App.pdf
How to Set Up and Send Mails Using SendGrid in NodeJs App.pdf
 
Ruby On Rails Performance Tuning Guide.pdf
Ruby On Rails Performance Tuning Guide.pdfRuby On Rails Performance Tuning Guide.pdf
Ruby On Rails Performance Tuning Guide.pdf
 
Uncovering 04 Main Types and Benefits of Salesforce ISV Partnerships.pdf
Uncovering 04 Main Types and Benefits of Salesforce ISV Partnerships.pdfUncovering 04 Main Types and Benefits of Salesforce ISV Partnerships.pdf
Uncovering 04 Main Types and Benefits of Salesforce ISV Partnerships.pdf
 

Recently uploaded

Serial Arm Control in Real Time Presentation
Serial Arm Control in Real Time PresentationSerial Arm Control in Real Time Presentation
Serial Arm Control in Real Time Presentation
tolgahangng
 
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAUHCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
panagenda
 
Fueling AI with Great Data with Airbyte Webinar
Fueling AI with Great Data with Airbyte WebinarFueling AI with Great Data with Airbyte Webinar
Fueling AI with Great Data with Airbyte Webinar
Zilliz
 
TrustArc Webinar - 2024 Global Privacy Survey
TrustArc Webinar - 2024 Global Privacy SurveyTrustArc Webinar - 2024 Global Privacy Survey
TrustArc Webinar - 2024 Global Privacy Survey
TrustArc
 
Energy Efficient Video Encoding for Cloud and Edge Computing Instances
Energy Efficient Video Encoding for Cloud and Edge Computing InstancesEnergy Efficient Video Encoding for Cloud and Edge Computing Instances
Energy Efficient Video Encoding for Cloud and Edge Computing Instances
Alpen-Adria-Universität
 
Ocean lotus Threat actors project by John Sitima 2024 (1).pptx
Ocean lotus Threat actors project by John Sitima 2024 (1).pptxOcean lotus Threat actors project by John Sitima 2024 (1).pptx
Ocean lotus Threat actors project by John Sitima 2024 (1).pptx
SitimaJohn
 
Columbus Data & Analytics Wednesdays - June 2024
Columbus Data & Analytics Wednesdays - June 2024Columbus Data & Analytics Wednesdays - June 2024
Columbus Data & Analytics Wednesdays - June 2024
Jason Packer
 
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdfUnlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
Malak Abu Hammad
 
National Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practicesNational Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practices
Quotidiano Piemontese
 
Introduction of Cybersecurity with OSS at Code Europe 2024
Introduction of Cybersecurity with OSS  at Code Europe 2024Introduction of Cybersecurity with OSS  at Code Europe 2024
Introduction of Cybersecurity with OSS at Code Europe 2024
Hiroshi SHIBATA
 
Artificial Intelligence for XMLDevelopment
Artificial Intelligence for XMLDevelopmentArtificial Intelligence for XMLDevelopment
Artificial Intelligence for XMLDevelopment
Octavian Nadolu
 
Choosing The Best AWS Service For Your Website + API.pptx
Choosing The Best AWS Service For Your Website + API.pptxChoosing The Best AWS Service For Your Website + API.pptx
Choosing The Best AWS Service For Your Website + API.pptx
Brandon Minnick, MBA
 
GraphRAG for Life Science to increase LLM accuracy
GraphRAG for Life Science to increase LLM accuracyGraphRAG for Life Science to increase LLM accuracy
GraphRAG for Life Science to increase LLM accuracy
Tomaz Bratanic
 
UiPath Test Automation using UiPath Test Suite series, part 6
UiPath Test Automation using UiPath Test Suite series, part 6UiPath Test Automation using UiPath Test Suite series, part 6
UiPath Test Automation using UiPath Test Suite series, part 6
DianaGray10
 
Skybuffer SAM4U tool for SAP license adoption
Skybuffer SAM4U tool for SAP license adoptionSkybuffer SAM4U tool for SAP license adoption
Skybuffer SAM4U tool for SAP license adoption
Tatiana Kojar
 
Programming Foundation Models with DSPy - Meetup Slides
Programming Foundation Models with DSPy - Meetup SlidesProgramming Foundation Models with DSPy - Meetup Slides
Programming Foundation Models with DSPy - Meetup Slides
Zilliz
 
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with SlackLet's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
shyamraj55
 
Building Production Ready Search Pipelines with Spark and Milvus
Building Production Ready Search Pipelines with Spark and MilvusBuilding Production Ready Search Pipelines with Spark and Milvus
Building Production Ready Search Pipelines with Spark and Milvus
Zilliz
 
Digital Marketing Trends in 2024 | Guide for Staying Ahead
Digital Marketing Trends in 2024 | Guide for Staying AheadDigital Marketing Trends in 2024 | Guide for Staying Ahead
Digital Marketing Trends in 2024 | Guide for Staying Ahead
Wask
 
Generating privacy-protected synthetic data using Secludy and Milvus
Generating privacy-protected synthetic data using Secludy and MilvusGenerating privacy-protected synthetic data using Secludy and Milvus
Generating privacy-protected synthetic data using Secludy and Milvus
Zilliz
 

Recently uploaded (20)

Serial Arm Control in Real Time Presentation
Serial Arm Control in Real Time PresentationSerial Arm Control in Real Time Presentation
Serial Arm Control in Real Time Presentation
 
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAUHCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
 
Fueling AI with Great Data with Airbyte Webinar
Fueling AI with Great Data with Airbyte WebinarFueling AI with Great Data with Airbyte Webinar
Fueling AI with Great Data with Airbyte Webinar
 
TrustArc Webinar - 2024 Global Privacy Survey
TrustArc Webinar - 2024 Global Privacy SurveyTrustArc Webinar - 2024 Global Privacy Survey
TrustArc Webinar - 2024 Global Privacy Survey
 
Energy Efficient Video Encoding for Cloud and Edge Computing Instances
Energy Efficient Video Encoding for Cloud and Edge Computing InstancesEnergy Efficient Video Encoding for Cloud and Edge Computing Instances
Energy Efficient Video Encoding for Cloud and Edge Computing Instances
 
Ocean lotus Threat actors project by John Sitima 2024 (1).pptx
Ocean lotus Threat actors project by John Sitima 2024 (1).pptxOcean lotus Threat actors project by John Sitima 2024 (1).pptx
Ocean lotus Threat actors project by John Sitima 2024 (1).pptx
 
Columbus Data & Analytics Wednesdays - June 2024
Columbus Data & Analytics Wednesdays - June 2024Columbus Data & Analytics Wednesdays - June 2024
Columbus Data & Analytics Wednesdays - June 2024
 
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdfUnlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
 
National Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practicesNational Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practices
 
Introduction of Cybersecurity with OSS at Code Europe 2024
Introduction of Cybersecurity with OSS  at Code Europe 2024Introduction of Cybersecurity with OSS  at Code Europe 2024
Introduction of Cybersecurity with OSS at Code Europe 2024
 
Artificial Intelligence for XMLDevelopment
Artificial Intelligence for XMLDevelopmentArtificial Intelligence for XMLDevelopment
Artificial Intelligence for XMLDevelopment
 
Choosing The Best AWS Service For Your Website + API.pptx
Choosing The Best AWS Service For Your Website + API.pptxChoosing The Best AWS Service For Your Website + API.pptx
Choosing The Best AWS Service For Your Website + API.pptx
 
GraphRAG for Life Science to increase LLM accuracy
GraphRAG for Life Science to increase LLM accuracyGraphRAG for Life Science to increase LLM accuracy
GraphRAG for Life Science to increase LLM accuracy
 
UiPath Test Automation using UiPath Test Suite series, part 6
UiPath Test Automation using UiPath Test Suite series, part 6UiPath Test Automation using UiPath Test Suite series, part 6
UiPath Test Automation using UiPath Test Suite series, part 6
 
Skybuffer SAM4U tool for SAP license adoption
Skybuffer SAM4U tool for SAP license adoptionSkybuffer SAM4U tool for SAP license adoption
Skybuffer SAM4U tool for SAP license adoption
 
Programming Foundation Models with DSPy - Meetup Slides
Programming Foundation Models with DSPy - Meetup SlidesProgramming Foundation Models with DSPy - Meetup Slides
Programming Foundation Models with DSPy - Meetup Slides
 
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with SlackLet's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
 
Building Production Ready Search Pipelines with Spark and Milvus
Building Production Ready Search Pipelines with Spark and MilvusBuilding Production Ready Search Pipelines with Spark and Milvus
Building Production Ready Search Pipelines with Spark and Milvus
 
Digital Marketing Trends in 2024 | Guide for Staying Ahead
Digital Marketing Trends in 2024 | Guide for Staying AheadDigital Marketing Trends in 2024 | Guide for Staying Ahead
Digital Marketing Trends in 2024 | Guide for Staying Ahead
 
Generating privacy-protected synthetic data using Secludy and Milvus
Generating privacy-protected synthetic data using Secludy and MilvusGenerating privacy-protected synthetic data using Secludy and Milvus
Generating privacy-protected synthetic data using Secludy and Milvus
 

How to implement golang jwt authentication and authorization

  • 1. How to Implement Golang JWT Authentication and Authorization www.bacancytechnology.com
  • 2. What is JSON Web Token? How does JSON Web Token look like? What does JSON Web Token comprise? Table of Content 1. Introduction 2. Exploring JSON Web Token 3. Implementing Golang JWT Authentication and Authorization 4. Conclusion
  • 4. Would you let anyone enter your house without knowing the person’s identity? The answer would be – Obviously No! So, we have the same scenario with our web applications too. It’s necessary to authenticate a user’s identity before making requests using APIs. And this authentication takes place with the help of JWT .i.e., JSON Web Token. Now you might wonder what is JWT in Golang and JWT authentication. Don’t panic if you are unaware of how to implement Golang JWT authentication. Here’s a tutorial where I will make you understand how to implement Golang JWT Authentication and Authorization. So let’s get started.
  • 5. Exploring JSON Web Token Under this section, we will comprehensively understand what is JWT, how does JSON Web token look like, and what JSON web token consists of.
  • 6. What is a JSON Web Token? A JWT token is a cryptographically signed token which the server generates and gives to the client. The client uses JWT for making various requests to the server. The token can be signed using two algorithms: HMAC or SHA256. SHA256 hashes the message without the need of any external input. It guarantees only message integrity. HMAC needs a private key in order to hash the message. It guarantees message integrity and authentication.
  • 7. How Does a JSON Web Token look like? eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1 c2VyaWQiOiIxZGQ5MDEwYy00MzI4LTRoZj NiOWU2LTc3N2Q4NDhlOTM3NSIsImF1dGhv cml6ZWQiOmZhbHNlfQ.vI7thh64mzXp_WM KZIedaKR4AF4trbvOHEpm2d62qIQ The above token is invalid. It cannot be used for production.
  • 8. What comprises a JSON Web Token? A JSON Web Token consists of three parts which are separated using .(dot) : Header: It indicates the token’s type it is and which signing algorithm has been used. Payload: It consists of the claims. And claims comprise of application’s data( email id, username, role), the expiration period of a token (Exp), and so on. Signature: It is generated using the secret (provided by the user), encoded header, and payload.
  • 9. We can set the expiration period for any JSON Web Token. Here in this application, we will consider Access Token and Refresh Token. Let’s see the difference. To test the token, you can go to https://jwt.io/.
  • 10. Access Token: An access token is used for authenticating the requests sent to the server. We add the access token in the header of the request. It is recommended that an access token should have a short lifespan (say 15 minutes) for security purposes. Giving an access token for a brief period can prevent severe damages. Refresh Token: A refresh token has a longer lifespan( usually 7 days) compared to an access token. Whenever an access token is expired, the refresh token allows generating a new access token without letting the user know.
  • 12. Follow these steps for Golang JWT Authentication and Authorization- Create a directory Create a directory called jwt-practice. mkdir jwt-practice cd jwt-practice Initializing with go.mod Initialize it with go.mod, for dependency management, using – go mod init jwt-practice
  • 13. Create a main.go Create a main.go file in the root directory of the project. For simplicity, I will the entire code in main.go Copy and paste the following code snippets, which I will show you in the coming steps. func main() { } mux for routing and handling HTTP requests GORM as ORM tool crypto for password hashing Postgres for the database Downloading dependencies Next, we will download the required dependencies. We will use
  • 14. $ go get github.com/gorilla/mux $ go get github.com/jinzhu/gorm $ go get github.com/lib/pq $ go get golang.org/x/crypto/bcrypt Downloading jwt-package Download the jwt package using this command- go get github.com/dgrijalva/jwt-go Create Router and initialize the routes In this step, we will create a router and initialize routes. Add this code in your main.go
  • 15. var router *mux.Router func CreateRouter() { router = mux.NewRouter() } func InitializeRoute() { router.HandleFunc("/signup", SignUp).Methods("POST") router.HandleFunc("/signin", SignIn).Methods("POST") } func main() { CreateRouter() InitializeRoute() }
  • 16. Create some Structures Let’s get our hands on to create some structs. type User struct { gorm.Model Name string `json:"name"` Email string `gorm:"unique" json:"email"` Password string `json:"password"` Role string `json:"role"` } type Authentication struct { Email string `json:"email"` Password string `json:"password"` } type Token struct { Role string `json:"role"` Email string `json:"email"` TokenString string `json:"token"` }
  • 17. User is for storing User details. Authentication is for login data. Token is for storing token information for correct login credentials. Connecting to Database The best practice would be to add the code related to the Database connection to your .env file but for simplicity purpose, I have implemented it in main.go itself. As said before, I’ll be using the Postgres database. Add the following code to establish a database connection.
  • 18. func GetDatabase() *gorm.DB { databasename := "userdb" database := "postgres" databasepassword := "1312" databaseurl := "postgres://postgres:" + databasepassword + "@localhost/" + databasename + "?sslmode=disable" connection, err := gorm.Open(database, databaseurl) if err != nil { log.Fatalln("wrong database url") } sqldb := connection.DB() err = sqldb.Ping() if err != nil { log.Fatal("database connected") } fmt.Println("connected to database") return connection
  • 19. } func InitialMigration() { connection := GetDatabase() defer Closedatabase(connection) connection.AutoMigrate(User{}) } func Closedatabase(connection *gorm.DB) { sqldb := connection.DB() sqldb.Close() } Sign Up process The SignUp function opens the database connection, receives user data from the form, and checks if the user already exists in the database or not. If the user is already present in the database, it returns an error, otherwise hash the user password and creates a new database entry. Copy-paste the below-mentioned code in your file.
  • 20. func SignUp(w http.ResponseWriter, r *http.Request) { connection := GetDatabase() defer Closedatabase(connection) var user User err := json.NewDecoder(r.Body).Decode(&user) if err != nil { var err Error err = SetError(err, "Error in reading body") w.Header().Set("Content-Type", "application/json") json.NewEncoder(w).Encode(err) return } var dbuser User connection.Where("email = ?", user.Email).First(&dbuser)
  • 21. //checks if email is already register or not if dbuser.Email != "" { var err Error err = SetError(err, "Email already in use") w.Header().Set("Content-Type", "application/json") json.NewEncoder(w).Encode(err) return } user.Password, err = GeneratehashPassword(user.Password) if err != nil { log.Fatalln("error in password hash") } //insert user details in database connection.Create(&user) w.Header().Set("Content-Type", "application/json") json.NewEncoder(w).Encode(user) }
  • 22. Use GeneratehashPassword for hashing the password. func GeneratehashPassword(password string) (string, error) { bytes, err := bcrypt.GenerateFromPassword([]byte( password), 14) return string(bytes), err } So, we are done with the fundamental set up in our main. go. It’s time to start coding for the Authentication and Authorization part. But, before that let me brief you regarding the difference between the two processes.
  • 23. Authentication vs Authorization Authentication can be defined as validating the users of any particular application. And that’s why it is said to be the crucial and foremost step in developing an application. It directly concerns security issues. Allowing someone to make a request to the server is a basic example of authentication. Authorization is a process of where the user roles are being managed. It can be briefed as giving a user some specific permissions for accessing particular resources. First, we will begin the process of authentication.
  • 24. Generate JWT Write the following function to create Golang JWT: The GenerateJWT() function takes email and role as input. Creates a token by HS256 signing method and adds authorized email, role, and exp into claims. Claims are pieces of information added into tokens. func GenerateJWT(email, role string) (string, error) { var mySigningKey = []byte(secretkey) token := jwt.New(jwt.SigningMethodHS256) claims := token.Claims.(jwt.MapClaims) claims["authorized"] = true claims["email"] = email claims["role"] = role claims["exp"] = time.Now().Add(time.Minute * 30).Unix()
  • 25. tokenString, err := token.SignedString(mySigningKey) if err != nil { fmt.Errorf("Something Went Wrong: %s", err.Error()) return "", err } return tokenString, nil } Sign In Process The SignIn function checks if the user is already present in the database. If the user is not present, then redirect the user to the login page. If the user is present in the database, then hash the password the user gave in the login form and compare that hashed password with the stored hashed password. If both the hashed passwords are the same, then generate a new Golang JWT authentication and give it back to the user or redirect the user to the login page.
  • 26. func SignIn(w http.ResponseWriter, r *http.Request) { connection := GetDatabase() defer Closedatabase(connection) var authdetails Authentication err := json.NewDecoder(r.Body).Decode(&authd etails) if err != nil { var err Error err = SetError(err, "Error in reading body") w.Header().Set("Content-Type", "application/json") json.NewEncoder(w).Encode(err) return }
  • 27. var authuser User connection.Where("email = ?", authdetails.Email).First(&authuser) if authuser.Email == "" { var err Error err = SetError(err, "Username or Password is incorrect") w.Header().Set("Content-Type", "application/json") json.NewEncoder(w).Encode(err) return } check := CheckPasswordHash(authdetails.Passwor d, authuser.Password)
  • 28. if !check { var err Error err = SetError(err, "Username or Password is incorrect") w.Header().Set("Content-Type", "application/json") json.NewEncoder(w).Encode(err) return } validToken, err := GenerateJWT(authuser.Email, authuser.Role) if err != nil { var err Error err = SetError(err, "Failed to generate token") w.Header().Set("Content-Type", "application/json") json.NewEncoder(w).Encode(err) return }
  • 29. var token Token token.Email = authuser.Email token.Role = authuser.Role token.TokenString = validToken w.Header().Set("Content-Type", "application/json") json.NewEncoder(w).Encode(token) } CheckPasswordHash() function compares the plain password with a hashed password. func CheckPasswordHash(password, hash string) bool { err := bcrypt.CompareHashAndPassword([]byte (hash), []byte(password)) return err == nil }
  • 30. Now let’s start the process of authorization. Writing MiddleWare function IsAuthorized() function verifies the token, and if the token is valid, it will extract the role from the token. And based on the role, the user will be redirected to the appropriate page. There are two roles: Admin and User. Now, finally, it’s time to write the middleware function. Copy-paste the below- mentioned code.
  • 31. func IsAuthorized(handler http.HandlerFunc) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { if r.Header["Token"] == nil { var err Error err = SetError(err, "No Token Found") json.NewEncoder(w).Encode(err) return } var mySigningKey = []byte(secretkey) token, err := jwt.Parse(r.Header["Token"][0], func(token *jwt.Token) (interface{}, error) { if _, ok := token.Method. (*jwt.SigningMethodHMAC); !ok { return nil, fmt.Errorf("There was an error in parsing") } return mySigningKey, nil })
  • 32. if err != nil { var err Error err = SetError(err, "Your Token has been expired") json.NewEncoder(w).Encode(err) return } if claims, ok := token.Claims. (jwt.MapClaims); ok && token.Valid { if claims["role"] == "admin" { r.Header.Set("Role", "admin") handler.ServeHTTP(w, r) return } else if claims["role"] == "user" { r.Header.Set("Role", "user") handler.ServeHTTP(w, r) return }
  • 33. } var reserr Error reserr = SetError(reserr, "Not Authorized") json.NewEncoder(w).Encode(err) } } Source code for the entire demo application is here – Github Repository Verifying Golang JWT After all the coding, let’s verify whether the Golang JWT authentication is working as expected.
  • 34. Thus, you are done with generating the Golang JWT. Further, for your frontend side, you can store this token in your local storage and use it in different API requests. Refer to the below images- (1) Signed In successfully and receiving Golang JWT in the response. You can see the “role”: “user” which satisfies the authorization part. It means that only specific resources will be accessible to the user role.
  • 35. (2) Storing Golang JWT in the local storage so that you can use this token for different API calls.
  • 36. Conclusion I hope this blog has helped you with Golang JWT Authentication and Authorization. The process of authentication and authorization is crucial step for developing any web application. If you are looking for a helping hand to implement Golang JWT, then hire Golang developer to leverage our top-of- the-line Golang development expertise.