This is an implementation of JWT in golang!

Overview

Build Status Coverage Status Go Report Card GoDoc

jwt

This is a minimal implementation of JWT designed with simplicity in mind.

What is JWT?

Jwt is a signed JSON object used for claims based authentication. A good resource on what JWT Tokens are is jwt.io, and in addition you can always read the RFC.

This implementation doesn't fully follow the specs in that it ignores the algorithm claim on the header. It does this due to the security vulnerability in the JWT specs. Details on the vulnerability can be found here

What algorithms does it support?

  • HS256
  • HS384
  • HS512

How does it work?

How to create a token?

Creating a token is actually pretty easy.

The first step is to pick a signing method. For demonstration purposes we will choose HSMAC256.

algorithm :=  jwt.HmacSha256("ThisIsTheSecret")

Now we need to the claims, and edit some values

claims := jwt.NewClaim()
claims.Set("Role", "Admin")

Then we will need to sign it!

token, err := algorithm.Encode(claims)
if err != nil {
    panic(err)    
}

How to authenticate a token?

Authenticating a token is quite simple. All we need to do is...

if algorithm.Validate(token) == nil {
    //authenticated
} 

How do we get the claims?

The claims are stored in a Claims struct. To get the claims from a token simply...

claims, err := algorithm.Decode(token)
if err != nil {
    panic(err)
}
_, role := claims.Get("Role")
if strings.Compare(role, "Admin") {
    //user is an admin    
}

How is it different from golang.org/x/oauth2/jwt?

This package contains just the logic for jwt encoding, decoding, and verification. The golang.org/x/oauth2/jwt package does not implement the jwt specifications. Instead it is specifically tied to oauth2, requiring a TokenURL, email and can only use a specific algorithm (RSA).

Issues
  • Double-encoding error in validateSignature

    Double-encoding error in validateSignature

    Algorithm.Sign returns an already base64 encoded string but validateSignature does it again resulting in validate always failing with an invalid signature error.

    Not sure if this is the way you'd fix it, but the following change corrects the issue for me:

    diff --git a/algorithms.go b/algorithms.go
    index 745118c..64f2772 100644
    --- a/algorithms.go
    +++ b/algorithms.go
    @@ -143,9 +143,7 @@ func (a *Algorithm) validateSignature(encoded string) error {
                    return errors.Wrap(err, "unable to sign token for validation")
            }
     
    -       b64SignedAttempt := base64.RawURLEncoding.EncodeToString([]byte(signedAttempt))
    -
    -       if !hmac.Equal([]byte(b64Signature), []byte(b64SignedAttempt)) {
    +       if !hmac.Equal([]byte(b64Signature), []byte(signedAttempt)) {
                    return errors.New("invalid signature")
            }
     
    
    opened by BonkaBonka 2
  • JWT uses base64 URL encoding, not std encoding

    JWT uses base64 URL encoding, not std encoding

    I ran into the following error decoding a JWT on my system:

    unable to decode base64 payload: illegal base64 data at input byte 264

    Looks like it's related to the base64 decode function being used: https://github.com/robbert229/jwt/blob/master/algorithms.go#L94

    If I switch the line to: payload, err := base64.RawURLEncoding.DecodeString(b64Payload)

    then it works! I suspect all of the encoding/decoding needs to use this. Here's the RFC, for reference.

    opened by tartale 0
  • Panic when running with multiple goroutines

    Panic when running with multiple goroutines

    Hi,

    I've discovered that this library panics when run with multiple goroutines.

    Considering the following minimal example:

    package main
    
    import (
    	"sync"
    
    	"github.com/robbert229/jwt"
    )
    
    func main() {
    	algorithm := jwt.HmacSha256("ThisIsTheSecret")
    	var wg sync.WaitGroup
    	noRoutines := 10
    	wg.Add(noRoutines)
    	for i := 0; i < noRoutines; i++ {
    		go decode(&algorithm, &wg)
    	}
    	wg.Wait()
    }
    
    func decode(algorithm *jwt.Algorithm, wg *sync.WaitGroup) {
    	defer wg.Done()
    	claims := jwt.NewClaim()
    	claims.Set("Role", "Admin")
    	token, err := algorithm.Encode(claims)
    	if err != nil {
    		panic(err)
    	}
    	for index := 0; index < 100; index++ {
    		_, err = algorithm.Decode(token)
    		if err != nil {
    			panic(err)
    		}
    	}
    }
    

    Almost every run of this program leads to a panic like

    panic: d.nx != 0
    
    goroutine 7 [running]:
    crypto/sha256.(*digest).checkSum(0xc42003fd10, 0x0, 0x0, 0x0, 0x0)
    	/usr/local/Cellar/go/1.9.2/libexec/src/crypto/sha256/sha256.go:157 +0x29e
    crypto/sha256.(*digest).Sum(0xc420084080, 0x0, 0x0, 0x0, 0x60, 0x5d, 0x0)
    	/usr/local/Cellar/go/1.9.2/libexec/src/crypto/sha256/sha256.go:131 +0x69
    crypto/hmac.(*hmac).Sum(0xc420052060, 0x0, 0x0, 0x0, 0x5d, 0x0, 0x0)
    	/usr/local/Cellar/go/1.9.2/libexec/src/crypto/hmac/hmac.go:46 +0x56
    gitlab.com/jwt-test/vendor/github.com/robbert229/jwt.(*Algorithm).sum(0xc42000a060, 0x0, 0x0, 0x0, 0x5d, 0x0, 0x0)
    	/myGopath/jwt-test/vendor/github.com/robbert229/jwt/algorithms.go:32 +0x51
    gitlab.com/jwt-test/vendor/github.com/robbert229/jwt.(*Algorithm).Sign(0xc42000a060, 0xc4200e4000, 0x5d, 0x1104718, 0x1, 0xc4200d4090, 0x2c)
    	/myGopath/jwt-test/vendor/github.com/robbert229/jwt/algorithms.go:50 +0xff
    gitlab.com/jwt-test/vendor/github.com/robbert229/jwt.(*Algorithm).Encode(0xc42000a060, 0xc420090010, 0x110490b, 0x4, 0xc42009e1b8, 0x0)
    	/myGopath/jwt-test/vendor/github.com/robbert229/jwt/algorithms.go:76 +0x1e7
    main.decode(0xc42000a060, 0xc4200160d0)
    	/myGopath/jwt-test/main.go:24 +0xca
    created by main.main
    	/myGopath/jwt-test/main.go:15 +0xf3
    exit status 2
    

    We should at least document how the expected concurrenct usage scenario for this library is.

    opened by Till--H 4
Releases(v2.0.0)
Owner
John Rowley
John Rowley
Account-jwt-go - Simple JWT api with go, gorm, gin

Account JWT on Go Go, gorm, Gin web framework 를 활용하여 만든 간단한 JWT API 입니다. Dajngo의

Deagwon Bu 1 Apr 14, 2022
Krakend-jwt-header-rewriter - Kraken Plugin - JWT Header Rewriter

Kraken Plugin - JWT Header Rewriter 1 Plugin Configuration Name Desciption Defau

null 0 Feb 15, 2022
This is an implementation of JWT in golang!

jwt This is a minimal implementation of JWT designed with simplicity in mind. What is JWT? Jwt is a signed JSON object used for claims based authentic

John Rowley 99 May 9, 2022
Golang implementation of JSON Web Tokens (JWT)

jwt-go A go (or 'golang' for search engine friendliness) implementation of JSON Web Tokens NEW VERSION COMING: There have been a lot of improvements s

Dave Grijalva 10.4k Aug 15, 2022
Golang implementation of JWT and Refresh Token

Fiber and JWT with Refresh Token Repo ini adalah demostrasi JWT support refresh token tanpa menggunakan storage Branch Main: unlimited refresh token R

Muhamad Surya Iksanudin 16 Aug 13, 2022
An implementation of JOSE standards (JWE, JWS, JWT) in Go

Go JOSE Package jose aims to provide an implementation of the Javascript Object Signing and Encryption set of standards. This includes support for JSO

Square 1.9k Aug 6, 2022
A fast and simple JWT implementation for Go

JWT Fast and simple JWT implementation written in Go. This package was designed with security, performance and simplicity in mind, it protects your to

Gerasimos (Makis) Maropoulos 146 Aug 6, 2022
backend implementation demonstration in go with JWT, MongoDB and etc.

backend implementation demonstration in go with JWT, MongoDB and etc.

Parham Alvani 12 May 18, 2022
This package provides json web token (jwt) middleware for goLang http servers

jwt-auth jwt auth middleware in goLang. If you're interested in using sessions, checkout my sessions library! README Contents: Quickstart Performance

Adam Hanna 218 Jul 29, 2022
Simple JWT Golang

sjwt Simple JSON Web Token - Uses HMAC SHA-256 Example // Set Claims claims := New() claims.Set("username", "billymister") claims.Set("account_id", 86

Brian Voelker 99 Aug 11, 2022
Golang Mongodb Jwt Auth Example Using Echo

Golang Mongodb Jwt Auth Example Using Echo Golang Mongodb Rest Api Example Using Echo Prerequisites Golang 1.16.x Docker 19.03+ Docker Compose 1.25+ I

Şuayb Şimşek 7 Jun 10, 2022
Golang jwt tokens without any external dependency

Yet another jwt lib This is a simple lib made for small footprint and easy usage It allows creating, signing, reading and verifying jwt tokens easily

Karpelès Lab Inc. 1 Oct 11, 2021
Golang with JWT, Go Gin and MongoDB

User authentication in Golang with JWT, Go Gin and MongoDB Golang backend application that uses JWT tokens for users Locally Up Setup your .env file,

Al Mamun Khan 10 May 27, 2022
Golang based User creation and Management application. GORM, Fiber, JWT

User Creation and Management app (BACK-END) Auth Features: Create Clients (regular password + 6 one-time passwords + (optional) QR code and Secret for

Artūras 5 May 11, 2022
Example App written in Golang for provide AuthZ/N using JWT

RCK Auth Application Example App written in Golang for provide Authentication & Authorization using Json Web Tokens. Run with Docker / Podman Run a Po

Roberto Carratala 2 Feb 25, 2022
JWT Auth in Golang

Credits This package used github.com/dgrijalva/jwt-go underhood and it heavily based on this post: http://www.inanzzz.com/index.php/post/kdl9/creating

Pablo Fuentes 0 Dec 12, 2021
🔥 Golang Rest Api with basic JWT Authentication and Basic Crud Operations.

?? Golang Rest Api with basic JWT Authentication and Basic Crud Operations.

Junaid Javed 16 Jul 29, 2022
A simple authentication web application in Golang (using jwt)

Simple Authentication WebApp A simple authentication web app in Go (using JWT) Routes Path Method Data /api/v1/auth/register POST {"firstname":,"lastn

Shayan 2 Feb 6, 2022
Verifier - Golang JWT token verifier with storage(default Redis)

verifier Golang JWT token verifier with storage(default Redis) Usage go get -u g

XanderCheung 7 Jul 1, 2022