/*
本函数所生成结果的用法
用法一：写入header头的属性“Authorization”中，值设为：前缀BEARER加tokenString的值
用法二：发送post或get参数“access_token”，值设为：tokenString的值
*/
511025
func (j *JWT) Response(values map[string]interface{}) (tokenString string, err error) {
	token := jwt.New(jwt.SigningMethodHS256)
	// Headers
	token.Header["alg"] = "HS256"
	token.Header["typ"] = "JWT"
	// Claims
	token.Claims = values
	token.Claims["exp"] = time.Now().Add(time.Hour * 72).Unix()
	tokenString, err = token.SignedString([]byte(j.Secret))
	return
}
578335
func (this *serviceImpl) get_token_from_header_query_param(req *http.Request) (*Token, error) {
	if this.settings.VerifyKeyFromHttpRequest == nil {
		return nil, ErrNoVerifyKey
	}
	t, err := jwt.ParseFromRequest(req, func(*jwt.Token) (interface{}, error) {
		return this.settings.VerifyKeyFromHttpRequest(req), nil
	})
	if err != nil {
		return nil, err
	}
	return this.check_token(t)
}
155140
func GetToken(r *http.Request) (string, error) {
	header := r.Header.Get("Authorization")
	if header == "" {
		return "", ErrAuthHeaderMissing
	}
	if !strings.HasPrefix(header, tokenScheme) {
		return "", ErrAuthBadScheme
	}
	return header[len(tokenScheme):], nil
}
1197003
func Token(ctx context.Context) *AuthorizationToken {
	v := ctx.Value(tokenIndex)
	if v == nil {
		return nil
	}
	return v.(*AuthorizationToken)
}
1169604
func (b *BearerJWT) Token(username string) (string, error) {
	if b.Now == nil {
		b.Now = time.Now
	}
	return JWT(username, b.SharedSecret, b.Now)
}
1359460
func (a *AuthorizeTokenGenDefault) GenerateAuthorizeToken(data *AuthorizeData) (ret string, err error) {
	token := uuid.NewRandom()
	return base64.RawURLEncoding.EncodeToString([]byte(token)), nil
}
1038675
func (a *accessToken) DecorateRequest(req *http.Request) {
	var token string

	// try to get new token and fall back to parent token
	if a.scope != "" {
		token, _ = a.manager.TokenForScope(a.scope)
	}

	if token == "" {
		token = a.accessToken
	}

	req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", token))
}
1223915
func (auth *Auth) ResponseHeader(ext string) string {
	auth.Ext = ext
	if auth.ReqHash {
		auth.Hash = nil
	}

	h := `Hawk mac="` + base64.StdEncoding.EncodeToString(auth.mac(AuthResponse)) + `"`
	if auth.Ext != "" {
		h += `, ext="` + auth.Ext + `"`
	}
	if auth.Hash != nil {
		h += `, hash="` + base64.StdEncoding.EncodeToString(auth.Hash) + `"`
	}

	return h
}
353575
func (t *Token) SigningString() (string, error) {
	var err error
	parts := make([]string, 2)
	for i, _ := range parts {
		var jsonValue []byte
		if i == 0 {
			if jsonValue, err = json.Marshal(t.Header); err != nil {
				return "", err
			}
		} else {
			if jsonValue, err = json.Marshal(t.Claims); err != nil {
				return "", err
			}
		}

		parts[i] = EncodeSegment(jsonValue)
	}
	return strings.Join(parts, "."), nil
}
744173
func (c *Config) Token(ctx context.Context) (*oauth2.Token, error) {
	return retrieveToken(ctx, c, url.Values{
		"grant_type": {"client_credentials"},
		"scope":      internal.CondVal(strings.Join(c.Scopes, " ")),
	})
}
1322521
func csrfTokenFromHeader(header string) csrfTokenExtractor {
	return func(c echo.Context) (string, error) {
		return c.Request().Header().Get(header), nil
	}
}
1286381
func GetBearerTokenFromReq(ctx types.Context, req *http.Request) string {
	m := rxBearer.FindStringSubmatch(
		req.Header.Get(types.AuthorizationHeader))
	if len(m) == 0 {
		return ""
	}
	return m[1]
}
1022797
func (us UsersService) GetToken(username, password string, client Client) (string, error) {
	req := network.Request{
		Method:        "POST",
		Path:          "/oauth/token",
		Authorization: network.NewBasicAuthorization(client.ID, ""),
		Body: network.NewFormRequestBody(url.Values{
			"username":      []string{username},
			"password":      []string{password},
			"grant_type":    []string{"password"},
			"response_type": []string{"token"},
		}),
		AcceptableStatusCodes: []int{http.StatusOK},
	}

	resp, err := newNetworkClient(us.config).MakeRequest(req)
	if err != nil {
		return "", translateError(err)
	}

	var responseBody struct {
		AccessToken string `json:"access_token"`
	}
	err = json.Unmarshal(resp.Body, &responseBody)
	if err != nil {
		return "", MalformedResponseError{err}
	}

	return responseBody.AccessToken, nil
}
1130695
func BearerFunc(authfn func(string) bool) macaron.Handler {
	return func(res http.ResponseWriter, req *http.Request, c *macaron.Context) {
		auth := req.Header.Get("Authorization")
		n := len(bearerPrefix)
		if len(auth) < n || auth[:n] != bearerPrefix {
			bearerUnauthorized(res)
			return
		}
		if !authfn(auth[n:]) {
			bearerUnauthorized(res)
			return
		}
		c.Map(User(""))
	}
}
21579
func Header(name, val string) RequestOption {
	return func(req *http.Request) error {
		req.Header.Add(name, val)
		return nil
	}
}
662960
func (c *Client) grantToken(params url.Values) (*Token, error) {
	// Create the access token url params
	if params == nil {
		params = make(url.Values)
	}

	// Add the client id, client secret and code to the query params
	params.Set("client_id", c.ClientId)
	params.Set("client_secret", c.ClientSecret)
	params.Set("redirect_uri", c.RedirectURL)

	// Create the access token request url
	endpoint, _ := url.Parse(c.AccessTokenURL)

	// Create the http request
	req := http.Request{
		URL:        endpoint,
		Method:     "POST",
		ProtoMajor: 1,
		ProtoMinor: 1,
		Close:      true,
	}

	// Encode the URL paraemeters in the Body of the Request
	encParams := params.Encode()
	reader := strings.NewReader(encParams)
	req.Body = ioutil.NopCloser(reader)

	// Add the header params
	header := make(http.Header)
	header.Set("Accept", "application/json")
	header.Set("Content-Type", "application/x-www-form-urlencoded")
	header.Set("Content-length", strconv.Itoa(len(encParams)))
	req.Header = header

	// Do the http request and get the response
	resp, err := http.DefaultClient.Do(&req)
	if err != nil {
		return nil, err
	}

	// Get the response body
	raw, err := ioutil.ReadAll(resp.Body)
	defer resp.Body.Close()
	if err != nil {
		return nil, err
	}

	// Unmarshal the json response body to get the token
	token := Token{}
	if err := json.Unmarshal(raw, &token); err != nil {
		return nil, err
	}

	// If no access token is provided it must be an error. Normally
	// we would check the StatusCode, however, some providers return
	// a 200 Status OK even if there is an error :(
	if len(token.AccessToken) == 0 {
		oauthError := Error{}
		if err := json.Unmarshal(raw, &oauthError); err != nil {
			return nil, err
		}
		return nil, oauthError
	}

	return &token, nil
}
182680
func (c *TokensClient) CreateAuth(ctx context.Context, authorization string, authTokenRequest *AuthTokenRequest) (*AuthToken, error) {
	p := "/tokens/auth"

	req, err := c.backend.NewRequest(http.MethodPost, p, nil, authTokenRequest)
	if err != nil {
		return nil, err
	}

	req.Header.Set("authorization", authorization)

	var resp AuthToken
	_, err = c.backend.Do(ctx, req, &resp, func(code int) error {
		return &Error{}
	})
	if err != nil {
		return nil, err
	}

	return &resp, nil
}