-
Notifications
You must be signed in to change notification settings - Fork 0
/
jwks.go
77 lines (63 loc) · 1.87 KB
/
jwks.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
package auth
import (
"context"
"fmt"
"log"
"github.com/MicahParks/keyfunc"
"github.com/gin-gonic/gin"
"github.com/golang-jwt/jwt/v4"
)
// func NewRouter() *gin.Engine {
// r := gin.New()
// r.Use(gin.Logger())
// r.Use(gin.CustomRecovery(func(c *gin.Context, err any) {
// c.JSON(http.StatusBadRequest, err.(error).Error())
// c.Abort()
// }))
// r.POST("upload", handlers.StoreFile)
// r.GET("files/:filename", handlers.GetFile)
// r.DELETE("files/:filename", handlers.DeleteFile)
// return r
// }
func getKeyFunc(context context.Context, jwksURL string) *keyfunc.JWKS {
options := keyfunc.Options{
Ctx: context,
RefreshErrorHandler: func(err error) {
log.Printf("There was an error with the jwt.Keyfunc\nError: %s", err.Error())
},
RefreshInterval: 0,
}
// Create the JWKS from the resource at the given URL.
jwks, err := keyfunc.Get(jwksURL, options)
if err != nil {
log.Fatalf("Failed to create JWKS from resource at the given URL.\nError: %s", err.Error())
}
return jwks
}
var jwksURL = "https://evilmerchant.b2clogin.com/2a80bde3-5842-4619-bc0c-bf0c754b32d0/b2c_1a_federate/discovery/v2.0/keys"
var EvilmerchantClaims = "EVMClaims"
func EvilmerchantAuth(authHeader *string) gin.HandlerFunc {
jwks := getKeyFunc(context.Background(), jwksURL)
return func(ctx *gin.Context) {
_usedHeader := "X-Evilmerchant-Authorization"
if authHeader != nil {
_usedHeader = *authHeader
}
header := ctx.GetHeader(_usedHeader)
if header == "" {
ctx.AbortWithError(401, fmt.Errorf("no authorization token found"))
return
}
jwtB64 := header[7:]
token, err := jwt.Parse(jwtB64, jwks.Keyfunc)
if err != nil {
ctx.AbortWithError(401, fmt.Errorf("failed to parse the JWT.\nError: %s", err.Error()))
return
}
if !token.Valid {
ctx.AbortWithError(401, fmt.Errorf("invalid token"))
return
}
ctx.Set(EvilmerchantClaims, token.Claims)
}
}