Exemple #1
0
        public void JwtTest()
        {
            // Instantiating a client
            testConfig.ApiClient = new ApiClient(testConfig.Host);
            // Adding signature as out scope.
            List <string> scopes = new List <string>
            {
                OAuth.Scope_SIGNATURE,
                OAuth.Scope_IMPERSONATION
            };

            // If this is the first time logging in - Get Consent from the user - this is a onetime step.
            // Uri oauthURI = testConfig.ApiClient.GetAuthorizationUri(testConfig.IntegratorKey, scopes, testConfig.ReturnUrl, OAuth.CODE, stateOptional);

            /////////////////////////////////////////////////////////////////////////////////////////////////////////
            // STEP 1: RequestJWTUserToken
            /////////////////////////////////////////////////////////////////////////////////////////////////////////

            byte[]           privateKeyStream = File.ReadAllBytes(testConfig.PrivateKeyFilename);
            OAuth.OAuthToken tokenInfo        = testConfig.ApiClient.RequestJWTUserToken(testConfig.IntegratorKey, testConfig.UserId, testConfig.OAuthBasePath, privateKeyStream, testConfig.ExpiresInHours);

            /////////////////////////////////////////////////////////////////////////////////////////////////////////
            // STEP 2: Get the Access Token
            /////////////////////////////////////////////////////////////////////////////////////////////////////////
            // now that the API client has an OAuth token, let's use it in all
            // DocuSign APIs
            OAuth.UserInfo userInfo = testConfig.ApiClient.GetUserInfo(tokenInfo.access_token);

            Assert.IsNotNull(userInfo);
            Assert.IsNotNull(userInfo.Accounts);

            string accountId = string.Empty;

            foreach (var item in userInfo.Accounts)
            {
                if (item.IsDefault == "true")
                {
                    testConfig.AccountId = item.AccountId;
                    testConfig.ApiClient = new ApiClient(item.BaseUri + "/restapi");
                    break;
                }
            }

            JwtRequestSignatureOnDocumentTest();
        }
Exemple #2
0
        private void attemptAuth()
        {
            byte[] keyBytes = new byte[] { };
            try
            {
                keyBytes = File.ReadAllBytes(privateKeyBox.Text);
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error: " + ex.Message, "Key read failed", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            try
            {
                apiClient  = new ApiClient(host);
                oAuthToken = apiClient.RequestJWTUserToken(iKeyBox.Text, userIdTextbox.Text, oauthBasePath, keyBytes, 1);
            }
            catch (Exception ex)
            {
                if (MessageBox.Show("Click OK if this is a consent error and you would like to copy your consent url: " + ex.Message, "Token Request failed", MessageBoxButtons.OKCancel) == DialogResult.OK)
                {
                    List <string> scopes = new List <string>();
                    scopes.Add("Signature");
                    scopes.Add("Impersonation");
                    string redirectURI = "https://www.example.com";
                    Uri    authUri     = apiClient.GetAuthorizationUri(integratorKey, scopes, redirectURI, "code");
                    Clipboard.SetText(authUri.ToString());
                } //Consent IF
            }     // token request exception
            OAuth.UserInfo userInfo = apiClient.GetUserInfo(oAuthToken.access_token);
            foreach (var item in userInfo.Accounts)
            {
                if (item.IsDefault == "true")
                {
                    accountId  = item.AccountId;
                    apiClient  = new ApiClient(item.BaseUri + "/restapi");
                    baseUri    = item.BaseUri + @"/restapi";
                    authorized = true;
                    break;
                }
            }
            authStatusLabel.Text = authorized.ToString();
            envelopesApi         = new EnvelopesApi(apiClient.Configuration);
        }
Exemple #3
0
        public void PostToken()
        {
            ApiClient apiClient = new ApiClient(RestApiUrl);

            DocuSign.eSign.Client.Configuration.Default.ApiClient = apiClient;
            //HttpContext httpContext = HttpContext.Current;
            // var request = HttpContext.Current.Request;
            //var v =   request.Cookies.Get("AcessToken").Value;
            // var v = request.Cookies["AccessToken"].Value;
            // var v = WebOperationContext.Current.IncomingRequest.Headers[HttpRequestHeader.Cookie];


            var vT = AccessToken;

            //HttpContext.Current.Response.Headers.Add("Authorization", vT);
            ACCESS_TOKEN = apiClient.GetOAuthToken(client_id, client_secret, true, vT);

            OAuth.UserInfo userInfo = apiClient.GetUserInfo(ACCESS_TOKEN);
            Console.WriteLine("Access_token: " + ACCESS_TOKEN);
        }
        public (ClaimsPrincipal, AuthenticationProperties) AuthenticateFromJwt()
        {
            OAuth.OAuthToken authToken = _apiClient.RequestJWTUserToken(
                _configurationService["DocuSign:IntegrationKey"],
                _configurationService["DocuSign:UserId"],
                _configurationService["DocuSign:AuthServer"],
                File.ReadAllBytes(_configurationService["DocuSign:RSAPrivateKeyFile"]),
                int.Parse(_configurationService["DocuSign:JWTLifeTime"]),
                new List <string> {
                "click.manage", "signature"
            });


            OAuth.UserInfo userInfo = _apiClient.GetUserInfo(authToken.access_token);
            var            claims   = new List <Claim>
            {
                new Claim("access_token", authToken.access_token),
                new Claim(ClaimTypes.NameIdentifier, userInfo.Sub),
                new Claim(ClaimTypes.Name, userInfo.Name),
                new Claim("account_id", userInfo.Accounts.First(x => x.IsDefault == "true").AccountId),
                new Claim("authType", LoginType.JWT.ToString()),
            };

            foreach (var account in userInfo.Accounts)
            {
                claims.Add(new Claim("accounts", JsonConvert.SerializeObject(account)));
            }

            var claimsIdentity = new ClaimsIdentity(
                claims,
                CookieAuthenticationDefaults.AuthenticationScheme);

            var authProperties = new AuthenticationProperties
            {
                AllowRefresh = true,
                ExpiresUtc   = DateTimeOffset.Now.AddDays(1),
                IsPersistent = true,
            };

            return(new ClaimsPrincipal(claimsIdentity), authProperties);
        }
Exemple #5
0
        private Account GetAccountInfo(OAuth.OAuthToken authToken)
        {
            OAuth.UserInfo userInfo = ApiClient.GetUserInfo(authToken.access_token);
            Account        acct     = null;

            var accounts = userInfo.GetAccounts();

            if (!string.IsNullOrEmpty(DSConfig.TargetAccountID) && !DSConfig.TargetAccountID.Equals("FALSE"))
            {
                acct = accounts.FirstOrDefault(a => a.AccountId() == DSConfig.TargetAccountID);

                if (acct == null)
                {
                    throw new Exception("The user does not have access to account " + DSConfig.TargetAccountID);
                }
            }
            else
            {
                acct = accounts.FirstOrDefault(a => a.GetIsDefault() == "true");
            }

            return(acct);
        }
Exemple #6
0
        public string GetUserIfo()
        {
            ApiClient apiClient = new ApiClient(RestApiUrl);

            DocuSign.eSign.Client.Configuration.Default.ApiClient = apiClient;

            OAuth.UserInfo userInfo = apiClient.GetUserInfo(ACCESS_TOKEN);

            string accountId = string.Empty;

            // find default account (if multiple present)
            foreach (var item in userInfo.GetAccounts())
            {
                if (item.GetIsDefault() == "true")
                {
                    accountId = item.AccountId();
                    apiClient = new ApiClient(item.GetBaseUri() + "/restapi");
                    break;
                }
            }

            return(accountId);
        }
        public static void RequestJWTUserToken_CorrectInputParameters_ReturnsOAuthToken(ref TestConfig testConfig)
        {
            testConfig.ApiClient = new ApiClient(testConfig.Host);

            Assert.IsNotNull(testConfig?.PrivateKey);

            byte[] privateKeyStream = testConfig.PrivateKey;

            var scopes = new List <string> {
                OAuth.Scope_SIGNATURE, OAuth.Scope_IMPERSONATION
            };

            OAuth.OAuthToken tokenInfo = testConfig.ApiClient.RequestJWTUserToken(
                testConfig.IntegratorKey,
                testConfig.UserId,
                testConfig.OAuthBasePath,
                privateKeyStream,
                testConfig.ExpiresInHours,
                scopes);

            OAuth.UserInfo userInfo = testConfig.ApiClient.GetUserInfo(tokenInfo.access_token);

            Assert.IsNotNull(userInfo?.Accounts);

            foreach (OAuth.UserInfo.Account item in userInfo.Accounts)
            {
                if (item.IsDefault == "true")
                {
                    testConfig.AccountId = item.AccountId;
                    testConfig.ApiClient.SetBasePath(item.BaseUri + "/restapi");
                    break;
                }
            }

            Assert.IsNotNull(testConfig?.AccountId);
            CreateEnvelopeMethod.CreateEnvelope_CorrectAccountIdAndEnvelopeDefinition_ReturnEnvelopeSummary(ref testConfig);
        }
        public void JwtLoginTest()
        {
            testConfig.ApiClient = new ApiClient(testConfig.Host);

            Assert.IsNotNull(testConfig.PrivateKey);

            byte[] privateKeyStream = Convert.FromBase64String(testConfig.PrivateKey);

            var scopes = new List <string>();

            scopes.Add("dtr.company.write");
            scopes.Add("dtr.company.read");
            scopes.Add("dtr.rooms.write");
            scopes.Add("dtr.rooms.read");
            scopes.Add("signature");
            scopes.Add("impersonation");

            OAuth.OAuthToken tokenInfo = testConfig.ApiClient.RequestJWTUserToken(testConfig.IntegratorKey, testConfig.UserId, testConfig.OAuthBasePath, privateKeyStream, testConfig.ExpiresInHours, scopes);

            // the authentication api uses the apiClient (and X-DocuSign-Authentication header) that are set in Configuration object
            OAuth.UserInfo userInfo = testConfig.ApiClient.GetUserInfo(tokenInfo.access_token);

            Assert.IsNotNull(userInfo);
            Assert.IsNotNull(userInfo.Accounts);

            foreach (var item in userInfo.Accounts)
            {
                if (item.IsDefault == "true")
                {
                    testConfig.AccountId = item.AccountId;
                    //testConfig.ApiClient.SetBasePath(item.BaseUri + "/restapi");
                    break;
                }
            }

            Assert.IsNotNull(testConfig.AccountId);
        }
Exemple #9
0
        /// <summary>
        /// Get User Info method takes the accessToken to retrieve User Account Data.
        /// </summary>
        /// <param name="accessToken"></param>
        /// <returns>The User Info model.</returns>
        public OAuth.UserInfo GetUserInfo(string accessToken)
        {
            if (string.IsNullOrEmpty(accessToken))
            {
                throw new ArgumentException("Cannot find a valid access token. Make sure OAuth is configured before you try again.");
            }

            string baseUri = string.Format("https://{0}/", GetOAuthBasePath());

            RestClient restClient = new RestClient(baseUri);

            restClient.Timeout   = Configuration.Timeout;
            restClient.UserAgent = Configuration.UserAgent;
            restClient.Proxy     = Proxy;

            RestRequest request = new RestRequest("oauth/userinfo", Method.GET);

            request.AddHeader("Authorization", "Bearer " + accessToken);
            // Don't cache authentication requests
            request.AddHeader("Cache-Control", "no-store");
            request.AddHeader("Pragma", "no-cache");

            IRestResponse response = restClient.Execute(request);

            if (response.StatusCode >= HttpStatusCode.OK && response.StatusCode < HttpStatusCode.BadRequest)
            {
                OAuth.UserInfo userInfo = JsonConvert.DeserializeObject <OAuth.UserInfo>(response.Content);
                return(userInfo);
            }
            else
            {
                throw new ApiException((int)response.StatusCode,
                                       "Error while requesting server, received a non successful HTTP code "
                                       + response.ResponseStatus + " with response Body: " + response.Content, response.Content);
            }
        }
Exemple #10
0
        public void AuthenticateWithJWT()
        {
            ApiClient apiClient  = new ApiClient();
            string    ik         = ConfigurationManager.AppSettings["IntegrationKey"];
            string    userId     = ConfigurationManager.AppSettings["userId"];
            string    authServer = ConfigurationManager.AppSettings["AuthServer"];
            string    rsaKey     = ConfigurationManager.AppSettings["RSAKey"];

            OAuth.OAuthToken authToken = apiClient.RequestJWTUserToken(ik, userId, authServer, Encoding.UTF8.GetBytes(File.ReadAllText(Server.MapPath("private.key"))), 1);

            apiClient.SetOAuthBasePath(authServer);
            OAuth.UserInfo userInfo = apiClient.GetUserInfo(authToken.access_token);
            Account        acct     = null;

            var accounts = userInfo.Accounts;

            {
                acct = accounts.FirstOrDefault(a => a.IsDefault == "true");
            }
            accountId   = acct.AccountId;
            baseUri     = acct.BaseUri + "/restapi";
            accessToken = authToken.access_token;
            return;
        }
Exemple #11
0
        protected void Button1_Click(object sender, EventArgs e)
        {
            string serverpath     = Server.MapPath(".");
            string signerClientId = "1000";

            StreamReader sr = new StreamReader(serverpath + @"\privatekey2.txt");

            DS_PRIVATE_KEY = sr.ReadToEnd();
            sr.Close();

            ApiClient APClient = new ApiClient();

            OAuth.OAuthToken authToken = APClient.RequestJWTUserToken(DS_CLIENT_ID,
                                                                      DS_IMPERSONATED_USER_GUID,
                                                                      DS_AUTH_SERVER,
                                                                      Encoding.UTF8.GetBytes(DS_PRIVATE_KEY),
                                                                      1);

            AccessToken = authToken.access_token;

            APClient.SetOAuthBasePath(DS_AUTH_SERVER);
            OAuth.UserInfo UserInfoGet = APClient.GetUserInfo(authToken.access_token);

            AccountIDVar = UserInfoGet.Accounts[0].AccountId;
            APClient     = new ApiClient(UserInfoGet.Accounts[0].BaseUri + "/restapi");
            APClient.Configuration.AccessToken = AccessToken;

            TemplatesApi tempAPI  = new TemplatesApi(APClient.Configuration);
            var          template = tempAPI.ListTemplates(AccountIDVar).EnvelopeTemplates.First(x => x.Name == "Steady Property");

            Text LblTxtName = new Text
            {
                TabLabel = "TxtName",
                Value    = TxtName.Text
            };

            Text LblTxtEmail = new Text
            {
                TabLabel = "TxtEmail",
                Value    = TxtEmail.Text
            };

            Text LblTxtDOB = new Text
            {
                TabLabel = "TxtDOB",
                Value    = TxtDOB.Text
            };

            string GenderValue = "";

            GenderValue = RbMale.Checked ? "Male" : "Female";

            Text LblTxtGender = new Text
            {
                TabLabel = "TxtGender",
                Value    = GenderValue
            };

            Text LblTxtPhone = new Text
            {
                TabLabel = "TxtPhone",
                Value    = TxtPhone.Text
            };

            Text LblTxtAddress = new Text
            {
                TabLabel = "TxtAddress",
                Value    = TxtAddress.Text
            };

            Text LblTxtMember = new Text
            {
                TabLabel = "TxtMember",
                Value    = DropMember.Text
            };

            Tabs tabs = new Tabs
            {
                TextTabs = new List <Text> {
                    LblTxtName, LblTxtEmail, LblTxtDOB, LblTxtGender, LblTxtPhone, LblTxtAddress, LblTxtMember
                }
            };

            TemplateRole signer = new TemplateRole
            {
                Email             = TxtEmail.Text,
                Name              = TxtName.Text,
                RoleName          = "Signer1",
                ClientUserId      = signerClientId,
                EmailNotification = new RecipientEmailNotification
                {
                    EmailSubject = "Please sign the membership form",
                    EmailBody    = "Dear " + TxtName.Text + @", <br><br>Please sign the membership form and we will process your application form." +
                                   @"<br>You will recieve email confirmation within 48 hours<br><br>Thank you <br>Steady Property"
                },
                Tabs = tabs                 //Set tab values
            };

            TemplateRole cc = new TemplateRole
            {
                Email             = TxtEmail.Text,
                Name              = TxtName.Text,
                EmailNotification = new RecipientEmailNotification
                {
                    EmailSubject = "Membership registation completed",
                    EmailBody    = "Dear " + TxtName.Text + @", <br><br>We will process your application form." +
                                   @"<br>You will recieve email confirmation within 48 hours<br><br>Thank you <br>Steady Property"
                },
                RoleName = "cc"
            };

            TemplateRole radmin = new TemplateRole
            {
                Email             = "*****@*****.**",
                Name              = "Harry Tim",
                EmailNotification = new RecipientEmailNotification
                {
                    EmailSubject = "New member registraion notification",
                    EmailBody    = "Dear Admin, <br><br>New membership registration for : " + TxtName.Text +
                                   @"<br>Please process it within 48 hours<br><br>Thank you <br>Steady Property"
                },
                RoleName = "admin"
            };

            EnvelopeDefinition envelopeAttributes = new EnvelopeDefinition
            {
                TemplateId    = "5aa70f7a-7a21-496b-9f24-ada8431cf93b",
                Status        = "Sent",
                TemplateRoles = new List <TemplateRole> {
                    signer, cc, radmin
                }
            };

            EnvelopesApi    envelopesApi = new EnvelopesApi(APClient.Configuration);
            EnvelopeSummary results      = envelopesApi.CreateEnvelope(AccountIDVar, envelopeAttributes);

            RecipientViewRequest viewRequest = new RecipientViewRequest();

            viewRequest.ReturnUrl = "https://localhost:44387/Confirm.aspx" + "?envelopeid=" + results.EnvelopeId;

            viewRequest.AuthenticationMethod = "none";

            viewRequest.Email        = TxtEmail.Text;
            viewRequest.UserName     = TxtName.Text;
            viewRequest.ClientUserId = signerClientId;

            viewRequest.PingFrequency = "600";             // seconds
            // NOTE: The pings will only be sent if the pingUrl is an HTTPS address
            viewRequest.PingUrl = "https://localhost";     // Optional setting

            ViewUrl results1 = envelopesApi.CreateRecipientView(AccountIDVar, results.EnvelopeId, viewRequest);

            Response.Redirect(results1.Url);
        }
    protected void SignIt_OnWeb(object sender, EventArgs e)
    {
        bool isError = false;

        try
        {
            string userId         = "aa621eb5-e488-4135-9698-613136bce319"; // use your userId (guid), not email address
            string oauthBasePath  = "account-d.docusign.com";
            string integratorKey  = "ad00790f-c0c8-49d8-a621-904549bc9d88";
            string privateKeyFile = Server.MapPath(@"~/App_Data/DocuSign_PrivateKey.pem");
            string privateKey     = System.IO.File.ReadAllText(privateKeyFile);

            int    expiresInHours = 1;
            string host           = "https://demo.docusign.net/restapi";

            string accountId = string.Empty;

            ApiClient        apiClient = new ApiClient(host);
            OAuth.OAuthToken tokenInfo = apiClient.ConfigureJwtAuthorizationFlowByKey(integratorKey, userId, oauthBasePath, privateKey, expiresInHours);

            /////////////////////////////////////////////////////////////////
            // STEP 1: Get User Info
            // now that the API client has an OAuth token, let's use it in all// DocuSign APIs
            /////////////////////////////////////////////////////////////////

            OAuth.UserInfo userInfo = apiClient.GetUserInfo(tokenInfo.access_token);

            foreach (var item in userInfo.GetAccounts())
            {
                if (item.GetIsDefault() == "true")
                {
                    accountId = item.AccountId();
                    apiClient = new ApiClient(item.GetBaseUri() + "/restapi");
                    break;
                }
            }

            // New Code

            // Read a file from disk to use as a document.
            string pdfToSign = Server.MapPath(@"~/Application/Uploads/CONFIRMATION PAGE.pdf");
            byte[] fileBytes = System.IO.File.ReadAllBytes(pdfToSign);

            EnvelopeDefinition envDef = new EnvelopeDefinition();
            envDef.EmailSubject = "[DocuSign C# SDK] - Please sign this doc";

            // Add a document to the envelope
            Document doc = new Document();
            doc.DocumentBase64 = System.Convert.ToBase64String(fileBytes);
            doc.Name           = "PROGRAM GUIDE & CONFIRMATION PAGE.pdf";
            doc.DocumentId     = "1";

            envDef.Documents = new List <Document>();
            envDef.Documents.Add(doc);

            // Add a recipient to sign the documeent
            Signer signer = new Signer();
            signer.Email        = "*****@*****.**";
            signer.Name         = "Noel Ciambotti";
            signer.RecipientId  = "1";
            signer.ClientUserId = "1002";

            // Create a |SignHere| tab somewhere on the document for the recipient to sign
            signer.Tabs = new Tabs();
            signer.Tabs.SignHereTabs = new List <SignHere>();
            SignHere signHere = new SignHere();
            signHere.DocumentId  = "1";
            signHere.PageNumber  = "1";
            signHere.RecipientId = "1";
            signHere.XPosition   = "37";
            signHere.YPosition   = "666";
            signer.Tabs.SignHereTabs.Add(signHere);

            envDef.Recipients         = new Recipients();
            envDef.Recipients.Signers = new List <Signer>();
            envDef.Recipients.Signers.Add(signer);

            // set envelope status to "sent" to immediately send the signature request
            envDef.Status = "sent";

            // |EnvelopesApi| contains methods related to creating and sending Envelopes (aka signature requests)
            // EnvelopesApi envelopesApi = new EnvelopesApi();
            EnvelopesApi    envelopesApi    = new EnvelopesApi(apiClient.Configuration);
            EnvelopeSummary envelopeSummary = envelopesApi.CreateEnvelope(accountId, envDef);

            // print the JSON response
            lblEnvelopeId.Text = envelopeSummary.EnvelopeId;
            lblEnvelope.Text   = "EnvelopeSummary:<br />" + Newtonsoft.Json.JsonConvert.SerializeObject(envelopeSummary);
            //Console.WriteLine("EnvelopeSummary:\n" + Newtonsoft.Json.JsonConvert.SerializeObject(envelopeSummary));
            lblEnvelope.Text += "<br />" + envelopeSummary.EnvelopeId;
            lblEnvelope.Text += "<br />" + envelopeSummary.Status;
            lblEnvelope.Text += "<br />" + envelopeSummary.StatusDateTime;
            lblEnvelope.Text += "<br />" + envelopeSummary.Uri;
        }
        catch (Exception ex)
        {
            isError = true;
            string errMsg = "Sign Test";
            lblError.Text += String.Format("<hr /><table class='table_error'>"
                                           + "<tr><td>Error<td/><td>{0}</td></tr>"
                                           + "<tr><td>Message<td/><td>{1}</td></tr>"
                                           + "<tr><td>StackTrace<td/><td>{2}</td></tr>"
                                           + "<tr><td>Source<td/><td>{3}</td></tr>"
                                           + "<tr><td>InnerException<td/><td>{4}</td></tr>"
                                           + "<tr><td>Data<td/><td>{5}</td></tr>"
                                           + "</table>"
                                           , errMsg            //0
                                           , ex.Message        //1
                                           , ex.StackTrace     //2
                                           , ex.Source         //3
                                           , ex.InnerException //4
                                           , ex.Data           //5
                                           , ex.HelpLink
                                           , ex.TargetSite
                                           );
        }

        if (!isError)
        {
            // In DeBug - We comment out so we can do multiple steps
            SignIt_OnWeb_View(sender, e);
        }
    }
    protected void SignIt_OnWeb_View(object sender, EventArgs e)
    {
        try
        {
            string userId         = "aa621eb5-e488-4135-9698-613136bce319"; // use your userId (guid), not email address
            string oauthBasePath  = "account-d.docusign.com";
            string integratorKey  = "ad00790f-c0c8-49d8-a621-904549bc9d88";
            string privateKeyFile = Server.MapPath(@"~/App_Data/DocuSign_PrivateKey.pem");
            string privateKey     = System.IO.File.ReadAllText(privateKeyFile);

            int    expiresInHours = 1;
            string host           = "https://demo.docusign.net/restapi";

            string accountId = string.Empty;

            ApiClient        apiClient = new ApiClient(host);
            OAuth.OAuthToken tokenInfo = apiClient.ConfigureJwtAuthorizationFlowByKey(integratorKey, userId, oauthBasePath, privateKey, expiresInHours);

            /////////////////////////////////////////////////////////////////
            // STEP 1: Get User Info
            // now that the API client has an OAuth token, let's use it in all// DocuSign APIs
            /////////////////////////////////////////////////////////////////

            OAuth.UserInfo userInfo = apiClient.GetUserInfo(tokenInfo.access_token);

            foreach (var item in userInfo.GetAccounts())
            {
                if (item.GetIsDefault() == "true")
                {
                    accountId = item.AccountId();
                    apiClient = new ApiClient(item.GetBaseUri() + "/restapi");
                    break;
                }
            }

            // New Code
            RecipientViewRequest viewOptions = new RecipientViewRequest()
            {
                ReturnUrl            = "https://application.cardgroupintl.com/Application/SignTest",
                ClientUserId         = "1002", // must match clientUserId of the embedded recipient
                AuthenticationMethod = "email",
                UserName             = "******",
                Email = "*****@*****.**"
            };

            string envelopeId = lblEnvelopeId.Text;
            // instantiate an envelopesApi object
            //EnvelopesApi envelopesApi = new EnvelopesApi();
            EnvelopesApi envelopesApi = new EnvelopesApi(apiClient.Configuration);
            // create the recipient view (aka signing URL)
            ViewUrl recipientView = envelopesApi.CreateRecipientView(accountId, envelopeId, viewOptions);

            // print the JSON response
            //Console.WriteLine("ViewUrl:\n{0}", Newtonsoft.Json.JsonConvert.SerializeObject(recipientView));
            //Trace.WriteLine("ViewUrl:\n{0}", JsonConvert.SerializeObject(recipientView));

            lblView.Text  = "ViewUrl:<br />" + Newtonsoft.Json.JsonConvert.SerializeObject(recipientView);
            lblView.Text += "<br />" + recipientView.Url;

            HyperLink1.NavigateUrl = recipientView.Url;

            // Start the embedded signing session
            // System.Diagnostics.Process.Start(recipientView.Url);

            // In DeBug - We comment out so we can do multiple steps
            Response.Redirect(recipientView.Url);
        }
        catch (Exception ex)
        {
            string errMsg = "Sign Test View";
            lblError.Text += String.Format("<hr /><table class='table_error'>"
                                           + "<tr><td>Error<td/><td>{0}</td></tr>"
                                           + "<tr><td>Message<td/><td>{1}</td></tr>"
                                           + "<tr><td>StackTrace<td/><td>{2}</td></tr>"
                                           + "<tr><td>Source<td/><td>{3}</td></tr>"
                                           + "<tr><td>InnerException<td/><td>{4}</td></tr>"
                                           + "<tr><td>Data<td/><td>{5}</td></tr>"
                                           + "</table>"
                                           , errMsg            //0
                                           , ex.Message        //1
                                           , ex.StackTrace     //2
                                           , ex.Source         //3
                                           , ex.InnerException //4
                                           , ex.Data           //5
                                           , ex.HelpLink
                                           , ex.TargetSite
                                           );
        }
    }
    //static void Main(string[] args)
    protected void SignIt(object sender, EventArgs e)
    {
        string userId         = "aa621eb5-e488-4135-9698-613136bce319"; // use your userId (guid), not email address
        string oauthBasePath  = "account-d.docusign.com";
        string integratorKey  = "ad00790f-c0c8-49d8-a621-904549bc9d88";
        string privateKeyFile = Server.MapPath(@"~/App_Data/DocuSign_PrivateKey.pem");
        string privateKey     = System.IO.File.ReadAllText(privateKeyFile);

        int    expiresInHours = 1;
        string host           = "https://demo.docusign.net/restapi";

        string accountId = string.Empty;

        ApiClient apiClient = new ApiClient(host);

        OAuth.OAuthToken tokenInfo = apiClient.ConfigureJwtAuthorizationFlowByKey(integratorKey, userId, oauthBasePath, privateKey, expiresInHours);

        /////////////////////////////////////////////////////////////////
        // STEP 1: Get User Info
        // now that the API client has an OAuth token, let's use it in all// DocuSign APIs
        /////////////////////////////////////////////////////////////////

        OAuth.UserInfo userInfo = apiClient.GetUserInfo(tokenInfo.access_token);

        foreach (var item in userInfo.GetAccounts())
        {
            if (item.GetIsDefault() == "true")
            {
                accountId = item.AccountId();
                apiClient = new ApiClient(item.GetBaseUri() + "/restapi");
                break;
            }
        }

        /////////////////////////////////////////////////////////////////
        // STEP 2: CREATE ENVELOPE API
        /////////////////////////////////////////////////////////////////

        EnvelopeDefinition envDef = new EnvelopeDefinition();

        envDef.EmailSubject = "[DocuSign C# SDK] - Please sign this doc";

        // assign recipient to template role by setting name, email, and role name.  Note that the
        // template role name must match the placeholder role name saved in your account template.
        TemplateRole tRole = new TemplateRole();

        tRole.Email    = "[SIGNER_EMAIL]";
        tRole.Name     = "[SIGNER_NAME]";
        tRole.RoleName = "[ROLE_NAME]";
        List <TemplateRole> rolesList = new List <TemplateRole>()
        {
            tRole
        };

        // add the role to the envelope and assign valid templateId from your account
        envDef.TemplateRoles = rolesList;
        envDef.TemplateId    = "[TEMPLATE_ID]";

        // set envelope status to "sent" to immediately send the signature request
        envDef.Status = "sent";

        // |EnvelopesApi| contains methods related to creating and sending Envelopes (aka signature requests)
        EnvelopesApi    envelopesApi    = new EnvelopesApi(apiClient.Configuration);
        EnvelopeSummary envelopeSummary = envelopesApi.CreateEnvelope(accountId, envDef);
    }
        /// <summary>
        /// Uses Json Web Token (JWT) Authentication Method to obtain the necessary information needed to make API calls.
        /// </summary>
        /// <returns>A tuple containing the accessToken, accountId and baseUri</returns>
        public static (string, string, string) AuthenticateWithJWT()
        {
            var    apiClient        = new ApiClient();
            string ik               = ConfigurationManager.AppSettings["IntegrationKey"];
            string userId           = ConfigurationManager.AppSettings["userId"];
            string authServer       = ConfigurationManager.AppSettings["AuthServer"];
            string rsaKeyFilePath   = ConfigurationManager.AppSettings["KeyFilePath"];
            string selectedApiTypes = ConfigurationManager.AppSettings["SelectedApiTypes"];

            List <string> scopes = new List <string>
            {
                "signature",
                "impersonation"
            };

            if (selectedApiTypes.Contains("Rooms"))
            {
                scopes.AddRange(new List <string>
                {
                    "dtr.rooms.read",
                    "dtr.rooms.write",
                    "dtr.documents.read",
                    "dtr.documents.write",
                    "dtr.profile.read",
                    "dtr.profile.write",
                    "dtr.company.read",
                    "dtr.company.write",
                    "room_forms"
                });
            }
            if (selectedApiTypes.Contains("Click"))
            {
                scopes.AddRange(new List <string>
                {
                    "click.manage",
                    "click.send"
                });
            }

            OAuth.OAuthToken authToken = apiClient.RequestJWTUserToken(ik,
                                                                       userId,
                                                                       authServer,
                                                                       File.ReadAllBytes(rsaKeyFilePath),
                                                                       1,
                                                                       scopes);

            string accessToken = authToken.access_token;

            apiClient.SetOAuthBasePath(authServer);
            OAuth.UserInfo userInfo = apiClient.GetUserInfo(authToken.access_token);
            Account        acct     = null;

            var accounts = userInfo.Accounts;
            {
                acct = accounts.FirstOrDefault(a => a.IsDefault == "true");
            }
            string accountId = acct.AccountId;
            string baseUri   = acct.BaseUri + "/restapi";

            return(accessToken, accountId, baseUri);
        }
        public (ClaimsPrincipal, AuthenticationProperties) AuthenticateFromJwt()
        {
            OAuth.OAuthToken authToken;
            try
            {
                authToken = _apiClient.RequestJWTUserToken(
                    _configuration["DocuSign:IntegrationKey"],
                    _configuration["DocuSign:UserId"],
                    _configuration["DocuSign:AuthServer"],
                    File.ReadAllBytes(_configuration["DocuSign:RSAPrivateKeyFile"]),
                    int.Parse(_configuration["DocuSign:JWTLifeTime"]),
                    new List <string>
                {
                    "click.manage",
                    "signature",
                    "impersonation"
                });
            }
            catch (ApiException e)
            {
                ApiExceptionContent error = JsonConvert.DeserializeObject <ApiExceptionContent>(
                    e.ErrorContent);
                if (error.Error == "consent_required")
                {
                    throw new ConsentRequiredException();
                }

                throw;
            }

            OAuth.UserInfo userInfo = _apiClient.GetUserInfo(authToken.access_token);
            var            claims   = new List <Claim>
            {
                new Claim("access_token", authToken.access_token),
                new Claim(ClaimTypes.NameIdentifier, userInfo.Sub),
                new Claim(ClaimTypes.Name, userInfo.Name),
                new Claim("account_id", userInfo.Accounts.First(x => x.IsDefault == "true").AccountId)
            };

            foreach (OAuth.UserInfo.Account account in userInfo.Accounts)
            {
                claims.Add(new Claim("accounts", JsonConvert.SerializeObject(account)));
            }

            var claimsIdentity = new ClaimsIdentity(
                claims,
                CookieAuthenticationDefaults.AuthenticationScheme);

            var authProperties = new AuthenticationProperties
            {
                AllowRefresh = true,
                ExpiresUtc   =
                    DateTimeOffset.UtcNow + (authToken.expires_in.HasValue
                        ? TimeSpan.FromSeconds(authToken.expires_in.Value)
                        : TimeSpan.FromHours(int.Parse(_configuration["DocuSign:JWTLifeTime"])))
                    - TimeSpan.FromMinutes(1),
                IsPersistent = true
            };

            return(new ClaimsPrincipal(claimsIdentity), authProperties);
        }