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

optional_auth.go 1.1KB

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