From 4e3fe0ce0bc0b7fba81cf540f5e3411959a05267 Mon Sep 17 00:00:00 2001 From: Joel Schmid Date: Sat, 5 Jun 2021 19:06:45 +0200 Subject: [PATCH] fix jwt token authorization --- api/rest-api.go | 8 ++++++-- config/config.go | 2 +- 2 files changed, 7 insertions(+), 3 deletions(-) diff --git a/api/rest-api.go b/api/rest-api.go index dc15bb4..a2186fd 100644 --- a/api/rest-api.go +++ b/api/rest-api.go @@ -21,7 +21,8 @@ var bearerTokenRegexPattern = "^(?i:Bearer\\s+)([A-Za-z0-9-_=]+\\.[A-Za-z0-9-_=] var bearerTokenRegex *regexp.Regexp = regexp.MustCompile(bearerTokenRegexPattern) type customClaims struct { - Username string `json:"username"` + Username string `json:"username"` + Roles []string `json:"role"` jwt.StandardClaims } @@ -111,6 +112,8 @@ func (api *weatherRestApi) generateToken(w http.ResponseWriter, r *http.Request) StandardClaims: jwt.StandardClaims{ ExpiresAt: time.Now().Add(time.Minute * 30).Unix(), }, + Username: "Joel", + Roles: []string{"role 1", "role 2"}, } token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims) @@ -307,9 +310,10 @@ func (api *weatherRestApi) IsAuthorized(next http.Handler) http.Handler { jwtFromHeader := bearerTokenRegex.FindStringSubmatch(authorizationHeader[0])[1] + var claims customClaims token, err := jwt.ParseWithClaims( jwtFromHeader, - &customClaims{}, + &claims, func(token *jwt.Token) (interface{}, error) { return []byte(api.config.JwtTokenSecret), nil }, diff --git a/config/config.go b/config/config.go index 2f1a1d4..2eec73c 100644 --- a/config/config.go +++ b/config/config.go @@ -65,7 +65,7 @@ var RestConfiguration = RestConfig{ AccessControlAllowOriginHeader: getEnv("ACCESS_CONTROL_ALLOW_ORIGIN_HEADER", "*"), UseTokenAuthorization: getEnvBool("USE_TOKEN_AUTHORIZATION", false), AllowTokenGeneration: getEnvBool("ALLOW_TOKEN_GENERATION", false), - JwtTokenSecret: getEnv("JWT_TOKEN_SECRET", "jwt-token-secret"), + JwtTokenSecret: getEnv("JWT_TOKEN_SECRET", "my_token_string"), } var AllowUnregisteredSensors = getEnvBool("ALLOW_UNREGISTERED_SENSORS", false)