如何设置授权 Bearer 令牌头部

huangapple go评论1491阅读模式
英文:

How to set Authorization Bearer token header

问题

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

我使用以下代码将令牌设置在响应的Authorization头部:

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("Authorization")

如果我使用该代码,我会收到没有授权头部的错误。

英文:

I am using JWT tokens for authentication and authorizaton process. I wish to set jwt token in "Authorization: Bearer <token> ".

w.Header().Add(&quot;Authorization&quot;, &quot;Bearer &quot;+TokenString)

I have used the above line to set my token in Authorization header in my response.

I need to use the token to access my other end points.

If I try to access the other end points using this header token. I cant able to do that. I am getting error as no authorization header.

This is my login function

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

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

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

The following line is used to get the token from header

authHeader := r.Header.Get("Authorization")

If I use that line, I am getting error as no authorization header.

答案1

得分: 2

尝试使用Set函数。

根据文档,Add会将值追加到与键相关联的任何现有值中,而Set会将与键相关联的标头条目设置为单个元素值。它会替换与键相关联的任何现有值。

req.Header.Set("Authorization", "Bearer "+jwtToken)
英文:

Try using Set function.

According to the documentation,
Add appends to any existing values associated with key, while Set sets the header entries associated with key to the single element value. It replaces any existing values associated with key.

req.Header.Set(&quot;Authorization&quot;, &quot;Bearer &quot;+jwtToken)

答案2

得分: -1

在你的代码中似乎有一个小错误。在Login函数中,你使用w.Header().Add("Authorization", "Bearer "+TokenString)将token设置在响应头中,但是你没有使用正确的变量来表示token。相反,你应该使用token(你生成的那个)而不是TokenString。

这是修正后的Login函数版本:

func (c *Customer) Login(w http.ResponseWriter, r *http.Request) {
    // ... 你现有的代码 ...

    token, err := c.customer.GenerateToken(customer)
    if err != nil || token == "" {
        w.WriteHeader(http.StatusUnauthorized)
        w.Write([]byte("无法生成token"))
        return
    }
    
    // 在这里使用 'token' 而不是 'TokenString'
    w.Header().Add("Authorization", "Bearer "+token)

    w.WriteHeader(http.StatusAccepted)
    w.Write([]byte("登录成功"))
    return
}

希望对你有帮助!

英文:

It seems like there might be a small mistake in your code. In the Login function, you are setting the token in the response header using w.Header().Add("Authorization", "Bearer "+TokenString), but you are not using the correct variable for the token. Instead, you should use token (the one you generated) instead of TokenString.

Here's the corrected version of your Login function:

func (c *Customer) Login(w http.ResponseWriter, r *http.Request) {
// ... Your existing code ...

token, err := c.customer.GenerateToken(customer)
if err != nil || token == &quot;&quot; {
    w.WriteHeader(http.StatusUnauthorized)
    w.Write([]byte(&quot;Cannot able to generate token&quot;))
    return
}

// Use &#39;token&#39; instead of &#39;TokenString&#39; here
w.Header().Add(&quot;Authorization&quot;, &quot;Bearer &quot;+token)

w.WriteHeader(http.StatusAccepted)
w.Write([]byte(&quot;Logged in successfully&quot;))
return
}

huangapple
  • 本文由 发表于 2023年7月28日 13:20:12
  • 转载请务必保留本文链接:https://go.coder-hub.com/76785024.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定