donglu3184 2016-07-22 12:44
浏览 1727
已采纳

使用JWT,如何检查Authorization-Header?

i'm completely new to working with JWT and i'm struggling at a certain point:

with ajax requests i can set the authorization-header before the request...ok.

How do i use the JWT for "normal" requests? F.e. when reloading the page or simply following a link.

F.e. if a user isn't logged in, i want to redirect him to a landing-page.

On the server-side i have middleware that checks the JWT from the authorization-header and then either grants permission or redirects to the landing-page, but ofc currently i'm always getting the landing-page, because there's no authorization-header for non-ajax requests.

I'm storing the JWT in localstorage.

What am i missing?

Regards

  • 写回答

3条回答 默认 最新

  • dos8244 2016-07-22 18:30
    关注

    You can store the JWT in a Cookie. This way they will be sent with every request (including "normal" ones). Here is a code snippet from one of my projects:

    func loginHandler(w http.ResponseWriter, r *http.Request) {
        ...
        accessToken := newAccessToken(...) // returns a JWT with fields .Token and .Expires
        cookie := &http.Cookie{
            Name:     "access_token",
            Value:    accessToken.Token,
            HttpOnly: true,
            Secure:true,
            Expires: time.Unix(accessToken.Expires, 0),
            Path:    "/",
        }
        http.SetCookie(w, cookie)
        ...
    }
    

    And to retreive the token:

    func someHandler(w http.ResponseWriter, r *http.Request) {
        cookie, err := r.Cookie("access_token")
        if err != nil {
            // handle missing cookie
        }
        accessToken := cookie.Value
        ...
    }
    

    Note that Cookies are vulnerable to CSRF Attacks.

    Further reading: Where to Store your JWTs – Cookies vs HTML5 Web Storage

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

报告相同问题?

悬赏问题

  • ¥15 matlab有关常微分方程的问题求解决
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿
  • ¥15 回答4f系统的像差计算
  • ¥15 java如何提取出pdf里的文字?
  • ¥100 求三轴之间相互配合画圆以及直线的算法
  • ¥100 c语言,请帮蒟蒻写一个题的范例作参考
  • ¥15 名为“Product”的列已属于此 DataTable