// requestToken returns the issued token (pad + masked token) from the HTTP POST
// body or HTTP header. It will return nil if the token fails to decode.
496836
func (cs *csrf) requestToken(r *http.Request) []byte {
	// 1. Check the HTTP header first.
	issued := r.Header.Get(cs.opts.RequestHeader)

	// 2. Fall back to the POST (form) value.
	if issued == "" {
		issued = r.PostFormValue(cs.opts.FieldName)
	}

	// 3. Finally, fall back to the multipart form (if set).
	if issued == "" && r.MultipartForm != nil {
		vals := r.MultipartForm.Value[cs.opts.FieldName]

		if len(vals) > 0 {
			issued = vals[0]
		}
	}

	// Decode the "issued" (pad + masked) token sent in the request. Return a
	// nil byte slice on a decoding error (this will fail upstream).
	decoded, err := base64.StdEncoding.DecodeString(issued)
	if err != nil {
		return nil
	}

	return decoded
}
421935
func (s *ProvisioningService) GetToken(token string) (services.ProvisionToken, error) {
	if token == "" {
		return nil, trace.BadParameter("missing parameter token")
	}
	item, err := s.Get(context.TODO(), backend.Key(tokensPrefix, token))
	if err != nil {
		return nil, trace.Wrap(err)
	}
	return services.UnmarshalProvisionToken(item.Value, services.SkipValidation(),
		services.WithResourceID(item.ID), services.WithExpires(item.Expires))
}
1289537
func Token(r *http.Request) string {
	if val, err := contextGet(r, tokenKey); err == nil {
		if maskedToken, ok := val.(string); ok {
			return maskedToken
		}
	}

	return ""
}
770737
func (authy *Authy) VerifyToken(userID string, token string, params url.Values) (*TokenVerification, error) {
	path := "/protected/json/verify/" + url.QueryEscape(token) + "/" + url.QueryEscape(userID)

	response, err := authy.DoRequest("GET", path, params)

	if err != nil {
		Logger.Println("Error while contacting the API:", err)
		return nil, err
	}

	defer closeResponseBody(response)

	tokenVerification, err := NewTokenVerification(response)
	return tokenVerification, err
}
1371894
func GetToken(c cookoo.Context, p *cookoo.Params) (interface{}, cookoo.Interrupt) {
	t, err := Token()
	if err != nil {
		return "", err
	}
	return string(t), err
}
531436
func (ts *tokenServer) postToken(ctx context.Context, w http.ResponseWriter, r *http.Request) {
	grantType := r.PostFormValue("grant_type")
	if grantType == "" {
		handleError(ctx, ErrorMissingRequiredField.WithDetail("missing grant_type value"), w)
		return
	}

	service := r.PostFormValue("service")
	if service == "" {
		handleError(ctx, ErrorMissingRequiredField.WithDetail("missing service value"), w)
		return
	}

	clientID := r.PostFormValue("client_id")
	if clientID == "" {
		handleError(ctx, ErrorMissingRequiredField.WithDetail("missing client_id value"), w)
		return
	}

	var offline bool
	switch r.PostFormValue("access_type") {
	case "", "online":
	case "offline":
		offline = true
	default:
		handleError(ctx, ErrorUnsupportedValue.WithDetail("unknown access_type value"), w)
		return
	}

	requestedAccessList := ResolveScopeList(ctx, r.PostFormValue("scope"))

	var subject string
	var rToken string
	switch grantType {
	case "refresh_token":
		rToken = r.PostFormValue("refresh_token")
		if rToken == "" {
			handleError(ctx, ErrorUnsupportedValue.WithDetail("missing refresh_token value"), w)
			return
		}
		rt, ok := ts.refreshCache[rToken]
		if !ok || rt.service != service {
			handleError(ctx, errcode.ErrorCodeUnauthorized.WithDetail("invalid refresh token"), w)
			return
		}
		subject = rt.subject
	case "password":
		ca, ok := ts.accessController.(auth.CredentialAuthenticator)
		if !ok {
			handleError(ctx, ErrorUnsupportedValue.WithDetail("password grant type not supported"), w)
			return
		}
		subject = r.PostFormValue("username")
		if subject == "" {
			handleError(ctx, ErrorUnsupportedValue.WithDetail("missing username value"), w)
			return
		}
		password := r.PostFormValue("password")
		if password == "" {
			handleError(ctx, ErrorUnsupportedValue.WithDetail("missing password value"), w)
			return
		}
		if err := ca.AuthenticateUser(subject, password); err != nil {
			handleError(ctx, errcode.ErrorCodeUnauthorized.WithDetail("invalid credentials"), w)
			return
		}
	default:
		handleError(ctx, ErrorUnsupportedValue.WithDetail("unknown grant_type value"), w)
		return
	}

	ctx = context.WithValue(ctx, acctSubject{}, subject)
	ctx = dcontext.WithLogger(ctx, dcontext.GetLogger(ctx, acctSubject{}))

	dcontext.GetLogger(ctx).Info("authenticated client")

	ctx = context.WithValue(ctx, requestedAccess{}, requestedAccessList)
	ctx = dcontext.WithLogger(ctx, dcontext.GetLogger(ctx, requestedAccess{}))

	grantedAccessList := filterAccessList(ctx, subject, requestedAccessList)
	ctx = context.WithValue(ctx, grantedAccess{}, grantedAccessList)
	ctx = dcontext.WithLogger(ctx, dcontext.GetLogger(ctx, grantedAccess{}))

	token, err := ts.issuer.CreateJWT(subject, service, grantedAccessList)
	if err != nil {
		handleError(ctx, err, w)
		return
	}

	dcontext.GetLogger(ctx).Info("authorized client")

	response := postTokenResponse{
		Token:     token,
		ExpiresIn: int(ts.issuer.Expiration.Seconds()),
		IssuedAt:  time.Now().UTC().Format(time.RFC3339),
		Scope:     ToScopeList(grantedAccessList),
	}

	if offline {
		rToken = newRefreshToken()
		ts.refreshCache[rToken] = refreshToken{
			subject: subject,
			service: service,
		}
	}

	if rToken != "" {
		response.RefreshToken = rToken
	}

	ctx, w = dcontext.WithResponseWriter(ctx, w)

	w.Header().Set("Content-Type", "application/json")
	json.NewEncoder(w).Encode(response)

	dcontext.GetResponseLogger(ctx).Info("post token complete")
}
810343
func (cs ClientsService) GetToken(id, secret string) (string, error) {
	resp, err := newNetworkClient(cs.config).MakeRequest(network.Request{
		Method:        "POST",
		Path:          "/oauth/token",
		Authorization: network.NewBasicAuthorization(id, secret),
		Body: network.NewFormRequestBody(url.Values{
			"client_id":  []string{id},
			"grant_type": []string{"client_credentials"},
		}),
		AcceptableStatusCodes: []int{http.StatusOK},
	})
	if err != nil {
		return "", translateError(err)
	}

	var response documents.TokenResponse
	err = json.Unmarshal(resp.Body, &response)
	if err != nil {
		return "", MalformedResponseError{err}
	}

	return response.AccessToken, 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
}
895328
func (a *OAuthStrategy) AccessToken() string {
	a.mu.RLock()
	defer a.mu.RUnlock()

	return a.accessToken
}
835905
func extractToken(r *http.Request) []byte {
	// Prefer the header over form value
	sentToken := r.Header.Get(HeaderName)

	// Then POST values
	if len(sentToken) == 0 {
		sentToken = r.PostFormValue(FormFieldName)
	}

	// If all else fails, try a multipart value.
	// PostFormValue() will already have called ParseMultipartForm()
	if len(sentToken) == 0 && r.MultipartForm != nil {
		vals := r.MultipartForm.Value[FormFieldName]
		if len(vals) != 0 {
			sentToken = vals[0]
		}
	}

	return b64decode(sentToken)
}
142330
func VerifyToken(token string, r *http.Request) error {
	realToken, err := ExtractTokenFromCookie(r)
	if err != nil {
		return trace.Wrap(err, "unable to extract CSRF token from cookie")
	}

	decodedTokenA, err := decode(token)
	if err != nil {
		return trace.Wrap(err, "unable to decode CSRF token")
	}

	decodedTokenB, err := decode(realToken)
	if err != nil {
		return trace.Wrap(err, "unable to decode cookie CSRF token")
	}

	if !compareTokens(decodedTokenA, decodedTokenB) {
		return trace.BadParameter("CSRF tokens do not match")
	}

	return nil
}
1219938
func signToken(secret []byte, token *AccessToken) (string, error) {
	t := accessTokenToJwt(token)
	return t.SignedString(secret)
}
44209
func SignToken(c context.Context, signer signing.Signer, body *tokenserver.MachineTokenBody) (string, error) {
	s := tokensigning.Signer{
		Signer:         signer,
		SigningContext: tokenSigningContext,
		Encoding:       base64.RawStdEncoding,
		Wrap: func(w *tokensigning.Unwrapped) proto.Message {
			return &tokenserver.MachineTokenEnvelope{
				TokenBody: w.Body,
				RsaSha256: w.RsaSHA256Sig,
				KeyId:     w.KeyID,
			}
		},
	}
	return s.SignToken(c, body)
}
904662
func (c *UserConfig) GetToken() (string, string) {
	if c.AccessTokenKey != "" {
		return c.AccessTokenKey, c.AccessTokenSecret
	}
	if c.RequestTokenKey != "" {
		return c.RequestTokenKey, c.RequestTokenSecret
	}
	return "", ""
}
1252271
func (c *UserConfig) parseRequestToken(response *http.Response) error {
	defer response.Body.Close()
	body, err := ioutil.ReadAll(response.Body)
	if err != nil {
		return err
	}
	params, err := url.ParseQuery(string(body))
	tokenKey := params.Get("oauth_token")
	tokenSecret := params.Get("oauth_token_secret")
	if tokenKey == "" || tokenSecret == "" {
		return fmt.Errorf("No token or secret found")
	}
	c.RequestTokenKey = tokenKey
	c.RequestTokenSecret = tokenSecret
	if params.Get("oauth_callback_confirmed") == "false" {
		return fmt.Errorf("OAuth callback not confirmed")
	}
	return nil
}
1371667
func (refreshTokenResponse RefreshedTokens) AuthorizationToken() string {
	return fmt.Sprintf("%s %s", refreshTokenResponse.Type, refreshTokenResponse.AccessToken)
}
1177663
func (c *Client) AuthToken() (string, error) {
	var authToken string
	err := c.doGet("auth-token", func(r io.Reader) error {
		authTokenraw, err := ioutil.ReadAll(r)
		authToken = string(authTokenraw)
		return err
	})
	return authToken, err
}