LoginSignup
10
4

More than 3 years have passed since last update.

GoでJWTまわりTips

Posted at

jwt-goまわりのTips

基礎

以下の記事が参考になる

Go言語で理解するJWT認証 実装ハンズオン - Qiita
https://qiita.com/po3rin/items/740445d21487dfcb5d9f

claimsにstructを使う

上記の例ではmapを使っているがstructを使うときは以下のようにする
https://godoc.org/github.com/dgrijalva/jwt-go#example-NewWithClaims--StandardClaims

独自のfieldを使うときは以下を参考にする(StandardClaimsを埋め込んだstructを使う)
https://godoc.org/github.com/dgrijalva/jwt-go#ex-NewWithClaims--CustomClaimsType

contextからclaims取得

func GetIDFromContext(r *http.Request) (uint, error) {
    user := r.Context().Value("user")
    claims := user.(*jwt.Token).Claims.(jwt.MapClaims)

    sid, ok := claims["sub"].(string)

    if !ok {
        return 0, errors.New("id type not match")
    }

    id, err := strconv.Atoi(sid)
    if err != nil {
        return 0, err
    }
    return uint(id), nil
}

structとしてパースしたいが、auth0/go-jwt-middleware では内部でjwt.Parseを使っているのでmapで参照する。

jwt自体にはstructとしてパースする関数ParseWithClaimsがある
https://godoc.org/github.com/dgrijalva/jwt-go#ex-ParseWithClaims--CustomClaimsType

test


// func Something(w http.ResponseWriter, r *http.Request) のテスト

// token取得しておく

req := httptest.NewRequest(http.MethodGet, "/", nil)
req.Header.Add("Authorization", fmt.Sprintf("Bearer %v", token))

w := httptest.NewRecorder()

h := JwtMiddleware.Handler(http.HandlerFunc(Something))

h.ServeHTTP(w, req)

if w.Code != http.StatusOK {
    t.Errorf("failed something. want %d got %d (%v)", http.StatusOK, w.Code)
}

swag用Header設定

認可が必要なハンドラに以下を設定する

// @Param Authorization header string true "Bearer"

How to add the custom request header · Issue #29 · swaggo/swag
https://github.com/swaggo/swag/issues/29

// Something godoc
// @Summary Something
// @Description Do something
// @ID get-something
// @Produce  json
// @Param Authorization header string true "Bearer"
// @Router /something [get]
func Something(w http.ResponseWriter, r *http.Request) {
}
10
4
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
10
4