如何在Go中设置Authorization Beare token header?

问题描述 投票:0回答:1

我目前正在使用 JWT 令牌进行身份验证和授权过程。我希望在“Authorization: Bearer”中设置 jwt 令牌。

w.Header().Add("Authorization", "Bearer "+TokenString)

我已使用上面的行在我的响应中的授权标头中设置我的令牌。

我需要使用令牌来访问我的其他端点。

如果我尝试使用此标头令牌访问其他端点。我做不到。我收到错误,因为没有授权标头。

这是我的登录功能

func (c *Customer) Login(w http.ResponseWriter, r *http.Request) {
    
    if r.Method != "POST" {
        w.WriteHeader(http.StatusBadRequest)
        w.Write([]byte("Method mismatch"))
        return
    }
    customer := mappers.Decode(w, r)
    if customer == nil {
        w.WriteHeader(http.StatusInternalServerError)
        w.Write([]byte("Cannot able to parse"))
        return
    }

    err := c.customer.CusotmerLoginService(customer)
    if err != nil {
        w.WriteHeader(http.StatusBadRequest)
        w.Write([]byte("UNauthorised user or Register first"))
        fmt.Println(err)
        return
    }

    token, err := c.customer.GenerateToken(customer)
    if err != nil || token == "" {
        w.WriteHeader(http.StatusUnauthorized)
        w.Write([]byte("Cannot able to generate token"))
        return
    }
    w.Header().Add("Authorization", "Bearer "+TokenString)
    w.WriteHeader(http.StatusAccepted)
    w.Write([]byte("Logined successfully"))
    return
}

以下行用于从标头获取令牌

authHeader := r.Header.Get("授权")

如果我使用该行,我会收到错误,因为没有授权标头。

go jwt http-headers authorization
1个回答
0
投票

尝试使用设置功能。

根据文档,

Add
附加到与 key 关联的任何现有值,而
Set
将与 key 关联的标头条目设置为单个元素值。它替换与键关联的任何现有值。

req.Header.Set("Authorization", "Bearer "+jwtToken)
© www.soinside.com 2019 - 2024. All rights reserved.