-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Added JWT token & Paseto Token authentication system
- Loading branch information
1 parent
5d73dcc
commit 4b41447
Showing
8 changed files
with
307 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,60 @@ | ||
package token | ||
|
||
import ( | ||
"errors" | ||
"fmt" | ||
"time" | ||
|
||
"github.com/golang-jwt/jwt" | ||
) | ||
|
||
const minSecretKeySize = 32 | ||
|
||
// Implements Maker interface | ||
type JWTMaker struct { | ||
secretKey string | ||
} | ||
|
||
func NewJWTMaker(secretKey string) (Maker, error) { | ||
if len(secretKey) < minSecretKeySize { | ||
return nil, fmt.Errorf("invalid key size: must be at least %d chars", minSecretKeySize) | ||
} | ||
return &JWTMaker{secretKey: secretKey}, nil | ||
} | ||
|
||
func (maker *JWTMaker) CreateToken(username string, duration time.Duration) (string, error) { | ||
payload, err := NewPayload(username, duration) | ||
if err != nil { | ||
return "", err | ||
} | ||
|
||
jwtToken := jwt.NewWithClaims(jwt.SigningMethodHS256, payload) | ||
return jwtToken.SignedString([]byte(maker.secretKey)) | ||
} | ||
|
||
func (maker *JWTMaker) VerifyToken(token string) (*Payload, error) { | ||
keyFunc := func(token *jwt.Token) (interface{}, error) { | ||
_, ok := token.Method.(*jwt.SigningMethodHMAC) | ||
if !ok { | ||
return nil, ErrInvalidToken | ||
} | ||
|
||
return []byte(maker.secretKey), nil | ||
} | ||
|
||
jwtToken, err := jwt.ParseWithClaims(token, &Payload{}, keyFunc) | ||
if err != nil { | ||
verr, ok := err.(*jwt.ValidationError) | ||
if ok && errors.Is(verr.Inner, ErrExpiredToken) { | ||
return nil, ErrExpiredToken | ||
} | ||
return nil, ErrInvalidToken | ||
} | ||
|
||
paload, ok := jwtToken.Claims.(*Payload) | ||
if !ok { | ||
return nil, ErrInvalidToken | ||
} | ||
|
||
return paload, nil | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,65 @@ | ||
package token | ||
|
||
import ( | ||
"testing" | ||
"time" | ||
|
||
"github.com/ashiqYousuf/sbank/util" | ||
"github.com/golang-jwt/jwt" | ||
"github.com/stretchr/testify/require" | ||
) | ||
|
||
func TestJWTMaker(t *testing.T) { | ||
maker, err := NewJWTMaker(util.RandomString(32)) | ||
require.NoError(t, err) | ||
|
||
username := util.RandomOwner() | ||
duration := time.Minute | ||
|
||
issuedAt := time.Now() | ||
expiredAt := issuedAt.Add(duration) | ||
|
||
token, err := maker.CreateToken(username, duration) | ||
require.NoError(t, err) | ||
require.NotEmpty(t, token) | ||
|
||
payload, err := maker.VerifyToken(token) | ||
require.NoError(t, err) | ||
require.NotEmpty(t, payload) | ||
|
||
require.NotZero(t, payload.ID) | ||
require.Equal(t, username, payload.Username) | ||
require.WithinDuration(t, issuedAt, payload.IssuedAt, time.Second) | ||
require.WithinDuration(t, expiredAt, payload.ExpiredAt, time.Second) | ||
} | ||
|
||
func TestExpiredJWTToken(t *testing.T) { | ||
maker, err := NewJWTMaker(util.RandomString(32)) | ||
require.NoError(t, err) | ||
|
||
token, err := maker.CreateToken(util.RandomOwner(), -time.Minute) | ||
require.NoError(t, err) | ||
require.NotEmpty(t, token) | ||
|
||
payload, err := maker.VerifyToken(token) | ||
require.Error(t, err) | ||
require.EqualError(t, err, ErrExpiredToken.Error()) | ||
require.Nil(t, payload) | ||
} | ||
|
||
func TestInvalidJWTTokenAlgNone(t *testing.T) { | ||
payload, err := NewPayload(util.RandomOwner(), time.Minute) | ||
require.NoError(t, err) | ||
|
||
jwtToken := jwt.NewWithClaims(jwt.SigningMethodNone, payload) | ||
token, err := jwtToken.SignedString(jwt.UnsafeAllowNoneSignatureType) | ||
require.NoError(t, err) | ||
|
||
maker, err := NewJWTMaker(util.RandomString(32)) | ||
require.NoError(t, err) | ||
|
||
payload, err = maker.VerifyToken(token) | ||
require.Error(t, err) | ||
require.EqualError(t, err, ErrInvalidToken.Error()) | ||
require.Nil(t, payload) | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,14 @@ | ||
package token | ||
|
||
import "time" | ||
|
||
// Maker is an interface for managing tokens | ||
// JWTMaker & PasetoMaker will implement this interface | ||
// Implies we can easily switch b/w our JWT & PASETO tokens | ||
type Maker interface { | ||
// creates a new token for a specific username & duration | ||
CreateToken(username string, duration time.Duration) (string, error) | ||
|
||
// checks if the token is valid or not | ||
VerifyToken(token string) (*Payload, error) | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,52 @@ | ||
package token | ||
|
||
import ( | ||
"fmt" | ||
"time" | ||
|
||
"github.com/aead/chacha20poly1305" | ||
"github.com/o1egl/paseto" | ||
) | ||
|
||
// Implements Maker interface | ||
type PasetoMaker struct { | ||
paseto *paseto.V2 | ||
symmetricKey []byte | ||
} | ||
|
||
func NewPasetoMaker(symmetricKey string) (Maker, error) { | ||
if len(symmetricKey) != chacha20poly1305.KeySize { | ||
return nil, fmt.Errorf("invalid key size: must be exactly %d chars", chacha20poly1305.KeySize) | ||
} | ||
|
||
maker := &PasetoMaker{ | ||
paseto: paseto.NewV2(), | ||
symmetricKey: []byte(symmetricKey), | ||
} | ||
return maker, nil | ||
} | ||
|
||
func (maker *PasetoMaker) CreateToken(username string, duration time.Duration) (string, error) { | ||
payload, err := NewPayload(username, duration) | ||
if err != nil { | ||
return "", err | ||
} | ||
|
||
return maker.paseto.Encrypt(maker.symmetricKey, payload, nil) | ||
} | ||
|
||
func (maker *PasetoMaker) VerifyToken(token string) (*Payload, error) { | ||
payload := &Payload{} | ||
|
||
err := maker.paseto.Decrypt(token, maker.symmetricKey, payload, nil) | ||
if err != nil { | ||
return nil, ErrInvalidToken | ||
} | ||
|
||
err = payload.Valid() | ||
if err != nil { | ||
return nil, err | ||
} | ||
|
||
return payload, nil | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,47 @@ | ||
package token | ||
|
||
import ( | ||
"testing" | ||
"time" | ||
|
||
"github.com/ashiqYousuf/sbank/util" | ||
"github.com/stretchr/testify/require" | ||
) | ||
|
||
func TestPasetoMaker(t *testing.T) { | ||
maker, err := NewPasetoMaker(util.RandomString(32)) | ||
require.NoError(t, err) | ||
|
||
username := util.RandomOwner() | ||
duration := time.Minute | ||
|
||
issuedAt := time.Now() | ||
expiredAt := issuedAt.Add(duration) | ||
|
||
token, err := maker.CreateToken(username, duration) | ||
require.NoError(t, err) | ||
require.NotEmpty(t, token) | ||
|
||
payload, err := maker.VerifyToken(token) | ||
require.NoError(t, err) | ||
require.NotEmpty(t, payload) | ||
|
||
require.NotZero(t, payload.ID) | ||
require.Equal(t, username, payload.Username) | ||
require.WithinDuration(t, issuedAt, payload.IssuedAt, time.Second) | ||
require.WithinDuration(t, expiredAt, payload.ExpiredAt, time.Second) | ||
} | ||
|
||
func TestExpiredPasetoToken(t *testing.T) { | ||
maker, err := NewPasetoMaker(util.RandomString(32)) | ||
require.NoError(t, err) | ||
|
||
token, err := maker.CreateToken(util.RandomOwner(), -time.Minute) | ||
require.NoError(t, err) | ||
require.NotEmpty(t, token) | ||
|
||
payload, err := maker.VerifyToken(token) | ||
require.Error(t, err) | ||
require.EqualError(t, err, ErrExpiredToken.Error()) | ||
require.Nil(t, payload) | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,44 @@ | ||
package token | ||
|
||
import ( | ||
"errors" | ||
"time" | ||
|
||
"github.com/google/uuid" | ||
) | ||
|
||
var ( | ||
ErrExpiredToken = errors.New("token has expired") | ||
ErrInvalidToken = errors.New("token is invalid") | ||
) | ||
|
||
// Payload data of the token | ||
type Payload struct { | ||
ID uuid.UUID `json:"id"` // uniquely indentify each token (blacklisting) | ||
Username string `json:"username"` | ||
IssuedAt time.Time `json:"issued_at"` | ||
ExpiredAt time.Time `json:"expired_at"` | ||
} | ||
|
||
func NewPayload(username string, duration time.Duration) (*Payload, error) { | ||
tokenID, err := uuid.NewRandom() | ||
if err != nil { | ||
return nil, err | ||
} | ||
|
||
payload := &Payload{ | ||
ID: tokenID, | ||
Username: username, | ||
IssuedAt: time.Now(), | ||
ExpiredAt: time.Now().Add(duration), | ||
} | ||
|
||
return payload, nil | ||
} | ||
|
||
func (payload *Payload) Valid() error { | ||
if time.Now().After(payload.ExpiredAt) { | ||
return ErrExpiredToken | ||
} | ||
return nil | ||
} |