31
internal/auth/service.go
Normal file
31
internal/auth/service.go
Normal file
@@ -0,0 +1,31 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"crypto/subtle"
|
||||
"log"
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"git.apinb.com/ops/files/internal/config"
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
func ServiceAuth() gin.HandlerFunc {
|
||||
return func(ctx *gin.Context) {
|
||||
serviceName := strings.TrimSpace(ctx.GetHeader("Service-Name"))
|
||||
secretKey := strings.TrimSpace(ctx.GetHeader("Secret-Key"))
|
||||
serviceSecret, exists := config.Spec.ServiceClients[serviceName]
|
||||
if serviceName == "" || secretKey == "" || !exists || strings.TrimSpace(serviceSecret) == "" || subtle.ConstantTimeCompare([]byte(serviceSecret), []byte(secretKey)) != 1 {
|
||||
log.Printf("服务鉴权失败: service=%q", serviceName)
|
||||
ctx.JSON(http.StatusUnauthorized, gin.H{"error": "Unauthorized"})
|
||||
ctx.Abort()
|
||||
return
|
||||
}
|
||||
|
||||
withActor(ctx, Actor{
|
||||
Type: ActorTypeService,
|
||||
Identity: serviceName,
|
||||
})
|
||||
ctx.Next()
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user