grpcjwt

package module
v0.4.0 Latest Latest
Warning

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

Go to latest
Published: Oct 31, 2023 License: MIT Imports: 14 Imported by: 0

README

GoDoc Build Status Sourcegraph Go Report Card GitHub tag

grpc-jwt - JWT recipe for gRPC-based server

preamble: almost all code for JWT stuff was taken from appleyboy's repository

Table of Contents

Usage

If you are planning to use private/public keys, you should generate it first. There is example of generting RS512 keys below:

ssh-keygen -t rsa -b 4096 -m PEM -f jwtRS512.key
openssl rsa -in jwtRS512.key -pubout -outform PEM -out jwtRS512.key.pub

If you want to re-build *.pb.go files

protoc -I . ./*.proto --go_out=./ --go-grpc_out=./ --go-grpc_opt=paths=source_relative --experimental_allow_proto3_optional
Server example

Whole example for server-side is here

How to run server-side:

go run .
Client example

Whole example for client-side is here

How to run client-side:

go run .

Support

If you have troubles or questions please open an issue. PRs are welcome!

Dependencies

  • github.com/golang-jwt/jwt - License is MIT
  • gRPC and protobuf for doing "'client-server'" application - grpc. License is Apache-2.0

License

You can check it here

Documentation

Overview

Package grpcjwt is a generated protocol buffer package.

It is generated from these files:

jwt.proto

It has these top-level messages:

LoginRequest
LoginResponse
NoArguments
RefreshTokenResponse

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrMissingSecretKey indicates Secret key is required
	ErrMissingSecretKey = fmt.Errorf("secret key is required")

	// ErrForbidden when HTTP status 403 is given
	ErrForbidden = fmt.Errorf("you don't have permission to access this resource")

	// ErrMissingAuthenticatorFunc indicates Authenticator is required
	ErrMissingAuthenticatorFunc = fmt.Errorf("ginJWTMiddleware.Authenticator func is undefined")

	// ErrMissingLoginValues indicates a user tried to authenticate without username or password
	ErrMissingLoginValues = fmt.Errorf("missing Username or Password")

	// ErrFailedAuthentication indicates authentication failed, could be faulty username or password
	ErrFailedAuthentication = fmt.Errorf("incorrect Username or Password")

	// ErrFailedTokenCreation indicates JWT Token failed to create, reason unknown
	ErrFailedTokenCreation = fmt.Errorf("failed to create JWT Token")

	// ErrExpiredToken indicates JWT token has expired. Can't refresh.
	ErrExpiredToken = fmt.Errorf("token is expired")

	// ErrEmptyAuthHeader can be thrown if authing with a HTTP header, the Auth header needs to be set
	ErrEmptyAuthHeader = fmt.Errorf("auth header is empty")

	// ErrMissingExpField missing exp field in token
	ErrMissingExpField = fmt.Errorf("missing exp field")

	// ErrWrongFormatOfExp field must be float64 format
	ErrWrongFormatOfExp = fmt.Errorf("exp must be float64 format")

	// ErrInvalidAuthHeader indicates auth header is invalid, could for example have the wrong Realm name
	ErrInvalidAuthHeader = fmt.Errorf("auth header is invalid")

	// ErrEmptyQueryToken can be thrown if authing with URL Query, the query token variable is empty
	ErrEmptyQueryToken = fmt.Errorf("query token is empty")

	// ErrEmptyCookieToken can be thrown if authing with a cookie, the token cookie is empty
	ErrEmptyCookieToken = fmt.Errorf("cookie token is empty")

	// ErrEmptyParamToken can be thrown if authing with parameter in path, the parameter in path is empty
	ErrEmptyParamToken = fmt.Errorf("parameter token is empty")

	// ErrInvalidSigningAlgorithm indicates signing algorithm is invalid, needs to be HS256, HS384, HS512, RS256, RS384 or RS512
	ErrInvalidSigningAlgorithm = fmt.Errorf("invalid signing algorithm")

	// ErrNoPrivKeyFile indicates that the given private key is unreadable
	ErrNoPrivKeyFile = fmt.Errorf("private key file unreadable")

	// ErrNoPubKeyFile indicates that the given public key is unreadable
	ErrNoPubKeyFile = fmt.Errorf("public key file unreadable")

	// ErrInvalidPrivKey indicates that the given private key is invalid
	ErrInvalidPrivKey = fmt.Errorf("private key invalid")

	// ErrInvalidPubKey indicates the the given public key is invalid
	ErrInvalidPubKey = fmt.Errorf("public key invalid")
)

Functions

func ExtractClaimsFromToken

func ExtractClaimsFromToken(token *jwt.Token) map[string]interface{}

ExtractClaimsFromToken help to extract the JWT claims from token

func RegisterJWTServiceServer

func RegisterJWTServiceServer(s *grpc.Server, srv JWTServiceServer)

Types

type JWTInterceptor

type JWTInterceptor struct {
	JWTServiceServer
	// contains filtered or unexported fields
}

JWTInterceptor Interceptor for JWT validation. Wraps JWTServiceServer structure

func NewJWTInterceptor

func NewJWTInterceptor(jwtOptions *JWTgRPC, methods ...string) (*JWTInterceptor, error)

NewJWTInterceptor Creates new instance of JWTInterceptor jwtOptions - pointer to object of type JWTgRPC methods - what methods do you want to intercept for JWT validation (optional)

func (*JWTInterceptor) AuthInterceptor

func (jwtService *JWTInterceptor) AuthInterceptor(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (interface{}, error)

AuthInterceptor Intercept provided methods and check token

func (*JWTInterceptor) AuthStreamInterceptor added in v0.3.0

func (jwtService *JWTInterceptor) AuthStreamInterceptor(srv interface{}, ss grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) error

AuthInterceptor Intercept provided methods and check token

func (*JWTInterceptor) GetClaimsFromJWT added in v0.2.2

func (jwtService *JWTInterceptor) GetClaimsFromJWT(token string) (map[string]interface{}, error)

GetClaimsFromJWT provides access to private method GetClaimsFromJWT

func (*JWTInterceptor) IgnoreMethods

func (jwtService *JWTInterceptor) IgnoreMethods(methods ...string)

IgnoreMethods Delete methods from list for interception

func (*JWTInterceptor) InterceptMethods

func (jwtService *JWTInterceptor) InterceptMethods(methods ...string)

InterceptMethods Provide list of methods for interception

func (*JWTInterceptor) LoginHandler

func (jwtService *JWTInterceptor) LoginHandler(ctx context.Context, in *LoginRequest) (*LoginResponse, error)

LoginHandler Implement LoginHandler() to match interface of JWTServiceServer in jwt.pb.go

func (*JWTInterceptor) ParseToken added in v0.2.1

func (jwtService *JWTInterceptor) ParseToken(token string) (*jwt.Token, error)

ParseToken provides access to private method ParseToken

func (*JWTInterceptor) RefreshToken added in v0.2.0

func (jwtService *JWTInterceptor) RefreshToken(ctx context.Context, in *NoArguments) (*RefreshTokenResponse, error)

RefreshToken Implement RefreshToken() to match interface of JWTServiceServer in jwt.pb.go

type JWTServiceClient

type JWTServiceClient interface {
	LoginHandler(ctx context.Context, in *LoginRequest, opts ...grpc.CallOption) (*LoginResponse, error)
	RefreshToken(ctx context.Context, in *NoArguments, opts ...grpc.CallOption) (*RefreshTokenResponse, error)
}

func NewJWTServiceClient

func NewJWTServiceClient(cc *grpc.ClientConn) JWTServiceClient

type JWTServiceServer

type JWTServiceServer interface {
	LoginHandler(context.Context, *LoginRequest) (*LoginResponse, error)
	RefreshToken(context.Context, *NoArguments) (*RefreshTokenResponse, error)
}

type JWTgRPC

type JWTgRPC struct {
	Realm            string
	SigningAlgorithm string
	Key              []byte
	Timeout          time.Duration
	MaxRefresh       time.Duration
	IdentityKey      string
	TokenLookup      string
	TokenHeadName    string
	TimeFunc         func() time.Time
	PrivKeyFile      string
	PubKeyFile       string

	SendAuthorization bool
	DisabledAbort     bool
	PayloadFunc       func(data interface{}) map[string]interface{}
	IdentityHandler   func(claims map[string]interface{}) interface{}
	Authenticator     func(login, password string) (interface{}, error)
	Authorizator      func(userInfo interface{}) bool
	// contains filtered or unexported fields
}

JWTgRPC Hold jwt-engine methods

func NewJWT

func NewJWT(m *JWTgRPC) (*JWTgRPC, error)

func (*JWTgRPC) CheckIfTokenExpire added in v0.2.0

func (mw *JWTgRPC) CheckIfTokenExpire(tokenString string) (jwt.MapClaims, error)

CheckIfTokenExpire check if token expire

func (*JWTgRPC) GetClaimsFromJWT

func (mw *JWTgRPC) GetClaimsFromJWT(tokenString string) (map[string]interface{}, error)

GetClaimsFromJWT get claims from JWT token

func (*JWTgRPC) Init

func (mw *JWTgRPC) Init() error

func (*JWTgRPC) ParseToken

func (mw *JWTgRPC) ParseToken(token string) (*jwt.Token, error)

ParseToken parse jwt token from gin context

type LoginRequest

type LoginRequest struct {
	Username string `protobuf:"bytes,1,opt,name=username" json:"username,omitempty"`
	Password string `protobuf:"bytes,2,opt,name=password" json:"password,omitempty"`
}

func (*LoginRequest) Descriptor

func (*LoginRequest) Descriptor() ([]byte, []int)

func (*LoginRequest) GetPassword

func (m *LoginRequest) GetPassword() string

func (*LoginRequest) GetUsername

func (m *LoginRequest) GetUsername() string

func (*LoginRequest) ProtoMessage

func (*LoginRequest) ProtoMessage()

func (*LoginRequest) Reset

func (m *LoginRequest) Reset()

func (*LoginRequest) String

func (m *LoginRequest) String() string

type LoginResponse

type LoginResponse struct {
	Code   uint32 `protobuf:"varint,1,opt,name=code" json:"code,omitempty"`
	Token  string `protobuf:"bytes,2,opt,name=token" json:"token,omitempty"`
	Expire uint64 `protobuf:"varint,3,opt,name=expire" json:"expire,omitempty"`
}

func (*LoginResponse) Descriptor

func (*LoginResponse) Descriptor() ([]byte, []int)

func (*LoginResponse) GetCode

func (m *LoginResponse) GetCode() uint32

func (*LoginResponse) GetExpire

func (m *LoginResponse) GetExpire() uint64

func (*LoginResponse) GetToken

func (m *LoginResponse) GetToken() string

func (*LoginResponse) ProtoMessage

func (*LoginResponse) ProtoMessage()

func (*LoginResponse) Reset

func (m *LoginResponse) Reset()

func (*LoginResponse) String

func (m *LoginResponse) String() string

type NoArguments added in v0.2.0

type NoArguments struct {
}

func (*NoArguments) Descriptor added in v0.2.0

func (*NoArguments) Descriptor() ([]byte, []int)

func (*NoArguments) ProtoMessage added in v0.2.0

func (*NoArguments) ProtoMessage()

func (*NoArguments) Reset added in v0.2.0

func (m *NoArguments) Reset()

func (*NoArguments) String added in v0.2.0

func (m *NoArguments) String() string

type RefreshTokenResponse added in v0.2.0

type RefreshTokenResponse struct {
	Code   uint32 `protobuf:"varint,1,opt,name=code" json:"code,omitempty"`
	Token  string `protobuf:"bytes,2,opt,name=token" json:"token,omitempty"`
	Expire uint64 `protobuf:"varint,3,opt,name=expire" json:"expire,omitempty"`
}

func (*RefreshTokenResponse) Descriptor added in v0.2.0

func (*RefreshTokenResponse) Descriptor() ([]byte, []int)

func (*RefreshTokenResponse) GetCode added in v0.2.0

func (m *RefreshTokenResponse) GetCode() uint32

func (*RefreshTokenResponse) GetExpire added in v0.2.0

func (m *RefreshTokenResponse) GetExpire() uint64

func (*RefreshTokenResponse) GetToken added in v0.2.0

func (m *RefreshTokenResponse) GetToken() string

func (*RefreshTokenResponse) ProtoMessage added in v0.2.0

func (*RefreshTokenResponse) ProtoMessage()

func (*RefreshTokenResponse) Reset added in v0.2.0

func (m *RefreshTokenResponse) Reset()

func (*RefreshTokenResponse) String added in v0.2.0

func (m *RefreshTokenResponse) String() string

Directories

Path Synopsis
cmd

Jump to

Keyboard shortcuts

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