forked from labstack/echox
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
docs(jwt): add a user-defined KeyFunc
Documentation for exposing KeyFunc: labstack/echo#1756
- Loading branch information
1 parent
3dafe29
commit bc46956
Showing
3 changed files
with
109 additions
and
2 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,66 @@ | ||
package main | ||
|
||
import ( | ||
"context" | ||
"errors" | ||
"fmt" | ||
"net/http" | ||
|
||
jwt "github.com/dgrijalva/jwt-go" | ||
echo "github.com/labstack/echo/v4" | ||
middleware "github.com/labstack/echo/v4/middleware" | ||
jwk "github.com/lestrrat-go/jwx/jwk" | ||
) | ||
|
||
func getKey(token *jwt.Token) (interface{}, error) { | ||
|
||
// Note: this downloads the keyset every time. | ||
keySet, err := jwk.Fetch(context.Background(), "https://www.googleapis.com/oauth2/v3/certs") | ||
if err != nil { | ||
return nil, err | ||
} | ||
|
||
keyID, ok := token.Header["kid"].(string) | ||
if !ok { | ||
return nil, errors.New("expecting JWT header to have a key ID in the kid field") | ||
} | ||
|
||
key, found := keySet.LookupKeyID(keyID) | ||
|
||
if !found { | ||
return nil, fmt.Errorf("unable to find key %q", keyID) | ||
} | ||
|
||
var pubkey interface{} | ||
if err := key.Raw(&pubkey); err != nil { | ||
return nil, fmt.Errorf("Unable to get the public key. Error: %s", err.Error()) | ||
} | ||
|
||
return pubkey, nil | ||
} | ||
|
||
func restricted(c echo.Context) error { | ||
user := c.Get("user").(*jwt.Token) | ||
claims := user.Claims.(jwt.MapClaims) | ||
name := claims["name"].(string) | ||
return c.String(http.StatusOK, "Welcome "+name+"!") | ||
} | ||
|
||
func main() { | ||
e := echo.New() | ||
|
||
// Middleware | ||
e.Use(middleware.Logger()) | ||
e.Use(middleware.Recover()) | ||
|
||
// Restricted group | ||
r := e.Group("/restricted") | ||
|
||
config := middleware.JWTConfig{ | ||
KeyFunc: getKey, | ||
} | ||
r.Use(middleware.JWTWithConfig(config)) | ||
r.GET("", restricted) | ||
|
||
e.Logger.Fatal(e.Start(":1323")) | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters