Authentication

Introdution

Authentication is an indispensable feature in Web Applications, the facades.Auth module of Goravel provides support for JWT.

Configration

You can configure default guard and multiple guards in the config/auth.go file to switch different user identities in the application.

You can configure parameters of JWT in the config/jwt.go file, such as secret, ttl, refresh_ttl.

Generate Token Using User

You can generate Token by Model, there is no extra configuration if the model use orm.Model, otherwise, you need to configure Tag on the model permary key filed, 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)

Generate Token Using ID

token, err := facades.Auth.LoginUsingID(ctx, 1)

Parse Token

err := facades.Auth.Parse(ctx, token)

You can judge whether the Token is expired by err:

"errors"
"github.com/goravel/framework/auth"

errors.Is(err, auth.ErrorTokenExpired)

Token can be parsed normally with or without Bearer prefix.

Get User

You need to generate Token by Parse before getting user, the process can be handled in HTTP middleware.

var user models.User
err := facades.Auth.User(ctx, &user)// Must point

Refrech Token

You need to generate Token by Parse before refreshing user.

token, err := facades.Auth.Refresh(ctx)

Logout

err := facades.Auth.Logout(ctx)

Multiple Guards

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 don't use default guard, the Guard method needs to be called beforehand when calling the above methods.

Last Updated:
Contributors: Bowens