authorizer

package module
v0.0.0-...-4079cb3 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Mar 10, 2024 License: MIT Imports: 10 Imported by: 0

README

authorizer

Package will Securely Sign / Un-sign a payload

- Prerequisite must have a valid RSA private/public certificates

Badge

build

How to use the package

import (
   "fmt"
   	"log"
   	"net/http"
   	"net/url"
   	"time"
   
   	"github.com/dgrijalva/jwt-go"
   	"github.com/go-chi/chi"
   	"github.com/go-chi/render"
   	"github.com/google/uuid"
   
   	"github.com/bayugyug/authorizer"
   	"github.com/bayugyug/authorizer/commons"
)

How to sign a payload

// salt, publicKey, privateKey
    
    
opts := authorizer.Options{
    PrivateKey: privKeyStr,
    PublicKey:  pubKeyStr,
    TokenSource: authorizer.TokenSource{
        QueryKey: "_verify",
    },
    Expiry: 1400,
}

verifier = authorizer.NewVerifierService(&opts)

claims := &authorizer.AuthClaims{
    StandardClaims: jwt.StandardClaims{
    Audience:  "source-verifier-aud",
    Id:        uuid.New().String(),
    Issuer:    "source-verifier-issuer",
    Subject:   salt,                                                     // salt
    ExpiresAt: time.Now().Add(time.Duration(3600) * time.Minute).Unix(), // expiry
    },
    MetaInfo: map[string]interface{}{
        "extra": uuid.New().String(),
    },
}

// sign
sign, err := verifier.Sign(claims)

if err != nil {
    fmt.Println("fail",err)
    return
}


How to un-sign a payload

// salt, publicKey, privateKey
    
    
opts := authorizer.Options{
    PrivateKey: privKeyStr,
    PublicKey:  pubKeyStr,
    TokenSource: authorizer.TokenSource{
        QueryKey: "_verify",
    },
    Expiry: 1400,
}

verifier = authorizer.NewVerifierService(&opts)
    
     
// handler
proxyHandler := func(w http.ResponseWriter, r *http.Request) {
    // un-sign jwt
    res, err := verifier.UnSign(r)
    if err != nil {
        render.Status(r, http.StatusInternalServerError)
        render.JSON(w, r,
            err.Error(),
        )
        return
    }

    // extra check the salt via the subject
    oks := res.CheckSubject(salt)
   
    commons.JSONify("check subject/salt", res, oks)

    if !oks {
        render.Status(r, http.StatusInternalServerError)
        render.JSON(w, r,
            err.Error(),
        )
        return
    }
}



Self sign RSA certificates

# init vars
mkdir -p ~/tmp/ 2>/dev/null
PREFIX=$(date '+%Y-%m-%d-%H%M%S')-$(printf "%04x-%04x" ${RANDOM} ${RANDOM})
PRIVKEY=~/tmp/${PREFIX}-priv.pem
CACERT=~/tmp/${PREFIX}-cacert.pem
DERCERT=~/tmp/${PREFIX}-dercert.cer
PUBKEY=~/tmp/${PREFIX}-pub.txt

# generate
openssl genrsa -out $PRIVKEY
openssl req -new -x509 -key $PRIVKEY -out $CACERT -days 365 -subj "/C=SG/ST='Singapore'/L='Singapore/O=Bayugismo/OU='Engineering'/CN=*.bayugismo.space"
openssl x509 -inform PEM -in $CACERT -outform DER -out $DERCERT
openssl x509 -inform der -in $DERCERT -noout -pubkey > $PUBKEY

# PUBLIC KEY
openssl rsa -pubin -in $PUBKEY -RSAPublicKey_out | sed -e ':a' -e 'N' -e '$!ba' -e 's/\n/\\n/g'


# PRIVATE KEY
cat $PRIVKEY | sed -e ':a' -e 'N' -e '$!ba' -e 's/\n/\\n/g'

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	// DefaultAuthHeaderKey ...
	DefaultAuthHeaderKey = `X-AuthVerifierToken`
	// DefaultExpiry ...
	DefaultExpiry = 2800 // minutes  ( 2 days default )
	// DefaultGetQueryParam ...
	DefaultGetQueryParam = "verifier"
	// ErrMissingParams ...
	ErrMissingParams = errors.New("missing required parameters")
	// ErrEmptyToken ...
	ErrEmptyToken = errors.New("empty token")
	// ErrInvalidToken ...
	ErrInvalidToken = errors.New("invalid token")
	// ErrConvertClaims ...
	ErrConvertClaims = errors.New("fail convert claims")
)

Functions

func GetPublicKey

func GetPublicKey(key string) func(token *jwt.Token) (interface{}, error)

GetPublicKey ...

func GetTokenFromAuthBearer

func GetTokenFromAuthBearer(r *http.Request) string

GetTokenFromAuthBearer ...

func GetTokenFromHeader

func GetTokenFromHeader(r *http.Request, key string) string

GetTokenFromHeader ...

func GetTokenFromQuery

func GetTokenFromQuery(r *http.Request, key string) string

GetTokenFromQuery ...

Types

type AuthClaims

type AuthClaims struct {
	jwt.StandardClaims             // standard claims
	MetaInfo           interface{} `json:"meta_info,omitempty"`
	Details            *Details    `json:"details,omitempty"`
}

AuthClaims custom claims

func (*AuthClaims) CheckSubject

func (s *AuthClaims) CheckSubject(salt string) bool

CheckSubject ...

func (*AuthClaims) SetSubject

func (s *AuthClaims) SetSubject(salt string) string

SetSubject ...

type Details

type Details struct {
	UUID         string   `json:"uuid,omitempty"`
	AuthToken    string   `json:"auth_token,omitempty"`
	RefreshToken string   `json:"refresh_token,omitempty"`
	AuthType     string   `json:"auth_type,omitempty"`
	Name         string   `json:"name,omitempty"`
	Method       string   `json:"method,omitempty"`
	Roles        []string `json:"roles,omitempty"`
}

Details ...

type Options

type Options struct {
	PrivateKey  string
	PublicKey   string
	TokenSource TokenSource
	Expiry      int
}

Options ...

type TokenSource

type TokenSource struct {
	HeaderKey  string
	QueryKey   string
	AuthBearer bool
}

TokenSource ...

type VerifierService

type VerifierService struct {
	// contains filtered or unexported fields
}

VerifierService ...

func (*VerifierService) Sign

func (s *VerifierService) Sign(payload *AuthClaims) (string, error)

Sign ... sign the payload

func (*VerifierService) UnSign

func (s *VerifierService) UnSign(req *http.Request) (*AuthClaims, error)

UnSign ... verify the signed payload

type VerifierServiceCreator

type VerifierServiceCreator interface {
	Sign(payload *AuthClaims) (string, error)
	UnSign(req *http.Request) (*AuthClaims, error)
}

VerifierServiceCreator ...

func NewVerifierService

func NewVerifierService(opts *Options) VerifierServiceCreator

NewVerifierService create a service

Directories

Path Synopsis
Package mock is a generated GoMock package.
Package mock is a generated GoMock package.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL