中文文档 | English
Sa-Token-Go provides annotation-like decorators for Gin framework, similar to Java's @SaCheckLogin, @SaCheckRole annotations.
@CheckLogin- Check if user is logged in@CheckRole- Check if user has specified role@CheckPermission- Check if user has specified permission@CheckDisable- Check if account is disabled@Ignore- Ignore authentication
import sagin "github.com/sa-tokens/sa-token-go/integrations/gin"
r := gin.Default()
// Requires login
r.GET("/user/info", sagin.CheckLogin(), func(c *gin.Context) {
c.JSON(200, gin.H{"message": "User info"})
})// Requires admin role
r.GET("/admin", sagin.CheckRole("admin"), func(c *gin.Context) {
c.JSON(200, gin.H{"message": "Admin page"})
})
// Requires any of the roles
r.GET("/dashboard", sagin.CheckRole("admin", "manager"), func(c *gin.Context) {
c.JSON(200, gin.H{"message": "Dashboard"})
})// Requires permission
r.GET("/users", sagin.CheckPermission("user:read"), func(c *gin.Context) {
c.JSON(200, gin.H{"message": "User list"})
})
// Requires any of the permissions
r.DELETE("/user/:id", sagin.CheckPermission("user:delete", "admin:*"), func(c *gin.Context) {
c.JSON(200, gin.H{"message": "User deleted"})
})// Check if account is disabled
r.GET("/profile", sagin.CheckDisable(), func(c *gin.Context) {
c.JSON(200, gin.H{"message": "Profile"})
})// Ignore authentication
r.GET("/public", sagin.Ignore(), func(c *gin.Context) {
c.JSON(200, gin.H{"message": "Public page"})
})package main
import (
"github.com/gin-gonic/gin"
"github.com/sa-tokens/sa-token-go/core"
"github.com/sa-tokens/sa-token-go/stputil"
"github.com/sa-tokens/sa-token-go/storage/memory"
sagin "github.com/sa-tokens/sa-token-go/integrations/gin"
)
func main() {
// Initialize
stputil.SetManager(
core.NewBuilder().
Storage(memory.NewStorage()).
Build(),
)
r := gin.Default()
// Public routes (no authentication)
r.GET("/", sagin.Ignore(), indexHandler)
r.POST("/login", loginHandler)
// Login required
r.GET("/user/info", sagin.CheckLogin(), userInfoHandler)
// Role required
r.GET("/admin", sagin.CheckRole("admin"), adminHandler)
r.GET("/manager", sagin.CheckRole("admin", "manager"), managerHandler)
// Permission required
r.GET("/users", sagin.CheckPermission("user:read"), listUsersHandler)
r.POST("/users", sagin.CheckPermission("user:create"), createUserHandler)
r.DELETE("/users/:id", sagin.CheckPermission("user:delete"), deleteUserHandler)
// Check disable
r.GET("/profile", sagin.CheckDisable(), profileHandler)
r.Run(":8080")
}Annotations are currently only supported for Gin framework. For other frameworks (Echo, Fiber, Chi), use middleware instead:
// Echo example
import saecho "github.com/sa-tokens/sa-token-go/integrations/echo"
e.GET("/user/info", userInfoHandler, saecho.NewPlugin(manager).AuthMiddleware())