forked from infobloxopen/atlas-app-toolkit
-
Notifications
You must be signed in to change notification settings - Fork 0
/
grpc_test.go
76 lines (71 loc) · 1.99 KB
/
grpc_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
package integration
import (
"context"
"fmt"
"log"
"strings"
"testing"
jwt "github.com/dgrijalva/jwt-go"
"github.com/infobloxopen/atlas-app-toolkit/auth"
"google.golang.org/grpc/metadata"
)
func TestAppendTokenToOutgoingContext(t *testing.T) {
token, err := MakeTestJWT(
jwt.SigningMethodHS256, jwt.MapClaims{
"test-key": "test-value",
},
)
if err != nil {
t.Fatalf("unable to make test token: %v", err)
}
ctx := AppendTokenToOutgoingContext(context.Background(), "Bearer", token)
md, ok := metadata.FromOutgoingContext(ctx)
if !ok {
t.Fatal("unable to get metadata from context")
}
if md["authorization"][0] != fmt.Sprintf("Bearer %s", token) {
t.Fatalf("context does not contain token in metadata")
}
}
func ExampleAppendTokenToOutgoingContext_output() {
// make the jwt
authToken, err := jwt.NewWithClaims(
jwt.SigningMethodHS256, jwt.MapClaims{
"user": "user-test",
"roles": "admin",
},
).SignedString([]byte("some-secret"))
if err != nil {
log.Fatalf("unable to build token: %v", err)
}
// add the jwt to context
ctxBearer := AppendTokenToOutgoingContext(
context.Background(), "Bearer", authToken,
)
// check to make sure the token was added
md, ok := metadata.FromOutgoingContext(ctxBearer)
if !ok || len(md["authorization"]) < 1 {
log.Fatalf("unable to get token from context: %v", err)
}
fields := strings.Split(md["authorization"][0], " ")
if len(fields) < 2 {
log.Fatalf("unexpected authorization metadata: %v", fields)
}
fmt.Println(fields[0] == "Bearer")
fmt.Println(fields[1] == authToken)
// Output: true
// true
}
func TestStandardTestingContext(t *testing.T) {
ctx, err := StandardTestingContext()
if err != nil {
t.Fatalf("unexpected error when getting standard context: %v", err)
}
md, ok := metadata.FromOutgoingContext(ctx)
if !ok {
t.Fatal("unable to get metadata from context")
}
if md["authorization"][0] != fmt.Sprintf("%s %s", auth.DefaultTokenType, standardToken) {
t.Fatalf("context does not contain token in metadata")
}
}