// AccessTokenSignature indicates an expected call of AccessTokenSignature
552420
func (mr *MockCoreStrategyMockRecorder) AccessTokenSignature(arg0 interface{}) *gomock.Call {
	return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AccessTokenSignature", reflect.TypeOf((*MockCoreStrategy)(nil).AccessTokenSignature), arg0)
}
466214
func (s *SigningManager) ValidateSignature(keyringFiles []string, signedFile string, signature []byte) error {
	var signedby string
	var e error
	var checked *openpgp.Entity

	signed, err := os.Open(signedFile)
	if err != nil {
		return fmt.Errorf("%v: %v\n%v", ErrSignedFileNotFound, signedFile, err)
	}
	defer signed.Close()

	//Go through all the keyrings til either signature is valid or end of keyrings
	for _, keyringFile := range keyringFiles {
		keyringf, err := os.Open(keyringFile)
		if err != nil {
			return fmt.Errorf("%v: %v\n%v", ErrKeyringFileNotFound, keyringFile, err)
		}
		defer keyringf.Close()

		//Read both armored and unarmored keyrings
		keyring, err := openpgp.ReadArmoredKeyRing(keyringf)
		if err != nil {
			keyringf.Seek(0, 0)
			keyring, err = openpgp.ReadKeyRing(keyringf)
			if err != nil {
				return fmt.Errorf("%v: %v\n%v", ErrUnableToReadKeyring, keyringFile, err)
			}
		}

		//Check the armored detached signature
		checked, e = openpgp.CheckArmoredDetachedSignature(keyring, signed, bytes.NewReader(signature))
		if e == nil {
			for k := range checked.Identities {
				signedby = signedby + k
			}
			fmt.Printf("Signature made %v using RSA key ID %v\nGood signature from %v\n", time.Now().Format(time.RFC1123), checked.PrimaryKey.KeyIdShortString(), signedby)
			return nil
		}
		signed.Seek(0, 0)
	}
	return fmt.Errorf("%v\n%v", ErrCheckSignature, e)
}
223952
func (t AccessToken) Token() *adal.Token {
	return &adal.Token{
		AccessToken: t.AccessToken,
		Type:        t.TokenType,
	}
}
1247106
func (m *MockAuthorizeCodeStrategy) AuthorizeCodeSignature(arg0 string) string {
	ret := m.ctrl.Call(m, "AuthorizeCodeSignature", arg0)
	ret0, _ := ret[0].(string)
	return ret0
}
416020
func NewSignerToken(iss, scope string, signer Signer) *Token {
	t := NewToken(iss, scope, nil)
	t.useExternalSigner = true
	t.signer = signer
	return t
}
1028078
func (s *GetDeviceInput) SetAccessToken(v string) *GetDeviceInput {
	s.AccessToken = &v
	return s
}
718851
func (service *Service) AccessTokenHandler(w http.ResponseWriter, r *http.Request) {
	w.Header().Add("Access-Control-Allow-Origin", "*")

	err := r.ParseForm()
	if err != nil {
		log.Debug("ERROR parsing form: ", err)
		http.Error(w, http.StatusText(http.StatusBadRequest), http.StatusBadRequest)
		return
	}

	var clientID, clientSecret string
	code := r.FormValue("code")
	grantType := r.FormValue("grant_type")
	clientSecret = r.FormValue("client_secret")
	clientID = r.FormValue("client_id")

	//If clientSecret if missing from form data check if its available as basicauth
	//See https://tools.ietf.org/html/rfc6749#section-2.3.1
	if clientSecret == "" {
		var ok bool
		clientID, clientSecret, ok = r.BasicAuth()
		if !ok {
			log.Debug("clientSecret not found in form data nor basicauth")
			http.Error(w, http.StatusText(http.StatusBadRequest), http.StatusBadRequest)
			return
		}
	}

	//Also accept some alternatives
	if grantType == "authorization_code" {
		grantType = ""
	}

	if clientSecret == "" || clientID == "" || (grantType == "" && code == "") {
		log.Debug("Required parameter missing in the request")
		http.Error(w, http.StatusText(http.StatusBadRequest), http.StatusBadRequest)
		return
	}

	var at *AccessToken
	var idToken string
	httpStatusCode := http.StatusOK

	mgr := NewManager(r)
	if grantType != "" {
		if grantType == ClientCredentialsGrantCodeType {
			at, httpStatusCode = clientCredentialsTokenHandler(clientID, clientSecret, mgr, r)
		} else {
			log.Debug("Invalid grant_type")
			httpStatusCode = http.StatusBadRequest
		}
	} else {
		redirectURI := r.FormValue("redirect_uri")
		state := r.FormValue("state")
		at, httpStatusCode = convertCodeToAccessTokenHandler(code, clientID, clientSecret, redirectURI, state, mgr)

		if httpStatusCode == http.StatusOK {
			idToken, httpStatusCode = getIDTokenFromCode(code, service.jwtSigningKey, r, at, mgr)
			at.Scope = removeScope(at.Scope, scopeOpenID)
		}
	}

	if httpStatusCode != http.StatusOK {
		http.Error(w, http.StatusText(httpStatusCode), httpStatusCode)
		return
	}

	// It is also possible to immediately get a JWT by specifying 'id_token' as the response type
	// In this case, the scope parameter needs to be given to prevent consumers to accidentally handing out too powerful tokens to third party services
	// It is also possible to specify additional audiences
	responseType := r.FormValue("response_type")

	if responseType == "id_token" {
		requestedScopeParameter := r.FormValue("scope")
		extraAudiences := r.FormValue("aud")

		validity := parseValidity(r)

		var tokenString string
		tokenString, err = service.convertAccessTokenToJWT(r, at, requestedScopeParameter, extraAudiences, validity)
		if err == errUnauthorized {
			http.Error(w, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized)
			return
		}
		if err != nil {
			log.Error(err)
			http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
			return
		}

		// if client could accept JSON we give the token as JSON string
		// if not, in plain text with the application/jwt mime-type
		if strings.Index(r.Header.Get("Accept"), "application/json") >= 0 {
			w.Header().Set("Content-type", "application/json")
			json.NewEncoder(w).Encode(map[string]string{"access_token": tokenString})
		} else {
			w.Header().Set("Content-type", "application/jwt")
			w.Write([]byte(tokenString))
		}
		return
	}
	mgr.saveAccessToken(at)

	orgMgr := organization.NewManager(r)
	scope, err := verifyScopes(at.Scope, at.Username, at.ClientID, orgMgr)
	if err != nil {
		log.Error("Failed to verify token scopes: ", err)
		http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
		return
	}

	// Add grants
	grantList, err := getGrants(at.Username, clientID, r)
	if err != nil {
		log.Error("Failed to get grants: ", err)
		http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
		return
	}

	scope = strings.Join([]string{scope, strings.Join(grantList, ",")}, ",")

	response := struct {
		AccessToken string      `json:"access_token"`
		IDToken     string      `json:"id_token,omitempty"`
		TokenType   string      `json:"token_type"`
		Scope       string      `json:"scope"`
		ExpiresIn   int64       `json:"expires_in"`
		Info        interface{} `json:"info"`
	}{
		AccessToken: at.AccessToken,
		IDToken:     idToken,
		TokenType:   at.Type,
		Scope:       scope,
		ExpiresIn:   int64(at.ExpirationTime().Sub(time.Now()).Seconds() - 600),

		Info: struct {
			Username string `json:"username"`
		}{
			Username: at.Username,
		},
	}

	w.Header().Set("Content-type", "application/json")
	json.NewEncoder(w).Encode(&response)
}
1359418
func (mr *MockAuthorizeCodeStrategyMockRecorder) AuthorizeCodeSignature(arg0 interface{}) *gomock.Call {
	return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AuthorizeCodeSignature", reflect.TypeOf((*MockAuthorizeCodeStrategy)(nil).AuthorizeCodeSignature), arg0)
}
274448
func (c *Client) SetAccessToken(token string) {
	c.Headers.Set(http.CanonicalHeaderKey("Authorization"), "Bearer "+token)
}
1254534
func (s *CustomCodeSigning) SetSignature(v *CodeSigningSignature) *CustomCodeSigning {
	s.Signature = v
	return s
}
887721
func (i *Inspector) checkSignature(c context.Context, unwrapped *Unwrapped) (string, error) {
	certsBundle, err := i.Certificates.Certificates(c)
	if err != nil {
		return "", transient.Tag.Apply(err)
	}
	cert, err := certsBundle.CertificateForKey(unwrapped.KeyID)
	if err != nil {
		return fmt.Sprintf("invalid signing key - %s", err), nil
	}
	withCtx := prependSigningContext(unwrapped.Body, i.SigningContext)
	err = cert.CheckSignature(x509.SHA256WithRSA, withCtx, unwrapped.RsaSHA256Sig)
	if err != nil {
		return fmt.Sprintf("bad signature - %s", err), nil
	}
	return "", nil
}
555165
func accessTokenHash(alg jose.SignatureAlgorithm, accessToken string) (string, error) {
	newHash, ok := hashForSigAlg[alg]
	if !ok {
		return "", fmt.Errorf("unsupported signature algorithm: %s", alg)
	}

	hash := newHash()
	if _, err := io.WriteString(hash, accessToken); err != nil {
		return "", fmt.Errorf("computing hash: %v", err)
	}
	sum := hash.Sum(nil)
	return base64.RawURLEncoding.EncodeToString(sum[:len(sum)/2]), nil
}
332177
func (om *OAuth2Middleware) GetAccessToken(r *http.Request) string {

	authorizationHeader := r.Header.Get("Authorization")

	if authorizationHeader == "" {
		accessTokenQueryParameter := r.URL.Query().Get("access_token")
		return accessTokenQueryParameter
	}
	if strings.HasPrefix(authorizationHeader, "bearer ") || strings.HasPrefix(authorizationHeader, "Bearer ") {
		return ""
	}
	accessToken := strings.TrimSpace(strings.TrimPrefix(authorizationHeader, "token"))
	return accessToken
}
715347
func (ls *LocalSigner) NewSignatureHeader() (*cb.SignatureHeader, error) {
	return &cb.SignatureHeader{
		Creator: ls.Identity,
		Nonce:   ls.Nonce,
	}, nil
}
45477
func (s *BuiltinIntentMetadata) SetSignature(v string) *BuiltinIntentMetadata {
	s.Signature = &v
	return s
}
137775
func GetSignature(auth *Auth, signing string) (string, error) {
	hashFunc := getHashFunction(auth.Algorithm)
	hash := hashFunc.New()
	hash.Write([]byte(signing))

	digest := hash.Sum(nil)

	signed, err := rsa.SignPKCS1v15(rand.Reader, auth.PrivateKey.key, hashFunc, digest)
	if err != nil {
		return "", fmt.Errorf("An error occurred while signing the key: %s", err)
	}

	return base64.StdEncoding.EncodeToString(signed), nil
}
523144
func NewSignature(name string, args []Arg) (*Signature, error) {
	signatureID := uuid.New().String()
	return &Signature{
		UUID: fmt.Sprintf("task_%v", signatureID),
		Name: name,
		Args: args,
	}, nil
}