1

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

w.Header().Add("Authorization", "Bearer "+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 != "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
}

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.

2
  • 5
    Show the client code that is sending the Authorization header in subsequent requests. Note also that Authorization is a request-specific header and should generally not be used in responses, so w.Header().Add("Authorization", ... is bad style.
    – mkopriva
    Commented Jul 28, 2023 at 5:32
  • Thank you for your reply. I don't know how can i set authorization header for all other end points. Can you give me the code for that? Commented Jul 28, 2023 at 7:30

1 Answer 1

2

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("Authorization", "Bearer "+jwtToken)

Not the answer you're looking for? Browse other questions tagged or ask your own question.