github.com/hxx258456/ccgo@v0.0.5-0.20230213014102-48b35f46f66f/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 "testing" 8 9 "github.com/hxx258456/ccgo/go-grpc-middleware/util/metautils" 10 "github.com/hxx258456/ccgo/grpc" 11 "github.com/hxx258456/ccgo/grpc/codes" 12 "github.com/hxx258456/ccgo/grpc/metadata" 13 "github.com/hxx258456/ccgo/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 assert.Equal(t, run.errCode, grpc.Code(err), run.msg) 68 } else { 69 assert.NoError(t, err, run.msg) 70 } 71 assert.Equal(t, run.value, out, run.msg) 72 } 73 74 }