[[toc]]
Authentication is an indispensable feature in Web Applications, the facades.Auth() module of Goravel provides support for JWT.
You can configure defaults guard and multiple guards in the config/auth.go file to switch different user identities in the application.
You can configure the parameters of JWT in the config/jwt.go file, such as secret, ttl, refresh_ttl.
go run . artisan jwt:secretYou can generate a token by Model, there is no extra configuration if the model uses orm.Model, otherwise, you need to configure Tag on the model primary key field, for example:
type User struct {
ID uint `gorm:"primaryKey"`
Name string
}
var user models.User
user.ID = 1
token, err := facades.Auth().Login(ctx, &user)token, err := facades.Auth().LoginUsingID(ctx, 1)payload, err := facades.Auth().Parse(ctx, token)Through payload you can get:
Guard: Current Guard;Key: User flag;ExpireAt: Expire time;IssuedAt: Issued time;
If
errisn't nil other thanErrorTokenExpired, the payload should be nil.
You can judge whether the Token is expired by err:
"errors"
"github.com/goravel/framework/auth"
errors.Is(err, auth.ErrorTokenExpired)The token can be parsed normally with or without the Bearer prefix.
You need to generate a Token by Parse before getting a user, the process can be handled in HTTP middleware.
var user models.User
err := facades.Auth().User(ctx, &user) // Must pointYou need to generate a Token by Parse before refreshing the user.
token, err := facades.Auth().Refresh(ctx)err := facades.Auth().Logout(ctx)token, err := facades.Auth().Guard("admin").LoginUsingID(ctx, 1)
err := facades.Auth().Guard("admin").Parse(ctx, token)
token, err := facades.Auth().Guard("admin").User(ctx, &user)When the default guard is not used, the
Guardmethod must be called before calling the above methods.