Sessions, user details & roles
Reading the current user in Fiber
After Protect or Guard:
app.Get("/api/me", fiberauth.Protect(auth), func(c fiber.Ctx) error {
s := fiberauth.SessionFrom(c)
if s == nil || s.User == nil {
return fiber.NewError(fiber.StatusUnauthorized, "unauthorized")
}
return c.JSON(fiber.Map{
"user": fiber.Map{
"id": s.User.ID,
"email": s.User.Email,
"name": s.User.Name,
"image": s.User.Image,
},
"roles": s.Roles(),
"sessionId": s.StringClaim("sessionId"), // bearer flow
})
})
Session shape
fiberauth.SessionFrom returns *goauth.Session:
| Field / method | Description |
|---|---|
s.User | *goauth.User — id, email, name, image |
s.Roles() | Roles from JWT roles array or role string |
s.HasRole("admin") | Case-sensitive role check |
s.HasAnyRole("a", "b") | Any role matches |
s.Claim("plan") | Arbitrary JWT claim |
s.StringClaim("org") | Claim as string |
Adding roles in JWT callback
Roles must be set when the token is created (credentials, OAuth, OTP sign-in):
auth, _ := goauth.New(goauth.Config{
Secret: []string{secret},
Providers: []goauth.Provider{ /* ... */ },
Callbacks: goauth.Callbacks{
JWT: func(ctx context.Context, p goauth.JWTCallbackParams) (goauth.JWT, error) {
if p.User != nil {
roles, _ := db.RolesForUser(ctx, p.User.ID)
p.Token["roles"] = roles
// optional single role for legacy checks:
if len(roles) > 0 {
p.Token["role"] = roles[0]
}
p.Token["plan"] = lookupPlan(p.User.ID)
}
return p.Token, nil
},
},
})
Then in Fiber:
app.Get("/api/billing",
fiberauth.Guard(auth,
fiberauth.HasRole("billing", "admin"),
fiberauth.HasClaim("plan", "pro"),
),
billingHandler,
)
Database session strategy
With Adapter + StrategyDatabase, s.User is loaded from the adapter on each request. Roles still typically live in JWT claims if you use hybrid token+cookie, or add roles in Session callback:
Session: func(ctx context.Context, p goauth.SessionCallbackParams) (*goauth.Session, error) {
if p.Session != nil && p.User != nil {
// enrich before JSON response — not stored in JWT
}
return p.Session, nil
},
Note: Guard/HasRole read JWT claims on the session object — ensure roles are on the token or copied into claims goauth exposes.
GET /auth/session from Fiber
Your SPA can also call goauth directly:
const res = await fetch("/auth/session", { credentials: "include" });
const session = await res.json();
Or with bearer:
const res = await fetch("/auth/session", {
headers: { Authorization: `Bearer ${accessToken}` },
});
Example from fiberauth repo
The official example maps in-memory users to JWT roles:
JWT: func(_ context.Context, p goauth.JWTCallbackParams) (goauth.JWT, error) {
acc := findByID(p.User.ID)
if acc == nil {
acc = findByEmail(p.User.Email)
}
if acc != nil {
p.Token["roles"] = acc.Roles
}
return p.Token, nil
},
app.Get("/api/me", fiberauth.Protect(auth), func(c fiber.Ctx) error {
s := fiberauth.SessionFrom(c)
return c.JSON(fiber.Map{"user": s.User, "roles": s.Roles()})
})