jwt

package module
v1.1.5 Latest Latest
Warning

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

Go to latest
Published: Mar 18, 2022 License: MIT Imports: 12 Imported by: 1

README

Overview

  1. Issue private key
openssl genrsa -out private.key 2048
  1. Example main.go
package main

import (
	"github.com/gin-gonic/gin"
	"github.com/ken109/gin-jwt"
	"fmt"
	"net/http"
)

const MyRealm = "my-realm"

func main() {
	// setup
	_ = jwt.SetUp(
		jwt.Option{
			Realm:            MyRealm,
			SigningAlgorithm: jwt.RS256,
			PrivKeyFile:      "private.key",
		},
	)

	r := gin.New()
	r.POST("/login", Login)
	r.GET("/refresh", RefreshToken)

	auth := r.Group("/api")

	// Set the middleware on the route you want to authenticate
	auth.Use(jwt.MustVerify(MyRealm))

	auth.GET(
		"/hello", func(c *gin.Context) {
			claims := jwt.GetClaims(c)

			fmt.Println(claims["admin"].(bool)) // true

			c.JSON(http.StatusOK, claims)
		},
	)

	if err := r.Run(":8080"); err != nil {
		panic(err)
	}
}

func Login(c *gin.Context) {
	password := "test"

	if password != "test" {

		c.JSON(http.StatusForbidden, "login failed")

		return
	} else {
		// Issue Token
		token, refreshToken, _ := jwt.IssueToken(
			MyRealm,
			jwt.Claims{
				"admin": true,
			},
		)

		c.JSON(
			http.StatusOK, gin.H{
				"token":         token,
				"refresh_token": refreshToken,
			},
		)
	}
}

func RefreshToken(c *gin.Context) {
	ok, token, refreshToken, _ := jwt.RefreshToken(MyRealm, c.Query("refresh_token"))
	if !ok {
		c.Status(http.StatusUnauthorized)
		return
	}

	c.JSON(
		http.StatusOK, gin.H{
			"token":         token,
			"refresh_token": refreshToken,
		},
	)
}

Documentation

Index

Constants

Variables

This section is empty.

Functions

func GetClaim added in v1.1.2

func GetClaim(c *gin.Context, key string) (value interface{}, ok bool)

func IssueToken

func IssueToken(realm string, claims Claims) (token string, refreshToken string, err error)

func MustVerify added in v1.1.3

func MustVerify(realm string) func(c *gin.Context)

func RefreshToken added in v1.1.0

func RefreshToken(realm string, refreshToken string) (ok bool, newToken string, newRefreshToken string, err error)

func SetUp

func SetUp(option Option) error

func TryVerify added in v1.1.3

func TryVerify(realm string) func(c *gin.Context)

Types

type Claims

type Claims map[string]interface{}

func GetClaims

func GetClaims(c *gin.Context) Claims

type Option

type Option struct {
	Realm string

	SigningAlgorithm SignatureAlgorithm

	SecretKey []byte

	PrivKeyFile  string
	PrivKeyBytes []byte

	Timeout        time.Duration
	RefreshTimeout time.Duration

	Issuer  string
	Subject string
	// contains filtered or unexported fields
}

type SignatureAlgorithm added in v1.1.0

type SignatureAlgorithm string

Jump to

Keyboard shortcuts

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