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

optional_auth.go 1.0KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. package auth
  2. import (
  3. "net/http"
  4. "fmt"
  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) > 7 {
  19. token, err := jwt.Parse(tokenFromHeader[7:], func(token *jwt.Token) (interface{}, error) {
  20. if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
  21. return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"])
  22. }
  23. return []byte(authKey), nil
  24. })
  25. if err != nil || !token.Valid {
  26. return
  27. }
  28. if mapClaims, ok := token.Claims.(jwt.MapClaims); ok {
  29. if uid, ok := mapClaims[CtxRequestHeaderUserId].(float64); ok {
  30. ctx.Set(CtxRequestHeaderUserId, int64(uid))
  31. }
  32. }
  33. }
  34. }
  35. }