| 18 | ) |
| 19 | |
| 20 | func TestVerify(t *testing.T) { |
| 21 | verifier := func(_ context.Context, token string, _ *http.Request) (*TokenInfo, error) { |
| 22 | switch token { |
| 23 | case "valid": |
| 24 | return &TokenInfo{Expiration: time.Now().Add(time.Hour)}, nil |
| 25 | case "invalid": |
| 26 | return nil, ErrInvalidToken |
| 27 | case "oauth": |
| 28 | return nil, ErrOAuth |
| 29 | case "noexp": |
| 30 | return &TokenInfo{}, nil |
| 31 | case "expired": |
| 32 | return &TokenInfo{Expiration: time.Now().Add(-time.Hour)}, nil |
| 33 | default: |
| 34 | return nil, errors.New("unknown") |
| 35 | } |
| 36 | } |
| 37 | |
| 38 | for _, tt := range []struct { |
| 39 | name string |
| 40 | opts *RequireBearerTokenOptions |
| 41 | header string |
| 42 | wantMsg string |
| 43 | wantCode int |
| 44 | }{ |
| 45 | { |
| 46 | "valid", nil, "Bearer valid", |
| 47 | "", 0, |
| 48 | }, |
| 49 | { |
| 50 | "bad header", nil, "Barer valid", |
| 51 | "no bearer token", 401, |
| 52 | }, |
| 53 | { |
| 54 | "invalid", nil, "bearer invalid", |
| 55 | "invalid token", 401, |
| 56 | }, |
| 57 | { |
| 58 | "oauth error", nil, "Bearer oauth", |
| 59 | "oauth error", 400, |
| 60 | }, |
| 61 | { |
| 62 | "no expiration", nil, "Bearer noexp", |
| 63 | "token missing expiration", 401, |
| 64 | }, |
| 65 | { |
| 66 | "expired", nil, "Bearer expired", |
| 67 | "token expired", 401, |
| 68 | }, |
| 69 | { |
| 70 | "missing scope", &RequireBearerTokenOptions{Scopes: []string{"s1"}}, "Bearer valid", |
| 71 | "insufficient scope", 403, |
| 72 | }, |
| 73 | } { |
| 74 | t.Run(tt.name, func(t *testing.T) { |
| 75 | _, gotMsg, gotCode := verify(&http.Request{ |
| 76 | Header: http.Header{"Authorization": {tt.header}}, |
| 77 | }, verifier, tt.opts) |