Add auth protection sample and standardize json.

This commit is contained in:
2025-05-14 09:26:48 +08:00
parent bcb820ea9b
commit 418a30f062
6 changed files with 71 additions and 20 deletions
+24
View File
@@ -0,0 +1,24 @@
package middleware
import (
"net/http"
"starter/backend/internal/handlers"
"github.com/gin-contrib/sessions"
"github.com/gin-gonic/gin"
"github.com/logto-io/go/client"
)
// AuthRequired 是 Logto 认证中间件,未认证用户返回 401
func AuthRequired() gin.HandlerFunc {
return func(c *gin.Context) {
session := sessions.Default(c)
logtoClient := client.NewLogtoClient(handlers.GetLogtoConfig(), &handlers.SessionStorage{Session: session})
if !logtoClient.IsAuthenticated() {
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "unauthorized"})
return
}
c.Next()
}
}