jwt package for gin go applications

Overview

gin-jwt tests codecov codebeat badge

jwt package for gin go applications

Usage

Download using go module:

go get github.com/ennaque/gin-jwt

Import it in your code:

import gwt "github.com/ennaque/gin-jwt"

Example

package main

func main() {
  router := gin.Default()

  db, err := gorm.Open(postgres.Open(GetDBConnectionData()))
  if err != nil {
    panic("db con failed")
  }
  
  gs, err := storage.InitGormStorage(db, "jwt1234_")
  if err != nil {
    panic(err)
  }
  
  auth, _ := gwt.Init(gwt.Settings{
    Authenticator: func(c *gin.Context) (string, error) {
      var loginCredentials LoginCredentials
      if err := c.ShouldBind(&loginCredentials); err != nil {
        return "", errors.New("bad request")
      }
      user, err := GetUserByCredentials(&loginCredentials)
      if err != nil {
        return "", errors.New("unauthorized")
      }
      return user.GetId(), nil
    },
    AccessSecretKey: []byte("access_super_secret"),
    RefreshSecretKey: []byte("refresh_super_secret"),
    Storage: gs,
    // Storage: &storage.RedisStorage{Con: GetRedisClient()},
    GetUserFunc: func(userId string) (interface{}, error) {
      return GetUserById(userId)
    },
    AccessLifetime: time.Minute * 15,
    RefreshLifetime: time.Hour * 48,
    SigningMethod: "HS256",
    AuthHeadName: "Bearer",
  })
  
  a := router.Group("auth") {
    a.POST("/logout", auth.Handler.GetLogoutHandler())
    a.POST("/login", auth.Handler.GetLoginHandler())
    a.POST("/refresh", auth.Handler.GetRefreshHandler())
    a.POST("/force-logout", auth.Handler.GetForceLogoutHandler())
  }
  
  router.Group("/api").Use(auth.Middleware.GetAuthMiddleware()).GET("/get-user-id", func(c *gin.Context) {
    user, _ := c.Get("user")
    c.JSON(http.StatusOK, gin.H{
      "userId": user.(*models.User).ID,
    })
  })
  
  err := router.Run(":8000")
  if err != nil {
    panic("err")
  }
}

Get tokens

&password= " http://localhost:8000/auth/login ">
curl -X POST -d "username=
    
     &password=
     
      "
     
     http://localhost:8000/auth/login

username and password params may differ depending on your login credentials

Response 200 OK:

{
    "access_expire": "1633653988",
    "access_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhY2Nlc3NfdXVpZCI6IjlkODFmNjRkLWY0ZWYtNDA2NC04YTY3LTRjNjMzY2MxNjExOCIsImV4cCI6MTYzMzY1Mzk4OCwicmVmcmVzaF91dWlkIjoiOTU3NWU5ZDEtNWFjOS00YmIzLTkwOGItODA3MmJkNDdmOTM2IiwidXNlcl9pZCI6IjI5In0.0CfHPjkVFiQixa4SdE5EUhu23imNri02QMFsDDXJHzg",
    "refresh_expire": "1633739788",
    "refresh_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhY2Nlc3NfdXVpZCI6IjlkODFmNjRkLWY0ZWYtNDA2NC04YTY3LTRjNjMzY2MxNjExOCIsImV4cCI6MTYzMzczOTc4OCwicmVmcmVzaF91dWlkIjoiOTU3NWU5ZDEtNWFjOS00YmIzLTkwOGItODA3MmJkNDdmOTM2IiwidXNlcl9pZCI6IjI5In0.UvPTvVaNkAgFVTrAEoaUK1n4iIYFGh1yNqPzzNbtUUM"
}

Refresh token

" http://localhost:8000/auth/refresh ">
curl -X POST -d "refresh_token=
   
    "
    http://localhost:8000/auth/refresh

Response 200 OK:

{
    "access_expire":"1633659261",
    "access_token":"eyJhbGciOiJIUzUxMiIsInR5cCI6IkpXVCJ9.eyJhY2Nlc3NfdXVpZCI6ImJiNjBhYzlmLTQ4ZGEtNDlhZC04NTM1LTU5MTJhY2MwZDIwNyIsImV4cCI6MTYzMzY1OTI2MSwicmVmcmVza
F91dWlkIjoiNDkxMWYxZjUtYjk5Ni00ZTEwLWE4NGEtNDg3NGVmNjMzZDc4IiwidXNlcl9pZCI6IjI5In0.tupNFRnANQmOScjWzlnWXzncX0Kxs7M40rsbFs0Vpg-70Ucc7R7vX2e7uAFf1fiAMODfGS5d3PRK3Nwk4RoPzg",
    "refresh_expire":"1633831941",
    "refresh_token":"eyJhbGciOiJIUzUxMiIsInR5cCI6IkpXVCJ9.eyJhY2Nlc3NfdXVpZCI6ImJiNjBhYzlmLTQ4ZGEtNDlhZC04NTM1LTU5MTJhY2MwZDIwNyIsImV4cCI6MTYzMzgzMTk0MSwicmVmcmVz
aF91dWlkIjoiNDkxMWYxZjUtYjk5Ni00ZTEwLWE4NGEtNDg3NGVmNjMzZDc4IiwidXNlcl9pZCI6IjI5In0.lj2nS6-M4GT-T9PHj9ijNY4g6h5hyP0xdVTHCw1M-07aL4zp7HpFrXFrT-V6RWpofaGvM79o64f8WECEqRPjig"
}

Logout

" http://localhost:8000/auth/logout ">
curl -X POST -H "Authorization: Bearer 
   
    "
    http://localhost:8000/auth/logout

Response 200 OK:

{}

Force logout user

This endpoint should be used only by authorized user.

" -d "user_id= " http://localhost:8000/auth/force-logout ">
curl -X POST -H "Authorization: Bearer 
    
     "
     -d "user_id=
    
     "
     http://localhost:8000/auth/force-logout

Response 200 OK:

{}

Additionaly there is a public method gwt.Service.ForceLogoutUser(userId)

Releases(v1.0.5)
Owner
Igor Volkov
Igor Volkov
jwt package for gin go applications

gin-jwt jwt package for gin go applications Usage Download using go module: go get github.com/ennaque/gin-jwt Import it in your code: import gwt "gith

Igor Volkov 2 Apr 21, 2022
JWT wrapper library which makes it simple to use ECDSA based JWT signing

JWT JWT wrapper library which makes it simple to user ECDSA based JWT signing. Usage package main import ( "context" "github.com/infiniteloopcloud

infinite loop 0 Feb 10, 2022
Krakend-jwt-header-rewriter - Kraken Plugin - JWT Header Rewriter

Kraken Plugin - JWT Header Rewriter 1 Plugin Configuration Name Desciption Defau

null 0 Feb 15, 2022
Golang with JWT, Go Gin and MongoDB

User authentication in Golang with JWT, Go Gin and MongoDB Golang backend application that uses JWT tokens for users Locally Up Setup your .env file,

Al Mamun Khan 10 May 27, 2022
A simple user identify template with jwt token and gin, toy project

Simple Docs Register url : /api/auth/register param type value name string username password string password mailbox string mailbox response: { "sta

null 1 Dec 31, 2021
This is a jwt for Gin framework.

JWT for Gin Framework This is a jwt useful for Gin framework. It uses jwt-go to provide a jwt encode and decode token. Usage go get github.com/wyy-go/

null 0 Jan 9, 2022
🔒 JWT with RS-signing methods, designed for Gin.

GinRS 套用在 gin-gonic/gin 基於 RS256 演算法的 JWT 簽署套件。 非對稱金鑰 透過 openssl 產生一個私鑰。 openssl genrsa -out private.key 2048 再透過這個私鑰產生一個公鑰,這個公鑰可以配發到其他伺服器或是第三方的手中用來驗證

TeaCat 1 Feb 23, 2022
A single sign-on solution based on go-oauth2 / oauth2 and gin-gonic/gin

A single sign-on solution based on go-oauth2 / oauth2 and gin-gonic/gin

yinhuanyi 1 Nov 17, 2021
This package provides json web token (jwt) middleware for goLang http servers

jwt-auth jwt auth middleware in goLang. If you're interested in using sessions, checkout my sessions library! README Contents: Quickstart Performance

Adam Hanna 217 Jun 7, 2022
:key: Secure alternative to JWT. Authenticated Encrypted API Tokens for Go.

branca branca is a secure alternative to JWT, This implementation is written in pure Go (no cgo dependencies) and implements the branca token specific

Wesley Hill 165 Jun 21, 2022
An implementation of JOSE standards (JWE, JWS, JWT) in Go

Go JOSE Package jose aims to provide an implementation of the Javascript Object Signing and Encryption set of standards. This includes support for JSO

Square 1.9k Jun 23, 2022
This is an implementation of JWT in golang!

jwt This is a minimal implementation of JWT designed with simplicity in mind. What is JWT? Jwt is a signed JSON object used for claims based authentic

John Rowley 99 May 9, 2022
Golang implementation of JSON Web Tokens (JWT)

jwt-go A go (or 'golang' for search engine friendliness) implementation of JSON Web Tokens NEW VERSION COMING: There have been a lot of improvements s

Dave Grijalva 10.4k Jun 23, 2022
JWT login microservice with plugable backends such as OAuth2, Google, Github, htpasswd, osiam, ..

loginsrv loginsrv is a standalone minimalistic login server providing a JWT login for multiple login backends. ** Attention: Update to v1.3.0 for Goog

tarent 1.9k Jun 23, 2022
Simple JWT Golang

sjwt Simple JSON Web Token - Uses HMAC SHA-256 Example // Set Claims claims := New() claims.Set("username", "billymister") claims.Set("account_id", 86

Brian Voelker 98 May 22, 2022
simple-jwt-provider - Simple and lightweight provider which exhibits JWTs, supports login, password-reset (via mail) and user management.

Simple and lightweight JWT-Provider written in go (golang). It exhibits JWT for the in postgres persisted user, which can be managed via api. Also, a password-reset flow via mail verification is available. User specific custom-claims also available for jwt-generation and mail rendering.

Max 25 May 18, 2022
The easiest JWT library to GO

JWT Go The easiest JWT Library that could be a starting point for your project. Installation go get github.com/supanadit/jwt-go Quick Start package ma

Supan Adit Pratama 15 Jan 13, 2022
YSHOP-GO基于当前流行技术组合的前后端RBAC管理系统:Go1.15.x+Beego2.x+Jwt+Redis+Mysql8+Vue 的前后端分离系统,权限控制采用 RBAC,支持数据字典与数据权限管理,支持动态路由等

YSHOP-GO 后台管理系统 项目简介 YSHOP-GO基于当前流行技术组合的前后端RBAC管理系统:Go1.15.x+Beego2.x+Jwt+Redis+Mysql8+Vue 的前后端分离系统,权限控制采用 RBAC,支持数据字典与数据权限管理,支持动态路由等 体验地址: https://go

null 102 Jun 23, 2022
Small Lambda function which performs a Aws:Sts:AssumeRole based on the presented JWT-Token

About This implements a AWS Lambda handler which takes a JWT-Token, validates it and then performs a Aws:Sts:AssumeRole based on preconfigured rules.

AOE 4 Nov 24, 2021