gojwt

package module
v0.0.0-...-11d508c Latest Latest
Warning

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

Go to latest
Published: Aug 19, 2019 License: MIT Imports: 11 Imported by: 0

README

golang + JWT = goJwt (GoJweto)

goJwt (Golang for JSON Web Token) is a Golang implementation for REST service security.
You can see an extended doc in godocs.

JWT

JWT (JSON Web Token) is a standard to make secure a connection in a compact URL-safe means of representing claims to be transferred between two parties.
See more info here.

goJwt

  • First, You should create your RSA key pairs.
    Create /tls-ssl/jwtkeys/ directory in your root path of your project:

    cd jwt/keys
    openssl genrsa -out rsakey.pem 2048
    openssl rsa -in rsakey.pem -pubout > rsakey.pem.pub
    
  • Or You should create your ECDSA key pairs.
    Create /tls-ssl/jwtkeys/ directory in your root path of your project:

    • First, select a curve list:

      openssl ecparam -list_curves
      
    • Then, select secp256r1 or secp384r1:

      cd jwt/keys
      openssl ecparam -genkey -name secp384r1 | sed -e '1,3d' > ecdsakey.pem
      openssl ec -in ecdsakey.pem -pubout > ecdsakey.pem.pub
      
  • Next, You should download my library:

    go get github.com/fmorenovr/gojwt/
    
  • Then, you should use for differents implements in Go.

    • First, Create a HMAC_SHA gojwt object, specifying nameServer, headerAuth in request, secretKey, bytes, and expiration time (in hours).

        var GojwtObject, _ = gojwt.NewGojwtHMAC_SHA("JnzadsServer", "jnzads-rest", "Jnzads-rest-JWT", "512", 24)
      
    • Or a RSA/ECDA Object, specifying nameServer, headerAuth in request, privKeypath, pubKeyPath, bytes, and expiration time (in hours).

        var GojwtObject, _ = gojwt.NewGojwtRSA("JnzadsServer", "Jnzads-rest-JWT", privKeyPath, pubKeyPath, "384", 24)
        var GojwtObject, _ = gojwt.NewGojwtECDSA("JnzadsServer", "Jnzads-rest-JWT", privKeyPath, pubKeyPath, "256", 24)
      
    • Then, generate the token string specifyind a nameserver and username:

        tokenString, _ := GojwtObject.CreateToken(Username)
      
    • Using in Go net/http package:

      • Add examples/goJwtHandler.go in your controllers directory.

      • Then, in your muxServe add:

          muxHttp.HandleFunc("/setToken", setTokenHandler)
          muxHttp.HandleFunc("/login", LoginHandler)
          muxHttp.HandleFunc("/profile", gojwt.MiddlewareGojwtHeaders(WithAuthHandler, NoAuthHandler))
        
    • Using in BeeGo:

      • Add examples/goJwtBeeGoController.go in your controllers directory.

      • And, in other controllers, add your new controller instead beegoController.

            import (
              "encoding/json";
              "restfulapi-beego/models";
              //"github.com/astaxie/beego";
            )
        
            type AlertController struct {
                //beego.Controller
                GoJwtController
            }
        

Documentation

Overview

Package Gojwt or goJweto is a JSON Web Tokens library implemented in golang.

See Readme.md for more info.

Example (CreateGoJwtObjects)

main function with hello world in goJwt

var (
	privECDSAKeyPath = "asdsa"
	pubECDSAKeyPath  = ""
	privRSAKeyPath   = ""
	pubRSAKeyPath    = ""
)
GojwtObject, err := gojwt.NewGojwt()
fmt.Println("Example with Default config GoJwt Object: ", GojwtObject, "with error: ", err)

GojwtObject, err = gojwt.NewGojwtHMAC_SHA("JnzadsServer", "jnzads-rest", "Jnzads-rest-JWT", "512", 24)
fmt.Println("Example with empty secret Key and HMAC method: ", GojwtObject, "with error: ", err)

GojwtObject, err = gojwt.NewGojwtRSA("JnzadsServer", "Jnzads-rest-JWT", privKeyPath, pubKeyPath, "384", 24)
fmt.Println("Example with empty secret Key and RSA/ECDSA method: ", GojwtObject, "with error: ", err)

GojwtObject, err = gojwt.NewGojwtECDSA("JnzadsServer", "Jnzads-rest-JWT", privKeyPath, pubKeyPath, "256", 24)
fmt.Println("Example with empty secret Key and RSA/ECDSA method: ", GojwtObject, "with error: ", err)
Output:

Index

Examples

Constants

This section is empty.

Variables

View Source
var (
	GojwtErrInvalidEmptySecretKey  = errors.New("Invalid Empty Secret Key.\n")
	GojwtErrInvalidEmptyPrivateKey = errors.New("Invalid Empty Path Private Key.\n")
	GojwtErrInvalidEmptyPublicKey  = errors.New("Invalid Empty Path Public Key.\n")
	GojwtErrInvalidEmptyToken      = errors.New("Invalid Empty Token")
	GojwtErrInvalidAlgorithm       = errors.New("Invalid Algorithm to create token.\n")
	GojwtErrInvalidRSABytes        = errors.New("Invalid RSA len bytes Algorithm.\n")
	GojwtErrInvalidECDSABytes      = errors.New("Invalid ECDSA len bytes Algorithm.\n")
	GojwtErrInvalidHMACHSABytes    = errors.New("Invalid HMAC-SHA len bytes Algorithm.\n")
	GojwtErrInvalidToken           = errors.New("Invalid Token")
	GojwtErrBadFormatToken         = errors.New("Invalid Format Token")
	GojwtErrTokenExpired           = errors.New("Invalid Token is Expired.\n")
	GojwtErrNotWorkToken           = errors.New("Invalid Token is not working.\n")
	GojwtErrIsNotPubECDSAKey       = errors.New("Is not an ECDSA Public Key.\n")
	GojwtErrIsNotPrivECDSAKey      = errors.New("Is not an ECDSA Private Key.\n")
	GojwtErrIsNotPubRSAKey         = errors.New("Is not a RSA Public Key.\n")
	GojwtErrIsNotPrivRSAKey        = errors.New("Is not a RSA Private Key.\n")
	GojwtErrTriedToMarshal         = errors.New("Tried to Marshal Invalid Type.\n")
	GojwtErrInterfaceNotExist      = errors.New("Interface passed does not exist.\n")
)

Functions

func FromJSON

func FromJSON(data []byte) (map[string]interface{}, error)

FromJSON Convert to JSON format the elements

func JsonResponse

func JsonResponse(response interface{}, w http.ResponseWriter)

Write in JSON Format

func MiddlewareGojwtHeaders

func MiddlewareGojwtHeaders(pageHandler, noAuthHandler http.HandlerFunc, o *Gojwt) http.HandlerFunc

middleware gojwt

func ToJSON

func ToJSON(s interface{}) ([]byte, error)

ToJSON return JSON format of elements

Types

type Claims

type Claims struct {
	NameServer string `json:"nameServer,omitempty"`
	jwt.StandardClaims
}

JWT schema of the data it will store

type CredentialsAuth

type CredentialsAuth struct {
	Token  string `json:"Token"`
	Logged bool   `json:"Logged"`
}

Struct to encapsulate if the username is not logged

type CredentialsNoAuth

type CredentialsNoAuth struct {
	Logged bool `json:"Logged"`
}

Struct to encapsulate if the username is not logged

type Gojwt

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

GoJwt object

func NewGojwt

func NewGojwt() (*Gojwt, error)

Create a New GoJwt Instance with HMAC-SHA encrypt method by default

func NewGojwtECDSA

func NewGojwtECDSA(nameserver, headerkey, privKeyPath, pubKeyPath, lenbytes string, hours time.Duration) (*Gojwt, error)

Create a New GoJwt Instance with ECDSA method

func NewGojwtHMAC_SHA

func NewGojwtHMAC_SHA(nameserver, headerkey, secretkey, lenbytes string, hours time.Duration) (*Gojwt, error)

Create a New GoJwt Instance with HMAC-SHA method

func NewGojwtRSA

func NewGojwtRSA(nameserver, headerkey, privKeyPath, pubKeyPath, lenbytes string, hours time.Duration) (*Gojwt, error)

Create a New GoJwt Instance with RSA method

func (*Gojwt) CreateToken

func (o *Gojwt) CreateToken(username string) (tokenString string, err error)

Create token with a specific encrypt method

func (*Gojwt) GetECDSAPrivKey

func (o *Gojwt) GetECDSAPrivKey() *ecdsa.PrivateKey

just for method ECDSA get ECDSA private key

func (*Gojwt) GetECDSAPubKey

func (o *Gojwt) GetECDSAPubKey() *ecdsa.PublicKey

get ECDSA public key

func (*Gojwt) GetEncryptLenBytes

func (o *Gojwt) GetEncryptLenBytes() string

get bytes of encrypt method

func (*Gojwt) GetEncryptMethod

func (o *Gojwt) GetEncryptMethod() string

get current encrypt method

func (*Gojwt) GetHeaderKey

func (o *Gojwt) GetHeaderKey() string

get Header authorization

func (*Gojwt) GetNameServer

func (o *Gojwt) GetNameServer() string

get Name Server

func (*Gojwt) GetNumHoursDuration

func (o *Gojwt) GetNumHoursDuration() time.Duration

get hours of token duration

func (*Gojwt) GetPrivKeyPath

func (o *Gojwt) GetPrivKeyPath() string

get PATH of Private key

func (*Gojwt) GetPubKeyPath

func (o *Gojwt) GetPubKeyPath() string

get PATH of Public key

func (*Gojwt) GetRSAPrivKey

func (o *Gojwt) GetRSAPrivKey() *rsa.PrivateKey

just for method RSA get RSA private key

func (*Gojwt) GetRSAPubKey

func (o *Gojwt) GetRSAPubKey() *rsa.PublicKey

get RSA public key

func (*Gojwt) GetSecretByte

func (o *Gojwt) GetSecretByte() []byte

get secret key word convert in bytes

func (*Gojwt) GetSecretKey

func (o *Gojwt) GetSecretKey() string

get secret key word to encrypt using hmac-sha

func (*Gojwt) SetEncryptLenBytes

func (o *Gojwt) SetEncryptLenBytes(lenBytes string)

set bytes of encrypt method

func (*Gojwt) SetEncryptMethod

func (o *Gojwt) SetEncryptMethod(method string)

change encrypt method

func (*Gojwt) SetHeaderKey

func (o *Gojwt) SetHeaderKey(name string)

set Header authorization

func (*Gojwt) SetNameServer

func (o *Gojwt) SetNameServer(name string)

set Name Server

func (*Gojwt) SetNumHoursDuration

func (o *Gojwt) SetNumHoursDuration(hours time.Duration)

set hours of token duration

func (*Gojwt) SetPrivKeyPath

func (o *Gojwt) SetPrivKeyPath(path string)

set PATH of Private key

func (*Gojwt) SetPubKeyPath

func (o *Gojwt) SetPubKeyPath(path string)

path of keys RSA/ECDSA set PATH of Public key

func (*Gojwt) SetSecretKey

func (o *Gojwt) SetSecretKey(name string)

just for method HMACSHA set secret key word to encrypt using hmac-sha

func (*Gojwt) ValidateToken

func (o *Gojwt) ValidateToken(tokenString string) (isValid bool, username string, err error)

validate token with a specific encrypt method

Jump to

Keyboard shortcuts

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