douxun1407 2018-11-12 22:51
浏览 235
已采纳

在JSON API调用上禁用CSRF

I have a website project. It uses Go and the Gorilla and it's CSRF packages to protect against CSRF. I also have a JSON API that authenticates using a JWT like token provider (internal), so a user must authenticate with that before issuing a JSON request each time. So the CSRF is not an issue on the JSON side. At least I don't think so.

Here's my code, where I am using a NewRouter for web Paths, and a Subrouter for the /api/v1/[endpoint]s. If I call a JSON endpoint that does a POST, the CSRF is engaged and I get a Forbidden - CSRF token invalid. I was under the assume, that perhaps a Sub Router would not have the middleware for the CSRF check associated with.

router := mux.NewRouter().StrictSlash(false)
router.Path("/").HandlerFunc(myApp.IndexHandler).Methods("GET")

apiRouter := router.PathPrefix("/api").Subrouter()
apiRouter.Path("/dosomething").HandlerFunc(myApp.DoSomethingAPIHandler).Methods("POST", "OPTIONS")

http.ListenAndServe(":8000",
    csrf.Protect(
        []byte("my-long-key-here-redacted"),
        csrf.Secure(false), // Set to false as we offload SSL elsewhere
    )(router)))

Question: How do I get my API to work with or without CSRF protection? Obviously, the web paths will need to be protected to protect form posts.

  • 写回答

1条回答 默认 最新

  • dtcyv3985 2018-11-12 23:55
    关注

    One option is to only use the CSRF protection on specific HTTP handlers, rather than protecting the entire router. Note that this will require you to perform a type conversion on your myApp.IndexHandler in order to satisfy the type signature for the function returned by csrf.Protect().

    router := mux.NewRouter().StrictSlash(false)
    
    // Instead of protecting your entire router, you can protect specific HTTP
    // handlers.
    router.Path("/").Handler(
        csrf.Protect(
            []byte("my-long-key-here-redacted"),
            csrf.Secure(false),
        )(http.HandlerFunc(myApp.IndexHandler)),
    ).Methods("GET")
    
    apiRouter := router.PathPrefix("/api").Subrouter()
    apiRouter.Path("/dosomething").HandlerFunc(myApp.DoSomethingAPIHandler).Methods("POST", "OPTIONS")
    
    http.ListenAndServe(
        ":8000",
        router,
    )
    

    Alternatively, you can use the function returned from csrf.Protect() to create your own middleware, with logic to only add the CSRF protection on certain requests. You could use this approach to only add protection on endpoints with the prefix /api for example, as I've done in the code below.

    protectionMiddleware := func(handler http.Handler) http.Handler {
        protectionFn := csrf.Protect(
            []byte("my-long-key-here-redacted"),
            csrf.Secure(false),
        )
    
        return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
            // Use some kind of condition here to see if the router should use
            // the CSRF protection. For the sake of this example, we'll check
            // the path prefix.
            if !strings.HasPrefix(r.URL.Path, "/api") {
                protectionFn(handler).ServeHTTP(w, r)
                return
            }
    
            handler.ServeHTTP(w, r)
        })
    }
    
    router := mux.NewRouter().StrictSlash(false)
    router.Path("/").HandlerFunc(myApp.IndexHandler).Methods("GET")
    
    apiRouter := router.PathPrefix("/api").Subrouter()
    apiRouter.Path("/dosomething").HandlerFunc(myApp.DoSomethingAPIHandler).Methods("POST", "OPTIONS")
    
    http.ListenAndServe(
        ":8000",
        protectionMiddleware(router),
    )
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?
  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3