dsfds656545 2015-02-09 19:55
浏览 48
已采纳

Negroni的路由特定中间件

I have a web server using httprouter and negroni. Users log into this system through external OAuth. We save the token to the encrypted session which indicates whether or not they are logged in. I would like to use a middleware to verify whether or not this token exists, and then kick the user back to the login page if it does not. I want to exclude some routes from using the authentication middleware. There is an example in the negroni README of doing this with gorilla mux, but I can't quite get my head around doing this scalably with httprouter. Something similar to my server setup is below:

router := httprouter.New()
router.GET("/login", Login) // auth not required
router.GET("/", Index)  // auth required

s := negroni.Classic()

s.Use(sessions.Sessions("example-web-dev", cookiestore.New([]byte("some garbage"))))
s.Use(authenticator.Get())
s.UseHandler(router)

Where /login is a route I do not want to require authorization through the middleware and / is. authenticator.Get() is my authentication handler func with contents I don't think are relevant to the question.

How can I apply authenticator.Get() to / but not /login? Keeping in mind that there will be several other "public" routes alongside /login and many other gated routes as well.

Some links:

  • 写回答

2条回答 默认 最新

  • duandui2803 2015-02-10 13:54
    关注

    I was eventually able to wrap my brain around this process. The solution is to create new negroni.Negroni instances for each individual route. In the case above:

    router := httprouter.New()
    router.Handler("GET", "/login",
                   negroni.New(negroni.HandlerFunc(loginHandler)))
    router.Handler("GET", "/",
                   negroni.New(authenticator.Get(),
                   negroni.HandlerFunc(indexHandler)))
    
    server := negroni.Classic()
    server.UseHandler(router)
    server.Use(sessions.Sessions("example-web-dev",
               cookiestore.New([]byte("some secret"))))
    server.Run(":3000")
    

    loginHandler and indexHandler will both need to have this method signature:

    func(http.ResponseWriter, *http.Request, http.HandlerFunc)
    

    With the given example, all routes will utilize the middleware provided by negroni.Classic() and the sessions middleware added to server, but only / will use the middleware I created in authenticator.Get().

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥30 YOLO检测微调结果p为1
  • ¥20 求快手直播间榜单匿名采集ID用户名简单能学会的
  • ¥15 DS18B20内部ADC模数转换器
  • ¥15 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题