douzhao6584 2018-04-09 02:15
浏览 77
已采纳

在Go Web App路由器中检查用户权限的最佳方法

My web app has URLs at three access levels:

  • Those accessible by anyone (login page and static assets)
  • Those accessible regular users and admins who are logged in
  • Those accessible only by admins who are logged in

I should specify the minimum access level for each URL pattern in my router, so that people below that level are blocked. (I suppose they should get HTTP error 401 or 403.)

How do I best implement these checks so that I don't have to remember to put them in every URL handler function separately (which is very easy to forget)? Ideally I'd like to do something like this:

router.Get("/someRegularPage", regularAccess(handleSomeRegularPage))
router.Get("/someAdminPage", adminAccess(handleSomeAdminPage))
router.Get("/", publicAccess(handleLoginPage))

Is there some semi-standard middleware to do this and how does that work? How hard would it be to write my own?

Additionally, it would be great if the default permission was to deny access to everybody in case I forget to specify the access level for some URL. A compiler warning or error would be ideal.

  • 写回答

2条回答 默认 最新

  • dongyi9484 2018-04-09 02:33
    关注

    Writing your own is not hard. Assuming you store your admin token in an environment variable called ADMINTOKEN :

    func AdminOnly(f func(w http.ResponseWriter, r *http.Request)) func(w http.ResponseWriter, r *http.Request) {
        return func(w http.ResponseWriter, r *http.Request) {
            w.Header().Set("Access-Control-Allow-Headers", "Accept, Content-Type, Content-Length, Accept-Encoding, Authorization")
            if r.Method == "OPTIONS" {
                f(w, r)
                return
            }
    
            h := r.Header.Get("Authorization")
            token := strings.TrimPrefix(h, "Bearer ")
            if token == os.Getenv("ADMINTOKEN") {
                f(w, r)
                return
            }
    
            http.Error(w, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized)
        }
    }
    

    OPTIONS method may have to be authorized regardless because of CORS.

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

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部