auth

package module
v1.7.0 Latest Latest
Warning

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

Go to latest
Published: Dec 2, 2018 License: MIT Imports: 4 Imported by: 5

README

Gear-Auth

Auth library base on JWT.

Build Status Coverage Status License GoDoc

Crypto Library

https://github.com/teambition/crypto-go

Demo

Create a token and verify it
auther := auth.New([]byte("key1"))
token, _ := auther.JWT().Sign(jwt.Claims{"test": "OK"})
claims, _ := auther.JWT().Verify(token)
fmt.Println(claims.Get("test"))
// Output: "OK"
jwt with ED25519 and HS256 Alg backup
package main

import (
	"fmt"

	josecrypto "github.com/SermoDigital/jose/crypto"
	josejws "github.com/SermoDigital/jose/jws"
	"github.com/teambition/gear-auth/jwt"
	"github.com/teambition/gear-auth/jwt/ed25519"
)

func main() {
	publicKey, privateKey := ed25519.GenerateKey()
	fmt.Println("publicKey:", publicKey)
	fmt.Println("privateKey:", privateKey)

	keyPair, err := ed25519.KeyPairFrom(publicKey, privateKey)
	if err != nil {
		panic(err)
	}

	jwter := jwt.New()
	jwter.SetSigning(ed25519.SigningMethodED25519, keyPair)
	jwter.SetBackupSigning(josecrypto.SigningMethodHS256, []byte("old key 1"), []byte("old key 2"))

	token, err := jwter.Sign(josejws.Claims{"test": "OK"})
	fmt.Println(err, token)

	claims, err := jwter.Verify(token)
	fmt.Println(err, claims)

	// claims, err = jwter.Verify(some_old_HS256_token)
}
Use with Gear
package main

import (
  "fmt"
  "io/ioutil"
  "net/http"

  "github.com/SermoDigital/jose/jwt"
  "github.com/mozillazg/request"
  "github.com/teambition/gear"
  "github.com/teambition/gear-auth"
)

func NewRequst() *request.Request {
  c := &http.Client{}
  return request.NewRequest(c)
}

func main() {
  auther := auth.New([]byte("some_key"))
  auther.JWT().SetIssuer("Gear")
  // auther.JWT().SetExpiration(time.Hour * 24)

  app := gear.New()

  // use auther as middleware, if authentication failure, next middleware will not run.
  app.UseHandler(auther)

  app.Use(func(ctx *gear.Context) error {
    claims, err := auther.FromCtx(ctx)
    if err != nil {
      return err // means Authentication failure.
    }
    return ctx.JSON(200, claims)
  })
  srv := app.Start()
  defer srv.Close()

  req := NewRequst()
  host := "http://" + srv.Addr().String()

  // create a token
  claims := jwt.Claims{}
  claims.Set("Hello", "world")
  token, _ := auther.JWT().Sign(claims)
  req.Headers["Authorization"] = "Bearer " + token
  res, _ := req.Get(host)
  defer res.Body.Close()

  body, _ := ioutil.ReadAll(res.Body)
  fmt.Println(string(body))
  // Output: {"Hello":"world","iss":"Gear"}
}

Documentation

https://godoc.org/github.com/teambition/gear-auth

License

Gear-Auth is licensed under the MIT license. Copyright © 2016-2018 Teambition.

Documentation

Index

Constants

View Source
const Version = "1.7.0"

Version ...

Variables

This section is empty.

Functions

This section is empty.

Types

type Auth added in v1.3.0

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

Auth is helper type. It combine JWT and Crypto object, and some useful mothod for JWT. You can use it as a gear middleware.

func New added in v1.3.0

func New(keys ...interface{}) *Auth

New returns a Auth instance.

auther := auth.New([]byte("my key"))

func (*Auth) FromCtx added in v1.3.0

func (a *Auth) FromCtx(ctx *gear.Context) (josejwt.Claims, error)

FromCtx will parse and validate token from the ctx, and return it as jwt.Claims. If token not exists or validate failure, a error and a empty jwt.Claims instance returned.

claims, err := auther.FromCtx(ctx)
fmt.Println(claims, err)

func (*Auth) JWT added in v1.3.0

func (a *Auth) JWT() *jwt.JWT

JWT returns internal JWT instance.

func (*Auth) New added in v1.3.0

func (a *Auth) New(ctx *gear.Context) (val interface{}, err error)

New implements gear.Any interface, then we can use it with ctx.Any:

any, err := ctx.Any(auther)
if err != nil {
	return err
}
claims := any.(jwt.Claims)

that is auth.FromCtx doing for us.

func (*Auth) Serve added in v1.3.0

func (a *Auth) Serve(ctx *gear.Context) error

Serve implements gear.Handler interface. We can use it as middleware. It will parse and validate token from the ctx, if succeed, gear's middleware process will go on, otherwise process ended and a 401 error will be to respond to client.

app := gear.New()
auther := auth.New()
app.UseHandler(auther)
// or
app.Use(auther.Serve)

func (*Auth) SetJWT added in v1.3.0

func (a *Auth) SetJWT(j *jwt.JWT)

SetJWT set a JWT instance to auth.

func (*Auth) SetSkipper added in v1.5.1

func (a *Auth) SetSkipper(fn func(*gear.Context) bool) *Auth

SetSkipper set a skip function to auth. If skip function return true, the auth middleware process will be skipped.

func (*Auth) SetTokenParser added in v1.3.0

func (a *Auth) SetTokenParser(ex TokenExtractor)

SetTokenParser set a custom tokenExtractor to auth.

type TokenExtractor

type TokenExtractor func(ctx *gear.Context) (token string)

TokenExtractor is a function that takes a gear.Context as input and returns either a string token or an empty string. Default to:

func(ctx *gear.Context) (token string) {
	if val := ctx.Get("Authorization"); strings.HasPrefix(val, "BEARER ") {
		token = val[7:]
	} else {
		token = ctx.Param("access_token")
	}
	return
}

Directories

Path Synopsis
jwt

Jump to

Keyboard shortcuts

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