Exemplo n.º 1
0
        private Account GetAccountInfo(OAuth.OAuthToken authToken)
        {
            ApiClient.SetOAuthBasePath(DSConfig.AuthServer);
            OAuth.UserInfo userInfo = ApiClient.GetUserInfo(authToken.access_token);
            Account        acct     = null;

            var accounts = userInfo.Accounts;

            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.IsDefault == "true");
            }

            return(acct);
        }
Exemplo n.º 2
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;
        }
 /**
 * construct OAuth object
 */
 public EchoOAuth(string consumer_key, string consumer_secret, string oauth_token, string oauth_token_secret)
 {
     this.SignatureType = OAuth.SignatureTypes.HMACSHA1;
     this.consumer = new OAuth.OAuthConsumer(consumer_key, consumer_secret);
     if (!string.IsNullOrEmpty(oauth_token) && !string.IsNullOrEmpty(oauth_token_secret))
     {
         this.token = new OAuth.OAuthToken(oauth_token, oauth_token_secret);
     }
     else
     {
         this.token = null;
     }
 }
Exemplo n.º 4
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);
        }
Exemplo n.º 5
0
 /// <summary>
 /// Initializes a new instance of an object.
 /// </summary>
 public UserApiAuthorization()
 {
     GoogleAnalytics = new OAuth.OAuthToken();
 }
Exemplo n.º 6
0
        /// <summary>
        /// *RESERVED FOR PARTNERS* Request JWT Application Token
        /// </summary>
        /// <param name="clientId">DocuSign OAuth Client Id(AKA Integrator Key)</param>
        /// <param name="oauthBasePath"> DocuSign OAuth base path
        /// <see cref="OAuth.Demo_OAuth_BasePath"/> <see cref="OAuth.Production_OAuth_BasePath"/> <see cref="OAuth.Stage_OAuth_BasePath"/>
        /// <seealso cref="GetOAuthBasePath()" /> <seealso cref="SetOAuthBasePath(string)"/>
        /// </param>
        /// <param name="privateKeyBytes">The byte contents of the RSA private key</param>
        /// <param name="expiresInHours">Number of hours remaining before the JWT assertion is considered as invalid</param>
        /// <param name="scopes">Optional. The list of requested scopes may include (but not limited to) You can also pass any advanced scope.
        /// <see cref="OAuth.Scope_SIGNATURE"/> <see cref="OAuth.Scope_IMPERSONATION"/> <see cref="OAuth.Scope_EXTENDED"/>
        /// </param>
        /// <returns>The JWT application token</returns>
        public OAuth.OAuthToken RequestJWTApplicationToken(string clientId, string oauthBasePath, byte[] privateKeyBytes, int expiresInHours, List <string> scopes = null)
        {
            string privateKey = Encoding.UTF8.GetString(privateKeyBytes);

            JwtSecurityTokenHandler handler = new JwtSecurityTokenHandler();

            SecurityTokenDescriptor descriptor = new SecurityTokenDescriptor()
            {
                Expires = DateTime.UtcNow.AddHours(expiresInHours),
            };

            if (scopes == null)
            {
                scopes = new List <string>
                {
                    OAuth.Scope_SIGNATURE
                };
            }

            descriptor.Subject = new ClaimsIdentity();
            descriptor.Subject.AddClaim(new Claim("scope", String.Join(" ", scopes)));
            descriptor.Subject.AddClaim(new Claim("aud", oauthBasePath));
            descriptor.Subject.AddClaim(new Claim("iss", clientId));

            if (!string.IsNullOrEmpty(privateKey))
            {
                var            rsa    = CreateRSAKeyFromPem(privateKey);
                RsaSecurityKey rsaKey = new RsaSecurityKey(rsa);
                descriptor.SigningCredentials = new SigningCredentials(rsaKey, SecurityAlgorithms.RsaSha256Signature);
            }
            else
            {
                throw new ApiException(400, "Private key not supplied or is invalid!");
            }

            var    token    = handler.CreateToken(descriptor);
            string jwtToken = handler.WriteToken(token);

            string     baseUri    = string.Format("https://{0}/", oauthBasePath);
            RestClient restClient = new RestClient(baseUri);

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

            string path        = "oauth/token";
            string contentType = "application/x-www-form-urlencoded";

            Dictionary <string, string> formParams = new Dictionary <string, string>();

            formParams.Add("grant_type", OAuth.Grant_Type_JWT);
            formParams.Add("assertion", jwtToken);

            Dictionary <string, string> queryParams = new Dictionary <string, string>();

            Dictionary <string, string> headerParams = new Dictionary <string, string>();

            headerParams.Add("Content-Type", "application/x-www-form-urlencoded");
            // Don't cache authentication requests
            headerParams.Add("Cache-Control", "no-store");
            headerParams.Add("Pragma", "no-cache");

            Dictionary <string, FileParameter> fileParams = new Dictionary <string, FileParameter>();
            Dictionary <string, string>        pathParams = new Dictionary <string, string>();

            object postBody = null;

            RestRequest request = PrepareRequest(path, Method.POST, queryParams, postBody, headerParams, formParams, fileParams, pathParams, contentType);

            IRestResponse response = restClient.Execute(request);

            if (response.StatusCode >= HttpStatusCode.OK && response.StatusCode < HttpStatusCode.BadRequest)
            {
                OAuth.OAuthToken tokenInfo = JsonConvert.DeserializeObject <OAuth.OAuthToken>(((RestResponse)response).Content);
                var config = Configuration.Default;
                config.AddDefaultHeader("Authorization", string.Format("{0} {1}", tokenInfo.token_type, tokenInfo.access_token));
                return(tokenInfo);
            }
            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);
            }
        }
Exemplo n.º 7
0
        /// <summary>
        /// ConfigureJwtAuthorizationFlowByKey which performs JWT authentication using the private key.
        /// </summary>
        /// <param name="clientId"></param>
        /// <param name="userId"></param>
        /// <param name="oauthBasePath"></param>
        /// <param name="privateKey"></param>
        /// <param name="expiresInHours"></param>
        /// <param name="scopes"></param>
        /// <returns>If Successful, returns the OAuthToken object model which consist of an access token and expiration time.</returns>
        public OAuth.OAuthToken ConfigureJwtAuthorizationFlowByKey(string clientId, string userId, string oauthBasePath, string privateKey, int expiresInHours, List <string> scopes = null)
        {
            JwtSecurityTokenHandler handler = new JwtSecurityTokenHandler();

            SecurityTokenDescriptor descriptor = new SecurityTokenDescriptor()
            {
                Lifetime = new Lifetime(DateTime.UtcNow, DateTime.UtcNow.AddHours(expiresInHours)),
            };

            if (scopes == null)
            {
                scopes = new List <string>
                {
                    OAuth.Scope_SIGNATURE
                };
            }

            descriptor.Subject = new ClaimsIdentity();
            descriptor.Subject.AddClaim(new Claim("scope", String.Join(" ", scopes)));
            descriptor.Subject.AddClaim(new Claim("aud", oauthBasePath));
            descriptor.Subject.AddClaim(new Claim("iss", clientId));

            if (!string.IsNullOrEmpty(userId))
            {
                descriptor.Subject.AddClaim(new Claim("sub", userId));
            }

            if (!string.IsNullOrEmpty(privateKey))
            {
                var            rsa    = CreateRSAKeyFromPem(privateKey);
                RsaSecurityKey rsaKey = new RsaSecurityKey(rsa);
                descriptor.SigningCredentials = new SigningCredentials(rsaKey, SecurityAlgorithms.RsaSha256Signature, SecurityAlgorithms.HmacSha256Signature);
            }
            else
            {
                throw new ApiException(400, "Private key not supplied or is invalid!");
            }

            var    token    = handler.CreateToken(descriptor);
            string jwtToken = handler.WriteToken(token);

            Uri baseUrl = this.RestClient.BaseUrl;

            this.RestClient.BaseUrl = new Uri(string.Format("https://{0}", oauthBasePath));

            string path        = "oauth/token";
            string contentType = "application/x-www-form-urlencoded";

            Dictionary <string, string> formParams = new Dictionary <string, string>();

            formParams.Add("grant_type", "urn:ietf:params:oauth:grant-type:jwt-bearer");
            formParams.Add("assertion", jwtToken);

            Dictionary <string, string> queryParams = new Dictionary <string, string>();

            Dictionary <string, string> headerParams = new Dictionary <string, string>();

            headerParams.Add("Content-Type", "application/x-www-form-urlencoded");

            Dictionary <string, FileParameter> fileParams = new Dictionary <string, FileParameter>();
            Dictionary <string, string>        pathParams = new Dictionary <string, string>();

            object postBody = null;

            try
            {
                var response = CallApi(path, Method.POST, queryParams, postBody, headerParams, formParams, fileParams, pathParams, contentType);
                OAuth.OAuthToken tokenInfo = JsonConvert.DeserializeObject <OAuth.OAuthToken>(((RestResponse)response).Content);

                var config = Configuration.Default;
                config.AddDefaultHeader("Authorization", string.Format("{0} {1}", tokenInfo.token_type, tokenInfo.access_token));

                this.RestClient.BaseUrl = baseUrl;

                return(tokenInfo);
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }
Exemplo n.º 8
0
        public void Initialize(string path)
        {
            OAuth.OAuthToken consumerToken = new OAuth.OAuthToken("LDlaQSUySTwDAuyNG7dUQ", "rOEqilylc2zYqBoRjmJjx61GgeLitb6Kf35dePbE");
            OAuth.OAuthToken accessToken = IsLoggedIn() ? new OAuth.OAuthToken(AccessToken, AccessTokenSecret) : null;

            this.consumer = new Springnote.Consumer(consumerToken, accessToken);
            FilePath = path;
        }
        /// <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);
        }