-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathexample_test.go
213 lines (171 loc) · 7.07 KB
/
example_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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
// SPDX-FileCopyrightText: 2023-2025 Greenbone AG
//
// SPDX-License-Identifier: AGPL-3.0-or-later
package auth_test
import (
"bytes"
"context"
"crypto/rand"
"crypto/rsa"
"encoding/base64"
"encoding/binary"
"fmt"
"log"
"math/big"
"net/http"
"net/http/httptest"
"github.com/Nerzal/gocloak/v13"
"github.com/gin-gonic/gin"
"github.com/golang-jwt/jwt/v5"
"github.com/jarcoal/httpmock"
"github.com/samber/lo"
"github.com/greenbone/keycloak-client-golang/auth"
)
func setupToken() (token string, clean func()) {
privateKey := newPrivateKey()
validToken := getToken(jwt.MapClaims{
"iss": "http://localhost:28080/auth/realms/user-management",
"sub": "1927ed8a-3f1f-4846-8433-db290ea5ff90",
"email": "[email protected]",
"preferred_username": "initial",
"roles": []string{"offline_access", "uma_authorization", "user", "default-roles-user-management"},
"groups": []string{"user-management-initial"},
"allowed-origins": []string{"http://localhost:3000"},
}, privateKey)
cleanUp := mockKeycloak(privateKey.PublicKey)
return validToken, cleanUp
}
func ExampleNewKeycloakAuthorizer() {
validToken, clean := setupToken()
defer clean()
var (
realmId = "user-management" // keycloak realm name
authUrl = "http://keycloak:8080/auth" // keycloak server internal url
origin = "http://localhost:3000" // request origin, note: it is optional, if request doesn't have Origin header it is not validated
)
realmInfo := auth.KeycloakRealmInfo{
RealmId: realmId,
AuthServerInternalUrl: authUrl,
}
authorizer, err := auth.NewKeycloakAuthorizer(realmInfo, authorizerKeycloakMock) // NOTE: authorizerKeycloakMock only used for mocking keycloak cert response in this example, do not use outside tests!
if err != nil {
log.Fatal(fmt.Errorf("error creating keycloak token authorizer: %w", err))
return
}
userContext1, err := authorizer.ParseJWT(context.TODO(), validToken) // pass jwt token here
if err != nil {
log.Fatal(fmt.Errorf("error parsing token: %w", err))
return
}
fmt.Printf("%#v\n", userContext1)
userContext2, err := authorizer.ParseAuthorizationHeader(context.TODO(), "bearer "+validToken) // pass authorization header here
if err != nil {
log.Fatal(fmt.Errorf("error parsing token: %w", err))
return
}
fmt.Printf("%#v\n", userContext2)
userContext3, err := authorizer.ParseRequest(context.TODO(), "bearer "+validToken, origin) // pass authorization and origin headers here
if err != nil {
log.Fatal(fmt.Errorf("error parsing token: %w", err))
return
}
fmt.Printf("%#v\n", userContext3)
// Output:
// auth.UserContext{Realm:"user-management", UserID:"1927ed8a-3f1f-4846-8433-db290ea5ff90", UserName:"initial", EmailAddress:"[email protected]", Roles:[]string{"offline_access", "uma_authorization", "user", "default-roles-user-management"}, Groups:[]string{"user-management-initial"}, AllowedOrigins:[]string{"http://localhost:3000"}}
// auth.UserContext{Realm:"user-management", UserID:"1927ed8a-3f1f-4846-8433-db290ea5ff90", UserName:"initial", EmailAddress:"[email protected]", Roles:[]string{"offline_access", "uma_authorization", "user", "default-roles-user-management"}, Groups:[]string{"user-management-initial"}, AllowedOrigins:[]string{"http://localhost:3000"}}
// auth.UserContext{Realm:"user-management", UserID:"1927ed8a-3f1f-4846-8433-db290ea5ff90", UserName:"initial", EmailAddress:"[email protected]", Roles:[]string{"offline_access", "uma_authorization", "user", "default-roles-user-management"}, Groups:[]string{"user-management-initial"}, AllowedOrigins:[]string{"http://localhost:3000"}}
}
func ExampleNewGinAuthMiddleware() {
validToken, clean := setupToken()
defer clean()
var (
realmId = "user-management" // keycloak realm name
authUrl = "http://keycloak:8080/auth" // keycloak server internal url
origin = "http://localhost:3000" // request origin, note: it is optional, if request doesn't have Origin header it is not validated
)
realmInfo := auth.KeycloakRealmInfo{
RealmId: realmId,
AuthServerInternalUrl: authUrl,
}
authorizer, err := auth.NewKeycloakAuthorizer(realmInfo, authorizerKeycloakMock) // NOTE: authorizerKeycloakMock only used for mocking keycloak cert response in this example, do not use outside tests!
if err != nil {
log.Fatal(fmt.Errorf("error creating keycloak token authorizer: %w", err))
return
}
authMiddleware, err := auth.NewGinAuthMiddleware(authorizer.ParseRequest)
if err != nil {
log.Fatal(fmt.Errorf("error creating keycloak auth middleware: %w", err))
return
}
gin.SetMode(gin.TestMode)
router := gin.New()
router.Use(authMiddleware) // wire up middleware
router.GET("/test", func(c *gin.Context) {
userContext, err := auth.GetUserContext(c)
if err != nil {
_ = c.AbortWithError(http.StatusInternalServerError, err)
return
}
c.String(http.StatusOK, fmt.Sprintf("%#v", userContext))
})
w := httptest.NewRecorder()
req, _ := http.NewRequest(http.MethodGet, "/test", nil)
req.Header.Add("Authorization", fmt.Sprintf("bearer %s", validToken))
req.Header.Add("Origin", origin)
router.ServeHTTP(w, req)
fmt.Print(w.Body.String())
// Output:
// auth.UserContext{Realm:"user-management", UserID:"1927ed8a-3f1f-4846-8433-db290ea5ff90", UserName:"initial", EmailAddress:"[email protected]", Roles:[]string{"offline_access", "uma_authorization", "user", "default-roles-user-management"}, Groups:[]string{"user-management-initial"}, AllowedOrigins:[]string{"http://localhost:3000"}}
}
const (
publicKeyID = "OMTg5TWEm1TZeqeb2zuJJFX1ZxOwDs_IfPIgJ0uIFU0"
publicKeyALG = "RS256"
)
func newPrivateKey() *rsa.PrivateKey {
privateKey, err := rsa.GenerateKey(rand.Reader, 2048)
if err != nil {
panic(err)
}
return privateKey
}
func getToken(claims jwt.MapClaims, privateKey *rsa.PrivateKey) string {
token := jwt.NewWithClaims(jwt.GetSigningMethod(publicKeyALG), claims)
token.Header["kid"] = publicKeyID
tokenString, err := token.SignedString(privateKey)
if err != nil {
panic(err)
}
return tokenString
}
func getBase64E(e int) string {
buf := new(bytes.Buffer)
_ = binary.Write(buf, binary.BigEndian, int32(e)) //nolint:gosec
res := base64.RawURLEncoding.EncodeToString(buf.Bytes())
return res
}
func getBase64N(n *big.Int) string {
res := base64.RawURLEncoding.EncodeToString(n.Bytes())
return res
}
var authorizerKeycloakMock func(*auth.KeycloakAuthorizer)
func mockKeycloak(publicKey rsa.PublicKey) (clean func()) {
certResponse := &gocloak.CertResponse{
Keys: &[]gocloak.CertResponseKey{
{
Kid: lo.ToPtr(publicKeyID),
Alg: lo.ToPtr(publicKeyALG),
N: lo.ToPtr(getBase64N(publicKey.N)),
E: lo.ToPtr(getBase64E(publicKey.E)),
},
},
}
certResponder, err := httpmock.NewJsonResponder(200, certResponse)
if err != nil {
panic(err)
}
httpmock.RegisterResponder("GET", "http://keycloak:8080/auth/realms/user-management/protocol/openid-connect/certs", certResponder)
authorizerKeycloakMock = auth.ConfigureGoCloak(func(c *gocloak.GoCloak) {
httpmock.ActivateNonDefault(c.RestyClient().GetClient())
})
return httpmock.DeactivateAndReset
}