go-zero icon indicating copy to clipboard operation
go-zero copied to clipboard

Jwt expire lead to the Cors error. All route invalid

Open ctra-wang opened this issue 1 year ago • 0 comments

Describe the bug when we used function "rest.MustNewServer()" with jwt and cors the sort jwt before cors validate lead to all route invalid.

To Reproduce 1、Route options is sucess (204) 2、Route other request is all CORS error 3、the jwt before cors validate

  1. The (my main) code is
    func main() {
	 flag.Parse()

	 var c config.Config
	 conf.MustLoad(*configFile, &c, conf.UseEnv())

	ctx := svc.NewServiceContext(c)
	server := rest.MustNewServer(c.RestConf, rest.WithUnauthorizedCallback(func(w http.ResponseWriter, r *http.Request, err error) {
		httpx.Error(w, xerr.NewEnsumError(xerr.LOGIN_ERROR))
	}), rest.WithCors("*"))
	defer server.Stop()

	handler.RegisterHandlers(server, ctx)
	httpx.SetErrorHandler(func(err error) (int, interface{}) {
		switch e := err.(type) {
		case *xerr.CodeError:
			return http.StatusOK, e.Data()
		default:
			logx.WithContext(context.Background()).Errorf(e.Error())
			return http.StatusOK, xerr.NewEnsumError(xerr.BAD_REQUEST_ERROR).(*xerr.CodeError).Data()
		}
	})

	fmt.Printf("Starting server at %s:%d...\n", c.Host, c.Port)
	fmt.Println("v0.0.1")
	server.Start()
    }
  1. The (go-zero) error is
   func (ng *engine) bindRoute(fr featuredRoutes, router httpx.Router, metrics *stat.Metrics,
	route Route, verifier func(chain.Chain) chain.Chain) error {
	chn := ng.chain
	if chn == nil {
		chn = chain.New(
			handler.TracingHandler(ng.conf.Name, route.Path),
			ng.getLogHandler(),
			handler.PrometheusHandler(route.Path),
			handler.MaxConns(ng.conf.MaxConns),
			handler.BreakerHandler(route.Method, route.Path, metrics),
			handler.SheddingHandler(ng.getShedder(fr.priority), metrics),
			handler.TimeoutHandler(ng.checkedTimeout(fr.timeout)),
			handler.RecoverHandler,
			handler.MetricHandler(metrics),
			handler.MaxBytesHandler(ng.checkedMaxBytes(fr.maxBytes)),
			handler.GunzipHandler,
		)
	}

	chn = ng.appendAuthHandler(fr, chn, verifier)

	for _, middleware := range ng.middlewares {
		chn = chn.Append(convertMiddleware(middleware))
	}
	handle := chn.ThenFunc(route.Handler)

	return router.Handle(route.Method, route.Path, handle)
   }

Expected behavior

the code path : go-zero/rest/engine.go

chn = ng.appendAuthHandler(fr, chn, verifier)

the function bindRoute() , include the function "handler.WithUnauthorizedCallback()" , lead to config rest.WithCors("*") invalid

func (ng *engine) appendAuthHandler(fr featuredRoutes, chn chain.Chain,
	verifier func(chain.Chain) chain.Chain) chain.Chain {
	chn.Prepend()
	if fr.jwt.enabled {
		if len(fr.jwt.prevSecret) == 0 {
			chn = chn.Append(handler.Authorize(fr.jwt.secret,
				handler.WithUnauthorizedCallback(ng.unauthorizedCallback)))
		} else {
			chn = chn.Append(handler.Authorize(fr.jwt.secret,
				handler.WithPrevSecret(fr.jwt.prevSecret),
				handler.WithUnauthorizedCallback(ng.unauthorizedCallback)))
		}
	}

	return verifier(chn)
}

Environments (please complete the following information):

  • OS: [Linux ubuntu]
  • go-zero version [1.3.4]
  • goctl version [1.3.4]

ctra-wang avatar Jul 18 '22 02:07 ctra-wang

1、使用正确的jwt请求,返回结果正常 image

2、使用错误的jwt请求,返回结果正常 image

3、不携带jwt请求,返回结果正常 image

本次修复有效

ctra-wang avatar Aug 22 '22 06:08 ctra-wang

Bot detected the issue body's language is not English, translate it automatically. 👯👭🏻🧑‍🤝‍🧑👫🧑🏿‍🤝‍🧑🏻👩🏾‍🤝‍👨🏿👬🏿


  1. Use the correct jwt request, and the returned result is normal image

  2. Using the wrong jwt request, the return result is normal image

  3. Without jwt request, the returned result is normal image

This fix works

Issues-translate-bot avatar Aug 22 '22 06:08 Issues-translate-bot