keystone_auth.go 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. // Copyright 2019 Yunion
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package middleware
  15. import (
  16. "fmt"
  17. "net/http"
  18. "strings"
  19. gin "github.com/gin-gonic/gin"
  20. "yunion.io/x/onecloud/pkg/mcclient/auth"
  21. )
  22. const (
  23. XAuthTokenKey = "X-Auth-Token"
  24. )
  25. func KeystoneTokenVerifyMiddleware() gin.HandlerFunc {
  26. return func(c *gin.Context) {
  27. // hack
  28. escapeAuth := []string{
  29. "ping",
  30. "version",
  31. "metrics",
  32. "k8s/predicates",
  33. "k8s/priorities",
  34. "debug/pprof",
  35. "debug/pprof/cmdline",
  36. "debug/pprof/profile",
  37. "debug/pprof/symbol",
  38. "debug/pprof/trace",
  39. }
  40. for _, s := range escapeAuth {
  41. if strings.HasSuffix(c.Request.URL.Path, s) {
  42. c.Next()
  43. return
  44. }
  45. }
  46. token := c.Request.Header.Get(XAuthTokenKey)
  47. if len(token) == 0 {
  48. c.AbortWithError(http.StatusBadRequest, fmt.Errorf("Not found %s in http header.", XAuthTokenKey))
  49. return
  50. }
  51. _, err := auth.Verify(c, token)
  52. if err != nil {
  53. c.AbortWithError(http.StatusUnauthorized, err)
  54. return
  55. }
  56. c.Next()
  57. }
  58. }