LoginSignup
1
0

gin-jwt の使い方

Last updated at Posted at 2021-02-02

参考ページ
JWT Middleware for Gin Framework

プログラムをクローンします。

git clone https://github.com/appleboy/gin-jwt

サンプルのサーバーの起動

cd gin-jwt/
go run _example/basic/server.go

トークンの取得

get_token.sh
http :8000/login username=admin password=admin  > tmp001.json
#
jq . tmp001.json

実行結果

$ ./get_token.sh 
{
  "code": 200,
  "expire": "2023-05-23T16:52:23+09:00",
  "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE2ODQ4MjgzNDMsImlkIjoiYWRtaW4iLCJvcmlnX2lhdCI6MTY4NDgyNDc0M30.jGHhFUXtDQAlbRtPxN_suH0DLDFYQb1pr60l_pLyabc"
}

トークンの更新

go_refresh.sh
token=`jq .token tmp001.json | sed 's/"//g'`
#
http :8000/auth/refresh_token "Authorization:Bearer ${token}"

ログインのテスト

go_login.sh
token=`jq .token tmp001.json | sed 's/"//g'`
#
http :8000/auth/hello "Authorization:Bearer ${token}"

実行結果

$ ./go_login.sh 
HTTP/1.1 200 OK
Content-Length: 59
Content-Type: application/json; charset=utf-8
Date: Tue, 23 May 2023 06:58:52 GMT

{
    "text": "Hello World.",
    "userID": "admin",
    "userName": "admin"
}

サーバーのプログラムを改造してメッセージを変更

_example/basic/server.go
省略
func helloHandler(c *gin.Context) {
        claims := jwt.ExtractClaims(c)
        user, _ := c.Get(identityKey)
        c.JSON(200, gin.H{
                "userID":   claims[identityKey],
                "userName": user.(*User).UserName,
//              "text":     "Hello World.",
                "text":     "Hello World. こんにちは",
        })
}
省略

サーバーを再起動します。

go run _example/basic/server.go

再びログインをしてみます。

実行結果

{
  "text": "Hello World. こんにちは",
  "userID": "admin",
  "userName": "admin"
}

確認したバージョン

$ go version
go version go1.20.3 linux/amd64
1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0