对Header进行排序 只留下Authorization和X-Api-开始的Header
500487
private function sign_headers($headers) {
        if(is_array($headers)){
            ksort($headers);
            $result = array();
            foreach($headers as $key=>$value){
                if ( ($key == 'Authorization') || (substr($key, 0, 6)=='X-Api-') ) {
                    $result[] = $key.'='.$value;
                }
            }
            return implode('&', $result);
        }
    }
649030
def request(self, action, data={}, headers={}, method='GET'):
        
        headers = {
            "Authorization": "Bearer " + self.token,
            "Content-Type": "application/json",
            "X-Version": "1",
            "Accept": "application/json"
        }

        return Transport.request(self, action, data, headers, method)
747942
def to_header(self):
        """"""
        d = dict(self)
        auth_type = d.pop("__auth_type__", None) or "basic"
        return "%s %s" % (
            auth_type.title(),
            ", ".join(
                [
                    "%s=%s"
                    % (
                        key,
                        quote_header_value(
                            value, allow_token=key not in self._require_quoting
                        ),
                    )
                    for key, value in iteritems(d)
                ]
            ),
        )
335556
function genAuthorizationHeaderValue (options) {

    log(options.verbose,"Now generating Authorization header value ...");

    var authHeaderParams = [];

    authHeaderParams.push(createEncodedParam("oauth_consumer_key",options.oAuthConsumerKey));
    authHeaderParams.push(createEncodedParam("oauth_nonce",options.oAuthNonce));
    authHeaderParams.push(createEncodedParam("oauth_signature",options.oAuthSignature));
    authHeaderParams.push(createEncodedParam("oauth_signature_method",options.oAuthSignatureMethod));
    authHeaderParams.push(createEncodedParam("oauth_timestamp",options.oAuthTimestamp));
    authHeaderParams.push(createEncodedParam("oauth_token",options.oAuthToken));
    authHeaderParams.push(createEncodedParam("oauth_version",options.oAuthVersion));

    var authHeaderValue = "OAuth ";

    log(options.verbose,"Authorization header key/value pairs are:");

    for ( var i=0; i<authHeaderParams.length; i++ ) {
        log(options.verbose,"  "+authHeaderParams[i].key+"=\""+authHeaderParams[i].value+"\"");
        authHeaderValue += authHeaderParams[i].key+"=\""+authHeaderParams[i].value+"\"";
        if ( authHeaderParams[i+1] ) {
            authHeaderValue += ", ";
        }
    }

    log(options.verbose,"Authorization header value is: "+authHeaderValue);

    return authHeaderValue;
}
768315
public function toHeader()
    {
        $out = 'Authorization: OAuth realm=""';
        foreach ($this->parameters as $k => $v) {
            if (substr($k, 0, 5) != "oauth") {
                continue;
            }
            if (is_array($v)) {
                throw new Exception('Arrays not supported in headers');
            }
            $out .= ',' .
                Util::urlencodeRfc3986($k) .
                '="' .
                Util::urlencodeRfc3986($v) .
                '"';
        }
        return $out;
    }
784756
@Get("/header")
    public HttpResponse header(@Header String xArmeriaText,            /* no conversion */
                               @Header List<Integer> xArmeriaSequence, /* converted into integer */
                               Cookies cookies                         /* converted into Cookies object */)
            throws JsonProcessingException {
        return HttpResponse.of(HttpStatus.OK, MediaType.JSON_UTF_8, mapper.writeValueAsBytes(
                Arrays.asList(xArmeriaText,
                              xArmeriaSequence,
                              cookies.stream().map(Cookie::name).collect(Collectors.toList()))));
    }
18709
def _request(self, *args, **kwargs):
        """"""
        if not self.token:
            self._obtain_token()

        headers = {
            "Authorization": "Bearer {}".format(self.token)
        }

        # add authorization headers
        if "headers" in kwargs:
            kwargs["headers"].update(headers)
        else:
            kwargs["headers"] = headers

        # add api site to url
        args = list(args)
        if not args[1].startswith("http"):
            args[1] = "{}{}".format(API_URL, args[1])

        has_no_token = kwargs.get("no_token")
        if has_no_token:
            del kwargs["no_token"]
        resp = requests.request(*args, **kwargs)
        if resp.status_code == 401 and not has_no_token:
            self._obtain_token()
            kwargs["no_token"] = True
            self._request(*args, **kwargs)
        return resp
190135
def _get_authorization_headers(self, context):
        
        headers = {}
        self._credentials.before_request(
            self._request,
            context.method_name,
            context.service_url,
            headers)

        return list(six.iteritems(headers))
976269
def get_auth_header(self, user_payload):
        
        auth_token = self.get_auth_token(user_payload)
        return '{auth_header_prefix} {auth_token}'.format(
            auth_header_prefix=self.auth_header_prefix, auth_token=auth_token
        )
310231
def __api_request(self, method, endpoint, params={}, files={}, headers={}, access_token_override=None, do_ratelimiting=True, use_json = False):
        
        response = None
        remaining_wait = 0
        # "pace" mode ratelimiting: Assume constant rate of requests, sleep a little less long than it
        # would take to not hit the rate limit at that request rate.
        if do_ratelimiting and self.ratelimit_method == "pace":
            if self.ratelimit_remaining == 0:
                to_next = self.ratelimit_reset - time.time()
                if to_next > 0:
                    # As a precaution, never sleep longer than 5 minutes
                    to_next = min(to_next, 5 * 60)
                    time.sleep(to_next)
            else:
                time_waited = time.time() - self.ratelimit_lastcall
                time_wait = float(self.ratelimit_reset - time.time()) / float(self.ratelimit_remaining)
                remaining_wait = time_wait - time_waited

            if remaining_wait > 0:
                to_next = remaining_wait / self.ratelimit_pacefactor
                to_next = min(to_next, 5 * 60)
                time.sleep(to_next)

        # Generate request headers
        headers = copy.deepcopy(headers)
        if not self.access_token is None:
            headers['Authorization'] = 'Bearer ' + self.access_token
        if not access_token_override is None:
            headers['Authorization'] = 'Bearer ' + access_token_override

        if self.debug_requests:
            print('Mastodon: Request to endpoint "' + endpoint + '" using method "' + method + '".')
            print('Parameters: ' + str(params))
            print('Headers: ' + str(headers))
            print('Files: ' + str(files))

        # Make request
        request_complete = False
        while not request_complete:
            request_complete = True

            response_object = None
            try:
                kwargs = dict(headers=headers, files=files,
                              timeout=self.request_timeout)
                if use_json == False:
                    if method == 'GET':
                        kwargs['params'] = params
                    else:
                        kwargs['data'] = params
                else:
                    kwargs['json'] = params
                    
                response_object = self.session.request(
                        method, self.api_base_url + endpoint, **kwargs)
            except Exception as e:
                raise MastodonNetworkError("Could not complete request: %s" % e)

            if response_object is None:
                raise MastodonIllegalArgumentError("Illegal request.")

            # Parse rate limiting headers
            if 'X-RateLimit-Remaining' in response_object.headers and do_ratelimiting:
                self.ratelimit_remaining = int(response_object.headers['X-RateLimit-Remaining'])
                self.ratelimit_limit = int(response_object.headers['X-RateLimit-Limit'])

                try:
                    ratelimit_reset_datetime = dateutil.parser.parse(response_object.headers['X-RateLimit-Reset'])
                    self.ratelimit_reset = self.__datetime_to_epoch(ratelimit_reset_datetime)

                    # Adjust server time to local clock
                    if 'Date' in response_object.headers:
                        server_time_datetime = dateutil.parser.parse(response_object.headers['Date'])
                        server_time = self.__datetime_to_epoch(server_time_datetime)
                        server_time_diff = time.time() - server_time
                        self.ratelimit_reset += server_time_diff
                        self.ratelimit_lastcall = time.time()
                except Exception as e:
                    raise MastodonRatelimitError("Rate limit time calculations failed: %s" % e)

            # Handle response
            if self.debug_requests:
                print('Mastodon: Response received with code ' + str(response_object.status_code) + '.')
                print('response headers: ' + str(response_object.headers))
                print('Response text content: ' + str(response_object.text))

            if not response_object.ok:
                try:
                    response = response_object.json(object_hook=self.__json_hooks)
                    if isinstance(response, dict) and 'error' in response:
                        error_msg = response['error']
                    elif isinstance(response, str):
                        error_msg = response
                    else:
                        error_msg = None
                except ValueError:
                    error_msg = None

                # Handle rate limiting
                if response_object.status_code == 429:
                    if self.ratelimit_method == 'throw' or not do_ratelimiting:
                        raise MastodonRatelimitError('Hit rate limit.')
                    elif self.ratelimit_method in ('wait', 'pace'):
                        to_next = self.ratelimit_reset - time.time()
                        if to_next > 0:
                            # As a precaution, never sleep longer than 5 minutes
                            to_next = min(to_next, 5 * 60)
                            time.sleep(to_next)
                            request_complete = False
                            continue

                if response_object.status_code == 404:
                    ex_type = MastodonNotFoundError
                    if not error_msg:
                        error_msg = 'Endpoint not found.'
                        # this is for compatibility with older versions
                        # which raised MastodonAPIError('Endpoint not found.')
                        # on any 404
                elif response_object.status_code == 401:
                    ex_type = MastodonUnauthorizedError
                elif response_object.status_code == 502:
                    ex_type = MastodonServerError
                else:
                    ex_type = MastodonAPIError

                raise ex_type(
                        'Mastodon API returned error',
                        response_object.status_code,
                        response_object.reason,
                        error_msg)

            try:
                response = response_object.json(object_hook=self.__json_hooks)
            except:
                raise MastodonAPIError(
                    "Could not parse response as JSON, response code was %s, "
                    "bad json content was '%s'" % (response_object.status_code,
                                                   response_object.content))

            # Parse link headers
            if isinstance(response, list) and \
                    'Link' in response_object.headers and \
                    response_object.headers['Link'] != "":
                tmp_urls = requests.utils.parse_header_links(
                    response_object.headers['Link'].rstrip('>').replace('>,<', ',<'))
                for url in tmp_urls:
                    if 'rel' not in url:
                        continue

                    if url['rel'] == 'next':
                        # Be paranoid and extract max_id specifically
                        next_url = url['url']
                        matchgroups = re.search(r"[?&]max_id=([^&]+)", next_url)

                        if matchgroups:
                            next_params = copy.deepcopy(params)
                            next_params['_pagination_method'] = method
                            next_params['_pagination_endpoint'] = endpoint
                            max_id = matchgroups.group(1)
                            if max_id.isdigit():
                                next_params['max_id'] = int(max_id)
                            else:
                                next_params['max_id'] = max_id
                            if "since_id" in next_params:
                                del next_params['since_id']
                            if "min_id" in next_params:
                                del next_params['min_id']
                            response[-1]._pagination_next = next_params

                    if url['rel'] == 'prev':
                        # Be paranoid and extract since_id or min_id specifically
                        prev_url = url['url']
                        
                        # Old and busted (pre-2.6.0): since_id pagination
                        matchgroups = re.search(r"[?&]since_id=([^&]+)", prev_url)
                        if matchgroups:
                            prev_params = copy.deepcopy(params)
                            prev_params['_pagination_method'] = method
                            prev_params['_pagination_endpoint'] = endpoint
                            since_id = matchgroups.group(1)
                            if since_id.isdigit():
                                prev_params['since_id'] = int(since_id)
                            else:
                                prev_params['since_id'] = since_id
                            if "max_id" in prev_params:
                                del prev_params['max_id']
                            response[0]._pagination_prev = prev_params
                            
                        # New and fantastico (post-2.6.0): min_id pagination
                        matchgroups = re.search(r"[?&]min_id=([^&]+)", prev_url)
                        if matchgroups:
                            prev_params = copy.deepcopy(params)
                            prev_params['_pagination_method'] = method
                            prev_params['_pagination_endpoint'] = endpoint
                            min_id = matchgroups.group(1)
                            if min_id.isdigit():
                                prev_params['min_id'] = int(min_id)
                            else:
                                prev_params['min_id'] = min_id
                            if "max_id" in prev_params:
                                del prev_params['max_id']
                            response[0]._pagination_prev = prev_params

        return response
27133
def SendSOAPDataHTTPDigestAuth(self, response, soapdata, url, request_uri, soapaction, **kw):
        '''
        '''
        if self.trace:
            print >>self.trace, "------ Digest Auth Header"
        url = url or self.url
        if response.status != 401:
            raise RuntimeError, 'Expecting HTTP 401 response.'
        if self.auth_style != AUTH.httpdigest:
            raise RuntimeError,\
                'Auth style(%d) does not support requested digest authorization.' %self.auth_style

        from pyremotevbox.ZSI.digest_auth import fetch_challenge,\
            generate_response,\
            build_authorization_arg,\
            dict_fetch

        chaldict = fetch_challenge( response.getheader('www-authenticate') )
        if dict_fetch(chaldict,'challenge','').lower() == 'digest' and \
            dict_fetch(chaldict,'nonce',None) and \
            dict_fetch(chaldict,'realm',None) and \
            dict_fetch(chaldict,'qop',None):
            authdict = generate_response(chaldict,
                request_uri, self.auth_user, self.auth_pass, method='POST')
            headers = {\
                'Authorization':build_authorization_arg(authdict),
                'Expect':'100-continue',
            }
            self.SendSOAPData(soapdata, url, soapaction, headers, **kw)
            return

        raise RuntimeError,\
            'Client expecting digest authorization challenge.'
1215605
def _get_token_from_headers(self, request, refresh_token):
        
        header = request.headers.get(self.config.authorization_header(), None)

        if header is None:
            return None

        else:
            header_prefix_key = "authorization_header_prefix"
            header_prefix = getattr(self.config, header_prefix_key)
            if header_prefix():
                try:
                    prefix, token = header.split(" ")
                    if prefix != header_prefix():
                        raise Exception

                except Exception:
                    raise exceptions.InvalidAuthorizationHeader()

            else:
                token = header

            if refresh_token:
                token = request.json.get(self.config.refresh_token_name())

            return token
795542
def authorization_middleware(environ, start_response=None):
    '''
    '''
    key = 'http.authorization'
    c = environ.get(key)
    if c is None:
        code = 'HTTP_AUTHORIZATION'
        if code in environ:
            environ[key] = parse_authorization_header(environ[code])
1029753
def headers(self, url):
        
        if self._token and url.lower().startswith('https'):
            return {'Authorization': 'Bearer {}'.format(self._token)}
        else:
            return None
1363453
function(req, res, next) {
                    if (req.headers.origin === undefined) {
                        res.setHeader('Access-Control-Allow-Origin', "*");
                    } else {
                        res.setHeader('Access-Control-Allow-Origin', req.headers.origin);
                    }
                    res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
                    console.log(req.method + " on " + req.originalUrl);
                    if (req.method === "OPTIONS") {
                        res.setHeader('Access-Control-Allow-Headers', 'content-type');
                        res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
                        res.setHeader('Content-Length', '0');
                        res.setHeader('Content-Type', 'application/json; charset=utf-8');
                        grunt.file.read(req.originalUrl.split("?")[0]);
                        //res.write(body);
                        res.end("200");
                        //next();
                    } else {
                        next();
                    }
                }
1035999
def oauth_access_token_from_header
      auth_header = request.env['HTTP_AUTHORIZATION'] || ''
      match = auth_header.match(/^Bearer\s(.*)/)
      return match[1] if match.present?
      false
    end
1121188
public function userAuthorization() {
        #返回Token信息
        $accessToken = $this->getUserAccessToken($_GET['code']);
        $reverse     = $this->isAttention($accessToken['openid']);
        #获取跳转URL地址
        $url = urldecode($_GET['state']) . "/openid/" . $accessToken['openid'] . "/subscribe/" . $reverse['subscribe'];
        #授权跳转
        redirect($url);
        exit(1);
    }