另客网go项目公用的代码库

optional_auth.go 1.1KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. package auth
  2. import (
  3. "fmt"
  4. "net/http"
  5. "github.com/dgrijalva/jwt-go"
  6. "github.com/gin-gonic/gin"
  7. )
  8. func OptionalAuth(authKey string) gin.HandlerFunc {
  9. return func(ctx *gin.Context) {
  10. var tokenFromCookie, tokenFromHeader string
  11. tokenFromCookie, err := ctx.Cookie(ctxRequestCookieAuthorization)
  12. if err == http.ErrNoCookie {
  13. tokenFromHeader = ctx.Request.Header.Get(ctxRequestHeaderAuthorization)
  14. }
  15. if tokenFromHeader == "" {
  16. tokenFromHeader = "Bearer " + tokenFromCookie
  17. }
  18. if len(tokenFromHeader) < 8 {
  19. ctx.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"msg": "auth failed"})
  20. return
  21. }
  22. token, err := jwt.Parse(tokenFromHeader[7:], func(token *jwt.Token) (interface{}, error) {
  23. if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
  24. return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"])
  25. }
  26. return []byte(authKey), nil
  27. })
  28. if err != nil || !token.Valid {
  29. return
  30. }
  31. if mapClaims, ok := token.Claims.(jwt.MapClaims); ok {
  32. if uid, ok := mapClaims[CtxRequestHeaderUserId].(float64); ok {
  33. ctx.Set(CtxRequestHeaderUserId, int64(uid))
  34. }
  35. }
  36. }
  37. }