gitee.com/ks-custle/core-gm@v0.0.0-20230922171213-b83bdd97b62c/go-grpc-middleware/auth/metadata_test.go (about) 1 // Copyright 2016 Michal Witkowski. All Rights Reserved. 2 // See LICENSE for licensing terms. 3 4 package grpc_auth 5 6 import ( 7 "gitee.com/ks-custle/core-gm/grpc/status" 8 "testing" 9 10 "gitee.com/ks-custle/core-gm/go-grpc-middleware/util/metautils" 11 "gitee.com/ks-custle/core-gm/grpc/codes" 12 "gitee.com/ks-custle/core-gm/grpc/metadata" 13 "gitee.com/ks-custle/core-gm/net/context" 14 "github.com/stretchr/testify/assert" 15 ) 16 17 func TestAuthFromMD(t *testing.T) { 18 for _, run := range []struct { 19 md metadata.MD 20 value string 21 errCode codes.Code 22 msg string 23 }{ 24 { 25 md: metadata.Pairs("authorization", "bearer some_token"), 26 value: "some_token", 27 msg: "must extract simple bearer tokens without case checking", 28 }, 29 { 30 md: metadata.Pairs("authorization", "Bearer some_token"), 31 value: "some_token", 32 msg: "must extract simple bearer tokens with case checking", 33 }, 34 { 35 md: metadata.Pairs("authorization", "Bearer some multi string bearer"), 36 value: "some multi string bearer", 37 msg: "must handle string based bearers", 38 }, 39 { 40 md: metadata.Pairs("authorization", "Basic login:passwd"), 41 value: "", 42 errCode: codes.Unauthenticated, 43 msg: "must check authentication type", 44 }, 45 { 46 md: metadata.Pairs("authorization", "Basic login:passwd", "authorization", "bearer some_token"), 47 value: "", 48 errCode: codes.Unauthenticated, 49 msg: "must not allow multiple authentication methods", 50 }, 51 { 52 md: metadata.Pairs("authorization", ""), 53 value: "", 54 errCode: codes.Unauthenticated, 55 msg: "authorization string must not be empty", 56 }, 57 { 58 md: metadata.Pairs("authorization", "Bearer"), 59 value: "", 60 errCode: codes.Unauthenticated, 61 msg: "bearer token must not be empty", 62 }, 63 } { 64 ctx := metautils.NiceMD(run.md).ToIncoming(context.TODO()) 65 out, err := AuthFromMD(ctx, "bearer") 66 if run.errCode != codes.OK { 67 // `grpc.Code` is deprecated. Use `status.Code` instead. 68 //assert.Equal(t, run.errCode, grpc.Code(err), run.msg) 69 assert.Equal(t, run.errCode, status.Code(err), run.msg) 70 } else { 71 assert.NoError(t, err, run.msg) 72 } 73 assert.Equal(t, run.value, out, run.msg) 74 } 75 76 }