jwt

package
v0.4.5 Latest Latest
Warning

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

Go to latest
Published: Nov 5, 2020 License: MIT Imports: 8 Imported by: 0

README

JWTMiddleware

> 描述:Token 验证和解析
> 配置 JWTMiddleware 中间件需要的参数

```
import (
    "github.com/hanguangbaihuo/sparrow_cloud_go/middleware/jwt"
)

app := iris.New()
jwtMiddleware := jwt.DefaultJwtMiddleware("your_jwt_secret")
// 自定义jwt中间件配置
// jwtMiddleware := jwt.New(jwt.Config{
//      ValidationKeyGetter: func(token *jwt.Token) (interface{}, error) {
// 	    return []byte("jwt_secret"), nil
// 	    },
// 	    SigningMethod: jwt.SigningMethodHS256,
//})

// 全局添加中间件
app.Use(jwtMiddleware.Serve)
```

注意

jwt.DefaultJwtMiddleware("your_jwt_secret")
上面的默认生成JWT中间件只会对携带jwt token的数据进行验证,
如果token过期或者解析无效则直接返回错误
如果没有携带token,则直接放过。
因此,如果用户的接口需要认证,还需要在接口中添加auth中间件认证。详见: github.com/hanguangbaihuo/sparrow_cloud_go/middleware/auth

获取原生token

token := ctx.Values().Get(jwt.RawTokenKey)
if token == nil {
    //不存在
} else {
    token = token.(string)
}

Documentation

Index

Constants

View Source
const (
	//DefaultContextKey jwt
	DefaultContextKey = "jwt"

	//RawTokenKey token
	RawTokenKey = "token"
)

Variables

View Source
var (
	NewToken           = jwt.New
	NewTokenWithClaims = jwt.NewWithClaims
)

Shortcuts to create a new Token.

View Source
var (
	SigningMethodHS256 = jwt.SigningMethodHS256
	SigningMethodHS384 = jwt.SigningMethodHS384
	SigningMethodHS512 = jwt.SigningMethodHS512
)

HS256 and company.

View Source
var (
	SigningMethodRS256 = jwt.SigningMethodRS256
	SigningMethodRS384 = jwt.SigningMethodRS384
	SigningMethodRS512 = jwt.SigningMethodRS512
)

RS256 and company.

View Source
var (
	SigningMethodES256 = jwt.SigningMethodES256
	SigningMethodES384 = jwt.SigningMethodES384
	SigningMethodES512 = jwt.SigningMethodES512
)

ECDSA - EC256 and company.

View Source
var (
	// ErrTokenMissing is the error value that it's returned when
	// a token is not found based on the token extractor.
	ErrTokenMissing = errors.New("required authorization token not found")

	// ErrTokenInvalid is the error value that it's returned when
	// a token is not valid.
	ErrTokenInvalid = errors.New("token is invalid")

	// ErrTokenExpired is the error value that it's returned when
	// a token value is found and it's valid but it's expired.
	ErrTokenExpired = errors.New("token is expired")
)

Functions

func FromAuthHeader

func FromAuthHeader(ctx context.Context) (string, error)

FromAuthHeader is a "TokenExtractor" that takes a give context and extracts the JWT token from the Authorization header.

func FromAuthHeaderToken

func FromAuthHeaderToken(ctx context.Context) (string, error)

FromAuthHeaderToken is a "TokenExtractor" that takes a give context and extracts the JWT token from the Authorization header, header key is "token".

func OnError

func OnError(ctx context.Context, err error)

OnError is the default error handler. Use it to change the behavior for each error. See `Config.ErrorHandler`.

Types

type Claims

type Claims = jwt.Claims

Claims must just have a Valid method that determines if the token is invalid for any supported reason.

A type alias for jwt.Claims.

type Config

type Config struct {
	// The function that will return the Key to validate the JWT.
	// It can be either a shared secret or a public key.
	// Default value: nil
	ValidationKeyGetter jwt.Keyfunc
	// The name of the property in the request where the user (&token) information
	// from the JWT will be stored.
	// Default value: "jwt"
	ContextKey string
	// The function that will be called when there's an error validating the token
	// Default value:
	ErrorHandler errorHandler
	// A boolean indicating if the credentials are required or not
	// Default value: false
	CredentialsOptional bool
	// A function that extracts the token from the request
	// Default: FromAuthHeader (i.e., from Authorization header as bearer token)
	Extractor TokenExtractor
	// When set, all requests with the OPTIONS method will use authentication
	// if you enable this option you should register your route with iris.Options(...) also
	// Default: false
	EnableAuthOnOptions bool
	// When set, the middelware verifies that tokens are signed with the specific signing algorithm
	// If the signing method is not constant the ValidationKeyGetter callback can be used to implement additional checks
	// Important to avoid security issues described here: https://auth0.com/blog/2015/03/31/critical-vulnerabilities-in-json-web-token-libraries/
	// Default: nil
	SigningMethod jwt.SigningMethod
	// When set, the expiration time of token will be check every time
	// if the token was expired, expiration error will be returned
	// Default: false
	Expiration bool
}

Config is a struct for specifying configuration options for the jwt middleware.

type MapClaims

type MapClaims = jwt.MapClaims

MapClaims type that uses the map[string]interface{} for JSON decoding This is the default claims type if you don't supply one

A type alias for jwt.MapClaims.

type Middleware

type Middleware struct {
	Config Config
}

Middleware the middleware for JSON Web tokens authentication method

func DefaultJwtMiddleware added in v0.2.1

func DefaultJwtMiddleware(jwtSecret string) *Middleware

DefaultJwtMiddleware return default iris jwt middleware use like this: jwtMiddleware := DefultJwtMiddleware("your_jwt_secret") app.Use(jwtMiddleware.Serve)

func New

func New(cfg ...Config) *Middleware

New constructs a new Secure instance with supplied options.

func (*Middleware) CheckJWT

func (m *Middleware) CheckJWT(ctx context.Context) (*jwt.Token, error)

CheckJWT the main functionality, checks for token

func (*Middleware) Get

func (m *Middleware) Get(ctx context.Context) *jwt.Token

Get returns the user (&token) information for this client/request

func (*Middleware) Serve

func (m *Middleware) Serve(ctx context.Context)

Serve the middleware's action

type Token

type Token = jwt.Token

Token for JWT. Different fields will be used depending on whether you're creating or parsing/verifying a token.

A type alias for jwt.Token.

type TokenExtractor

type TokenExtractor func(context.Context) (string, error)

TokenExtractor is a function that takes a context as input and returns either a token or an error. An error should only be returned if an attempt to specify a token was found, but the information was somehow incorrectly formed. In the case where a token is simply not present, this should not be treated as an error. An empty string should be returned in that case.

func FromFirst

func FromFirst(extractors ...TokenExtractor) TokenExtractor

FromFirst returns a function that runs multiple token extractors and takes the first token it finds

func FromParameter

func FromParameter(param string) TokenExtractor

FromParameter returns a function that extracts the token from the specified query string parameter

Jump to

Keyboard shortcuts

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