2016-07-22 12:44
浏览 1.7k


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?


图片转代码服务由CSDN问答提供 功能建议

我是刚开始使用JWT的人,在某个时候我很挣扎: \ n


如何将JWT用于“正常”请求? F.E. 重新加载页面或仅跟随链接时。

F.e。 如果用户未登录,我想将他重定向到登录页面。

在服务器端,我具有中间件,该中间件从授权标头检查JWT,然后 要么授予权限,要么重定向到登录页面,但是由于没有针对非ajax请求的授权标头,因此我目前总是在访问登录页面。

我 将JWT存储在本地存储中。



  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 邀请回答

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,
            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

    解决 无用
    打赏 举报

相关推荐 更多相似问题