MCPcopy Create free account
hub / github.com/cli/cli / AddAuthTokenHeader

Function AddAuthTokenHeader

api/http_client.go:154–190  ·  view source on GitHub ↗

AddAuthTokenHeader adds an authentication token header for the host specified by the request.

(rt http.RoundTripper, cfg config)

Source from the content-addressed store, hash-verified

152
153// AddAuthTokenHeader adds an authentication token header for the host specified by the request.
154func AddAuthTokenHeader(rt http.RoundTripper, cfg config) http.RoundTripper {
155 return &funcTripper{roundTrip: func(req *http.Request) (*http.Response, error) {
156 // If the header is already set in the request, don't overwrite it.
157 if req.Header.Get(authorization) != "" {
158 return rt.RoundTrip(req)
159 }
160
161 var redirectHostnameChange bool
162 if req.Response != nil && req.Response.Request != nil {
163 redirectHostnameChange = getHostname(req) != getHostname(req.Response.Request)
164 }
165
166 // Only set header if an initial request or redirect request to the same host as the initial request.
167 // If the host has changed during a redirect do not add the authentication token header.
168 if redirectHostnameChange {
169 return rt.RoundTrip(req)
170 }
171
172 hostnameInRequest := ghauth.NormalizeHostname(getHostname(req))
173 token, _ := cfg.ActiveToken(hostnameInRequest)
174 if token == "" {
175 // The request may be aimed at a host's api_host, which gh is
176 // not logged in to and so has no token of its own. Fall back
177 // to the token of the host it stands in for. This only ever
178 // adds a token where there would have been none, so hosts we
179 // already authenticate keep resolving exactly as before.
180 if canonicalHost, ok := cfg.HostForAPIHost(hostnameInRequest); ok {
181 token, _ = cfg.ActiveToken(canonicalHost)
182 }
183 }
184 if token != "" {
185 req.Header.Set(authorization, fmt.Sprintf("token %s", token))
186 }
187
188 return rt.RoundTrip(req)
189 }}
190}
191
192// ExtractHeader extracts a named header from any response received by this client and,
193// if non-blank, saves it to dest.

Calls 6

getHostnameFunction · 0.85
GetMethod · 0.65
ActiveTokenMethod · 0.65
HostForAPIHostMethod · 0.65
SetMethod · 0.65
RoundTripMethod · 0.45