Skip to content

Commit 1853bd5

Browse files
committed
Fix checkScope logic
1 parent 95f924a commit 1853bd5

1 file changed

Lines changed: 17 additions & 27 deletions

File tree

01-Authorization-RS256/main.go

Lines changed: 17 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,6 @@ type JSONWebKeys struct {
3535
}
3636

3737
func main() {
38-
3938
err := godotenv.Load()
4039
if err != nil {
4140
log.Print("Error loading .env file")
@@ -97,16 +96,15 @@ func main() {
9796
r.Handle("/api/private-scoped", negroni.New(
9897
negroni.HandlerFunc(jwtMiddleware.HandlerWithNext),
9998
negroni.Wrap(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
100-
authHeaderParts := strings.Split(r.Header.Get("Authorization"), " ")
101-
token := authHeaderParts[1]
99+
token := r.Context().Value("user").(*jwt.Token)
102100

103101
hasScope := checkScope("read:messages", token)
104-
105102
if !hasScope {
106103
message := "Insufficient scope."
107104
responseJSON(message, w, http.StatusForbidden)
108105
return
109106
}
107+
110108
message := "Hello from a private endpoint! You need to be authenticated to see this."
111109
responseJSON(message, w, http.StatusOK)
112110
}))))
@@ -117,34 +115,26 @@ func main() {
117115
http.ListenAndServe("0.0.0.0:3010", handler)
118116
}
119117

120-
type CustomClaims struct {
121-
Scope string `json:"scope"`
122-
jwt.StandardClaims
123-
}
124-
125-
func checkScope(scope string, tokenString string) bool {
126-
token, _ := jwt.ParseWithClaims(tokenString, &CustomClaims{}, func(token *jwt.Token) (interface{}, error) {
127-
cert, err := getPemCert(token)
128-
if err != nil {
129-
return nil, err
130-
}
131-
result, _ := jwt.ParseRSAPublicKeyFromPEM([]byte(cert))
132-
return result, nil
133-
})
118+
func checkScope(scope string, token *jwt.Token) bool {
119+
claims, ok := token.Claims.(jwt.MapClaims)
120+
if !ok {
121+
return false
122+
}
134123

135-
claims, ok := token.Claims.(*CustomClaims)
124+
const scopeKey = "scope"
125+
tokenScope, ok := claims[scopeKey].(string)
126+
if !ok {
127+
return false
128+
}
136129

137-
hasScope := false
138-
if ok && token.Valid {
139-
result := strings.Split(claims.Scope, " ")
140-
for i := range result {
141-
if result[i] == scope {
142-
hasScope = true
143-
}
130+
result := strings.Split(tokenScope, " ")
131+
for i := range result {
132+
if result[i] == scope {
133+
return true
144134
}
145135
}
146136

147-
return hasScope
137+
return false
148138
}
149139

150140
func getPemCert(token *jwt.Token) (string, error) {

0 commit comments

Comments
 (0)