1
0
mirror of https://github.com/kataras/iris.git synced 2025-12-27 14:57:05 +00:00

add context partial user helper and accept a generic interface on SetUser - the same method now returns an error if the given value does not complete at least one method of the User interface

This commit is contained in:
Gerasimos (Makis) Maropoulos
2020-10-31 15:47:28 +02:00
parent 8eea0296a7
commit 3d59d19de6
8 changed files with 356 additions and 191 deletions

View File

@@ -26,14 +26,14 @@ func main() {
signer := jwt.NewSigner(jwt.HS256, sigKey, 10*time.Minute)
// Enable payload encryption with:
// signer.WithGCM(encKey, nil)
// signer.WithEncryption(encKey, nil)
app.Get("/", generateToken(signer))
verifier := jwt.NewVerifier(jwt.HS256, sigKey)
// Enable server-side token block feature (even before its expiration time):
verifier.WithDefaultBlocklist()
// Enable payload decryption with:
// verifier.WithGCM(encKey, nil)
// verifier.WithDecryption(encKey, nil)
verifyMiddleware := verifier.Verify(func() interface{} {
return new(fooClaims)
})

View File

@@ -28,6 +28,21 @@ type UserClaims struct {
Username string `json:"username"`
}
// GetID implements the partial context user's ID interface.
// Note that if claims were a map then the claims value converted to UserClaims
// and no need to implement any method.
//
// This is useful when multiple auth methods are used (e.g. basic auth, jwt)
// but they all share a couple of methods.
func (u *UserClaims) GetID() string {
return u.ID
}
// GetUsername implements the partial context user's Username interface.
func (u *UserClaims) GetUsername() string {
return u.Username
}
// Validate completes the middleware's custom ClaimsValidator.
// It will not accept a token which its claims missing the username field
// (useful to not accept refresh tokens generated by the same algorithm).
@@ -58,8 +73,15 @@ func main() {
protectedAPI.Use(verifyMiddleware)
protectedAPI.Get("/", func(ctx iris.Context) {
claims := jwt.Get(ctx).(*UserClaims)
ctx.Writef("Username: %s\n", claims.Username)
// Access the claims through: jwt.Get:
// claims := jwt.Get(ctx).(*UserClaims)
// ctx.Writef("Username: %s\n", claims.Username)
//
// OR through context's user (if at least one method was implement by our UserClaims):
user := ctx.User()
id, _ := user.GetID()
username, _ := user.GetUsername()
ctx.Writef("ID: %s\nUsername: %s\n", id, username)
})
}