Set Header on ReDirect

Hi,

I set a Header value and go Redirect.

w.Header().Set("Authorization", "Bearer "+token)
w.Header().Set("Location","/dashboard")
w.WriteHeader(301)
w.Write([]byte{})

The responseheader is not set! Why? How I get a Redirect with my old header?

Any reason you don’t use Redirect? Maybe like this:

w.Header().Set("Authorization", "Bearer "+token)
http.Redirect(w, r, "/dashboard", 301)

Its the same problem, header is not set!

Which header is not set? If you mean Authorization, note that this is a request header. It makes no sense to set it on the response.

https://developer.mozilla.org/de/docs/Web/HTTP/Headers/Authorization

1 Like

How set a header by redirect???

Which header to you want to set?

I would a redirect after login to dashboard with Authorization value ("Authorization", "Bearer "+token)

You should split this into two requests:

  1. Login: The server returns the token in the response body with status 200 OK. The client keeps the token for further requests.
  2. Open Dashboard: The client requests /dashboard and sets the Authorization header using the token received as the result of the previous request.

Ok, is a well-know way! But, the client is a normal website, with navigtion including tag links and i can’t set a header by call the next page. Ok, i like JS, but you can only set a header when use ajax, the header set from browser is false. https://developer.mozilla.org/en-US/docs/Web/API/Headers/set

When i use a onepage-site or Vue/React, then is any call a ajax-call.

I always wanted to loop the JWT token from the server site with set and get header.

Note that this is not a question specific to Go. How HTTP works is the same, no matter which programming language you use as the backed.

So maybe this forum is the wrong place to discussion this question.

How about setting a cookie including the JWT in the response? The backend should be able to extract the JWT both from a cookie and the Authorization header.

Yes, this is a GO-Question, as I search a workaround for http- response/request serversite. Cookie is not well, just got away from it!

When you me not can help, it’s ok, no problem, but try not to distract yourself by looking for a reason not to answer this question.

Redirecting won’t pass headers to destination if this is what you ask yourself. You must use other methods to forward headers like sessions.

1 Like

I am still trying to wrap my head around why is request Authorization header is needed in the server response?

If you want to keep the old data (headers, method, body …), use http code 308 instead. Client will re-send all data to new location. (Some client like OkHttp will not accept 308 method)

2 Likes

THX… That was the answer I was looking for! :kissing_closed_eyes: And welcome into the community!

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.