douzhao6584 2018-04-09 10: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 10: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条)

报告相同问题?

悬赏问题

  • ¥15 oracle集群安装出bug
  • ¥15 关于#python#的问题:自动化测试
  • ¥20 问题请教!vue项目关于Nginx配置nonce安全策略的问题
  • ¥15 教务系统账号被盗号如何追溯设备
  • ¥20 delta降尺度方法,未来数据怎么降尺度
  • ¥15 c# 使用NPOI快速将datatable数据导入excel中指定sheet,要求快速高效
  • ¥15 再不同版本的系统上,TCP传输速度不一致
  • ¥15 高德地图点聚合中Marker的位置无法实时更新
  • ¥15 DIFY API Endpoint 问题。
  • ¥20 sub地址DHCP问题