質問編集履歴

3

修正

2018/09/07 07:16

投稿

goike
goike

スコア7

test CHANGED
File without changes
test CHANGED
@@ -22,7 +22,7 @@
22
22
 
23
23
  ```
24
24
 
25
- invalid operation: claims["uid"] (type interface {}
25
+ invalid operation: claims["uid"] (type interface {} does not support indexing)
26
26
 
27
27
  ```
28
28
 
@@ -56,13 +56,11 @@
56
56
 
57
57
 
58
58
 
59
- func someHandler (w http.ResponseWrite, r *http.Request) {
59
+ func hogeHandler (w http.ResponseWrite, r *http.Request) {
60
60
 
61
61
  claims := r.Context().Value(tokenKey)
62
62
 
63
- uid := claims["uid"].(string) //<- エラー invalid operation: claims["uid"] (type interface {}
63
+ uid := claims["uid"].(string) //<- エラー invalid operation: claims["uid"] (type interface {} does not support indexing)
64
-
65
- does not support indexing)
66
64
 
67
65
  }
68
66
 

2

内容をはしょり過ぎていたので修正しました

2018/09/07 07:16

投稿

goike
goike

スコア7

test CHANGED
File without changes
test CHANGED
@@ -4,22 +4,66 @@
4
4
 
5
5
 
6
6
 
7
- トークンをパース後のClaimsからどのように取得するのか教えていただきたいです。
8
7
 
8
+
9
- そもそもmap[string]interface{}からの取得方法が間違っているのでしょうか?
9
+ - 渡ってきたトークンから`jwt-go`でClaims(`jwt.MapClaims`)取得
10
+
11
+ - `http.Request.Context()`に入れる
12
+
13
+ - `r.Context().Value()`から`MapClaims`取得
14
+
15
+ - `MapClaims`からvalueを得ようとする
10
16
 
11
17
 
12
18
 
19
+ 上記手順でエラーになってしまいます。なぜか教えていただけると幸いです。
20
+
21
+ contextに入れる前では取得できてます。
22
+
13
23
  ```
14
24
 
15
- token, err := jwt.Parse(t, func(token *jwt.Token) (interface{}, error) {
25
+ invalid operation: claims["uid"] (type interface {}
16
-
17
- return []byte(secretKey), nil
18
-
19
- })
20
-
21
- c := token.Claims.(jwt.MapClaims)
22
-
23
- uid := c["uid"].(string) //<- エラー invalid operation: c["uid"] (type interface {} does not support indexing)
24
26
 
25
27
  ```
28
+
29
+
30
+
31
+ 以下コードです
32
+
33
+ ```
34
+
35
+ func jwtMiddleware(fn http.HandleFunc) http.HandleFunc {
36
+
37
+ return func (w http.ResponseWriter, r *http.Request) {
38
+
39
+ token, err := jwt.Parse(t, func(token *jwt.Token) (interface{}, error) {
40
+
41
+ return []byte(secretKey), nil
42
+
43
+ })
44
+
45
+ claims := token.Claims.(jwt.MapClaims)
46
+
47
+ ctx := r.Context()
48
+
49
+ ctx = context.WithValue(ctx, tokenKey, claims)
50
+
51
+ fn(w, r.WithContext(ctx))
52
+
53
+ }
54
+
55
+ }
56
+
57
+
58
+
59
+ func someHandler (w http.ResponseWrite, r *http.Request) {
60
+
61
+ claims := r.Context().Value(tokenKey)
62
+
63
+ uid := claims["uid"].(string) //<- エラー invalid operation: claims["uid"] (type interface {}
64
+
65
+ does not support indexing)
66
+
67
+ }
68
+
69
+ ```

1

修正

2018/09/07 07:13

投稿

goike
goike

スコア7

test CHANGED
File without changes
test CHANGED
@@ -18,7 +18,7 @@
18
18
 
19
19
  })
20
20
 
21
- c := token.Claims.(MapClaims)
21
+ c := token.Claims.(jwt.MapClaims)
22
22
 
23
23
  uid := c["uid"].(string) //<- エラー invalid operation: c["uid"] (type interface {} does not support indexing)
24
24