コード例 #1
0
        public ActionResult Authentication(string error_reason,
                                           string error,
                                           string error_description,
                                           string code)
        {
            if (string.IsNullOrEmpty(error_reason))
            {
                if (!string.IsNullOrEmpty(code))
                {
                    var oAuthAuthentication = new OAuthAuthentication(new WebRequestService(),
                                                                      new FacebookUriAuthentication(Request.IsSecureConnection),
                                                                      new FacebookExtractTokenFromText());

                    if (oAuthAuthentication.Authenticate(code, RequestType.Get))
                    {
                        var client = new FacebookClient(oAuthAuthentication.Token);

                        var info         = client.Get("me?fields=id,name");
                        var facebookId   = (string)info.id;
                        var facebookName = (string)info.name;

                        Response.Write("id:" + facebookId + "- name::" + facebookName);
                    }
                }
            }

            return(null);
        }
コード例 #2
0
        public void TestGetRedirectUri()
        {
            var serverConnectionMock = CreateServerConnectionMockWithContext();
            var oAuth = new OAuthAuthentication(serverConnectionMock.Object);

            Assert.AreEqual(serverConnectionMock.Object.RedirectUri, oAuth.RedirectUri);
        }
コード例 #3
0
        public void setup()
        {
            var currentPath    = MasterCard.Core.Util.GetCurrenyAssemblyPath();
            var authentication = new OAuthAuthentication("gVaoFbo86jmTfOB4NUyGKaAchVEU8ZVPalHQRLTxeaf750b6!414b543630362f426b4f6636415a5973656c33735661383d", currentPath + "\\prod_key.p12", "alias", "password");

            ApiConfig.SetAuthentication(authentication);
        }
コード例 #4
0
        public void setup()
        {
            var currentPath    = MasterCard.Core.Util.GetCurrenyAssemblyPath();
            var authentication = new OAuthAuthentication("L5BsiPgaF-O3qA36znUATgQXwJB6MRoMSdhjd7wt50c97279!50596e52466e3966546d434b7354584c4975693238513d3d", currentPath + "\\Test\\mcapi_sandbox_key.p12", "test", "password");

            ApiConfig.SetAuthentication(authentication);
        }
コード例 #5
0
        public void Authenticate_WhenResponseTypeIsPost_ShouldCallWebRequestServicePostMethod()
        {
            WebRequestServiceFake mockWebRequestServiceFake;
            OAuthAuthentication   oAuthAuthentication = CreateOAuthAuthentication(out mockWebRequestServiceFake);

            oAuthAuthentication.Authenticate("any authoritzation code", RequestType.Post);

            mockWebRequestServiceFake.PostCalls.Should().Be(1);
        }
コード例 #6
0
 public async void TestAuthenticateFailure_FailedToGetAuthorizationCode_UnknownResponseUri()
 {
     var serverConnectionMock = CreateServerConnectionMockWithContext();
     var oAuth = new OAuthAuthentication(serverConnectionMock.Object)
     {
         GetRedirectedUri = uri => Task.FromResult(new Uri("http://www.unknown.com"))
     };
     await AssertEx.ThrowsAsync <OperationCanceledException>(async() => await oAuth.Authenticate());
 }
コード例 #7
0
 public async void TestAuthenticateFailure_FailedToGetAuthorizationCode_UnknownResponseUri()
 {
     var serverConnectionMock = CreateServerConnectionMockWithContext();
     var oAuth = new OAuthAuthentication(serverConnectionMock.Object)
     {
         GetRedirectedUri = uri => Task.FromResult(new Uri("http://www.unknown.com"))
     };
     await AssertEx.ThrowsAsync<OperationCanceledException>(async () => await oAuth.Authenticate());
 }
コード例 #8
0
        public void Authenticate_WhenTokenReturnedByExtractClassIsNull_ShouldReturnFalse()
        {
            var extractTokenFromTextFake = new ExtractTokenFromTextFake {
                ExtractStringReturn = null
            };
            OAuthAuthentication oAuthAuthentication = CreateOAuthAuthenticationWith(extractTokenFromTextFake);
            var gotToken = oAuthAuthentication.Authenticate("any authoritzation code", RequestType.Post);

            gotToken.Should().Be(false);
        }
コード例 #9
0
 public async void TestAuthenticateFailure_FailedToGetAuthorizationCode_Exception()
 {
     var serverConnectionMock = CreateServerConnectionMockWithContext();
     var oAuth = new OAuthAuthentication(serverConnectionMock.Object)
     {
         GetRedirectedUri = async uri => await Task.Run(new Func<Task<Uri>>(() => { throw new Exception("Test message."); })),
     };
     var ex = await AssertEx.ThrowsAsync<Exception>(async () => await oAuth.Authenticate());
     Assert.AreEqual("Test message.", ex.Message);
 }
コード例 #10
0
        public void Can_Authenticate_Netflix_With_OAuth()
        {
            const string consumerKey    = "L7gdVVLFZ24LkQlPXxPk3WBjd";
            const string consumerSecret = "t0q0QWPAquKblDoRFoI9VmzH8DGrRNtGrdXPbrYfsE1WolVqBP";

            AuthContext     context = new OAuth1Context(consumerKey, consumerSecret);
            XAuthentication xas     = new OAuthAuthentication(context);

            var request = new RestRequest("oauth/request_token", Method.POST);

            xas.Authenticate(client, request);
            var response = client.Execute(request);

            Assert.NotNull(response);
            Assert.AreEqual(HttpStatusCode.OK, response.StatusCode);

            // For Access Token >
            var qs               = HttpUtility.ParseQueryString(response.Content);
            var oauthToken       = qs["oauth_token"];
            var oauthTokenSecret = qs["oauth_token_secret"];

            request = new RestRequest("oauth/authorize");
            request.AddParameter("oauth_token", oauthToken);
            request.AddParameter("user_name", "*****@*****.**");
            request.AddParameter("password", "twitprachi");
            request.AddParameter("grant_type", "password");

            var url = client.BuildUri(request)
                      .ToString();

            Process.Start(url);

            const string requestUrl = "https://www.prachi.com/?oauth_token=g6o8mAAAAAAA46YAAAABYhuA2DU&oauth_verifier=ZUSV9exrCch0jTOQYxWmszh6aLYyaveo";

            // get the access token
            string e = "https://www.prachi.com/?oauth_token=yu489AAAAAAA46YAAAABYifW0Ac&oauth_verifier=rNZFFL25DHvxmo0qmijN2mKf4SNaszJc";
            var    requestTokenQueryParameters = HttpUtility.ParseQueryString(new Uri(e).Query);
            var    requestVerifier             = requestTokenQueryParameters["oauth_verifier"];


            client.Authenticator = OAuth1Authenticator.ForAccessToken(consumerKey, consumerSecret, oauthToken,
                                                                      oauthTokenSecret, requestVerifier);

            context = new OAuth1Context(consumerKey, consumerSecret, oauthToken, oauthTokenSecret, requestVerifier);
            xas     = new OAuthAuthentication(context);

            request = new RestRequest("oauth/access_token", Method.POST);

            xas.Authenticate(client, request);
            response = client.Execute(request);

            Assert.NotNull(oauthToken);
            Assert.NotNull(oauthTokenSecret);
        }
コード例 #11
0
        public async void TestAuthenticateFailure_FailedToGetAuthorizationCode_Exception()
        {
            var serverConnectionMock = CreateServerConnectionMockWithContext();
            var oAuth = new OAuthAuthentication(serverConnectionMock.Object)
            {
                GetRedirectedUri = async uri => await Task.Run(new Func <Task <Uri> >(() => { throw new Exception("Test message."); })),
            };
            var ex = await AssertEx.ThrowsAsync <Exception>(async() => await oAuth.Authenticate());

            Assert.AreEqual("Test message.", ex.Message);
        }
コード例 #12
0
 public async void TestAuthenticateFailure_FailedToGetAuthorizationCode_ErrorMessage()
 {
     var serverConnectionMock = CreateServerConnectionMockWithContext();
     var oAuth = new OAuthAuthentication(serverConnectionMock.Object)
     {
         GetRedirectedUri = uri => Task.FromResult(new Uri("http://www.testRedirectUri.com?error=access_denied"))
     };
     var ex = await AssertEx.ThrowsAsync<ServerException>(async () => await oAuth.Authenticate());
     Assert.IsNotNull(ex);
     Assert.AreEqual(-1, ex.Code);
     Assert.AreEqual("access_denied", ex.ErrorMessage);
 }
コード例 #13
0
        public void setup()
        {
            var authentication = new OAuthAuthentication("gVaoFbo86jmTfOB4NUyGKaAchVEU8ZVPalHQRLTxeaf750b6!414b543630362f426b4f6636415a5973656c33735661383d", "../../Test/prod_key.p12", "alias", "password");

            ApiConfig.setAuthentication(authentication);
            ApiConfig.setSandbox(true);


#if DEBUG
            ApiConfig.setLocalhost();
#endif
        }
コード例 #14
0
        public async void TestAuthenticateFailure_FailedToGetAccessToken_InvalidJson()
        {
            var serverConnectionMock = CreateServerConnectionMockWithContext();

            serverConnectionMock.Setup(s => s.Post(It.IsAny <Uri>(), null)).ReturnsAsync("###").Verifiable();
            var oAuth = new OAuthAuthentication(serverConnectionMock.Object)
            {
                GetRedirectedUri = uri => Task.FromResult(new Uri("http://www.testRedirectUri.com?code=testCode"))
            };
            await AssertEx.ThrowsAsync <JsonReaderException>(async() => await oAuth.Authenticate());

            serverConnectionMock.Verify();
        }
コード例 #15
0
        public async void TestAuthenticateFailure_FailedToGetAuthorizationCode_ErrorMessage()
        {
            var serverConnectionMock = CreateServerConnectionMockWithContext();
            var oAuth = new OAuthAuthentication(serverConnectionMock.Object)
            {
                GetRedirectedUri = uri => Task.FromResult(new Uri("http://www.testRedirectUri.com?error=access_denied"))
            };
            var ex = await AssertEx.ThrowsAsync <ServerException>(async() => await oAuth.Authenticate());

            Assert.IsNotNull(ex);
            Assert.AreEqual(-1, ex.Code);
            Assert.AreEqual("access_denied", ex.ErrorMessage);
        }
コード例 #16
0
        public async void TestAuthenticateFailure_FailedToGetAccessToken_Exception()
        {
            var serverConnectionMock = CreateServerConnectionMockWithContext();

            serverConnectionMock.Setup(s => s.Post(It.IsAny <Uri>(), null)).ThrowsAsync(new Exception("Test message.")).Verifiable();
            var oAuth = new OAuthAuthentication(serverConnectionMock.Object)
            {
                GetRedirectedUri = uri => Task.FromResult(new Uri("http://www.testRedirectUri.com?code=testCode"))
            };
            var ex = await AssertEx.ThrowsAsync <Exception>(async() => await oAuth.Authenticate());

            Assert.AreEqual("Test message.", ex.Message);
            serverConnectionMock.Verify();
        }
コード例 #17
0
        public void setup()
        {
            ApiConfig.SetDebug(true);
            ApiConfig.SetSandbox(true);
            var path = MasterCard.Core.Util.GetCurrenyAssemblyPath();

            var authentication = new OAuthAuthentication("L5BsiPgaF-O3qA36znUATgQXwJB6MRoMSdhjd7wt50c97279!50596e52466e3966546d434b7354584c4975693238513d3d", path + "\\Test\\mcapi_sandbox_key.p12", "test", "password");

            ApiConfig.SetAuthentication(authentication);

            var interceptor = new MDESCryptography(path + "\\Test\\mastercard_public.crt", path + "\\Test\\mastercard_private.pem");

            ApiConfig.AddCryptographyInterceptor(interceptor);
        }
コード例 #18
0
        private void PersistAuthenticationTokens()
        {
            using (var context = new OAuthDataContext())
            {
                context.Database.ExecuteSqlCommand("DELETE FROM [OAuthAuthentications]");

                var item = new OAuthAuthentication();
                item.AccessToken   = _accessToken;
                item.RefreshToken  = _refreshToken;
                item.Expiry        = _tokenExpiry;
                item.AuthorizeCode = _authorizeCode;
                context.OAuthAuthentication.Add(item);
                context.SaveChanges();
            }
        }
コード例 #19
0
        public OAuthTestWindow()
        {
            OAuth = new OAuthAuthentication(((App)Application.Current).ServerConnection)
            {
                GetRedirectedUri = async uri =>
                {
                    var window = new BrowserWindow(uri, OAuth.RedirectUri);
                    return(await window.GetRedirectUri());
                }
            };

            InitializeComponent();

            ShowSessionInfo();
        }
コード例 #20
0
ファイル: Server.cs プロジェクト: PyYoshi/TwitterIrcGateway
        public Server(Boolean useSslConnection)
        {
            // for Mono
            if (Environment.OSVersion.Platform == PlatformID.Unix)
            {
                ServicePointManager.ServerCertificateValidationCallback += delegate { return(true); }
            }
            ;

            // OAuth Default Tokens (TweetIrcGateway)
            OAuthClientKey = "9gGt51Xp3AB8C7wU2Tw";
            OAuthSecretKey = "74K9CwKANFVLVupHMtHy4fJ3TjAJq58CvxxtAQjoI";

            ServicePointManager.DefaultConnectionLimit = 1000;
            Authentication  = new OAuthAuthentication();
            IsSslConnection = useSslConnection;
        }
コード例 #21
0
        public void Run()
        {
            ApiAuthentication auth = null;

            //auth = new PasswordAuthentication("username", "passsword", "developerToken");

            auth = new OAuthAuthentication(
                "accessToken",
                "refreshToken",
                "developerToken",
                DateTime.UtcNow.Ticks,
                "clientId");

            IList <AccountInfo> accounts = null;

            using (CustomerMHelper cs = new CustomerMHelper(LogHandler))
            {
                var response = cs.TryGetAccountsInfo(auth, CustomerId, true);
                if (response != null && response.AccountsInfo != null)
                {
                    accounts = response.AccountsInfo.ToList();
                }
            }

            if (accounts == null || accounts.Count == 0)
            {
                return;
            }

            //you can submit a report request which could most contain 1000 accountIds per time
            //if you have more than 1000 accounts, then you should submit the report request every 1000 accountIds
            //for demo, we just pick up the first 1000 accountIds
            if (accounts.Count > 1000)
            {
                accounts = accounts.TakeWhile((p, i) => { return(i < 1000); }).ToList();
            }

            using (ReportingHelper rs = new ReportingHelper(LogHandler))
            {
                //Submit & download
                var succeed =
                    rs.TrySubmitGenerateReport(auth, BuildRequest(accounts.Select(p => p.Id).ToArray()), CustomerId, null, SaveFilePath);
            }
        }
コード例 #22
0
        public ActionResult Authentication(string code)
        {
            if (!string.IsNullOrEmpty(code))
            {
                var oAuthAuthentication = new OAuthAuthentication(new WebRequestService(), new OrkutUriAuthentication(), new OrkutExtractTokenFromText());

                if (oAuthAuthentication.Authenticate(code, RequestType.Post))
                {
                    string info;
                    using (var webClient = new WebClient()) {
                        info = webClient.DownloadString(string.Format("https://www.orkut.com/social/rest/people/@me?access_token={0}", oAuthAuthentication.Token));
                    }

                    Response.Write(info);
                }
            }

            return(null);
        }
コード例 #23
0
        protected void Page_Load(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(Request["error_reason"]))
            {
                var oAuthAuthentication = new OAuthAuthentication(new WebRequestService(), new FacebookUriAuthentication(Request.IsSecureConnection), new FacebookExtractTokenFromText());
                if (oAuthAuthentication.Authenticate(Request["code"], RequestType.Get))
                {
                    var client       = new FacebookClient(oAuthAuthentication.Token);
                    var info         = client.Get("me?fields=id,name");
                    var facebookId   = (string)info.id;
                    var facebookName = (string)info.name;

                    Response.Write("id:" + facebookId + "- name::" + facebookName);
                }
            }

            Response.Flush();
            Response.End();
        }
コード例 #24
0
 public async void TestAuthenticateSuccess()
 {
     var serverConnectionMock = CreateServerConnectionMockWithContext();
     var expectedPostUri = new Uri("https://www.douban.com/service/auth2/token?client_id=testClientId12345&client_secret=testClientSecret12345&redirect_uri=http%3A%2F%2Fwww.testredirecturi.com%2F&grant_type=authorization_code&code=testCode");
     serverConnectionMock.Setup(s => s.Post(It.Is<Uri>(u=>u == expectedPostUri), null)).ReturnsAsync(Resource.TestOAuthResponse).Verifiable();
     var oAuth = new OAuthAuthentication(serverConnectionMock.Object)
     {
         GetRedirectedUri = uri => Task.FromResult(new Uri("http://www.testRedirectUri.com?code=testCode"))
     };
     var result = await oAuth.Authenticate();
     Assert.IsNotNull(result);
     Assert.IsNotNull(result);
     Assert.IsNotNull(result.AccessToken);
     Assert.IsNotNull(result.RefreshToken);
     Assert.IsNotNull(result.Username);
     Assert.AreNotEqual(0, result.UserId);
     Assert.AreNotEqual(0, result.ExpiresIn);
     serverConnectionMock.Verify();
 }
コード例 #25
0
        public void setup()
        {
            ApiConfig.setSandbox(true);
            ApiConfig.setDebug(true);


            var path = MasterCard.Core.Util.GetCurrenyAssemblyPath();


            var authentication = new OAuthAuthentication("gVaoFbo86jmTfOB4NUyGKaAchVEU8ZVPalHQRLTxeaf750b6!414b543630362f426b4f6636415a5973656c33735661383d", path + "\\Test\\prod_key.p12", "alias", "password");

            ApiConfig.setAuthentication(authentication);

            String mastercardPublic  = path + "\\Test\\mastercard_public.crt";
            String mastercardPrivate = path + "\\Test\\mastercard_private.pem";
            var    interceptor       = new MDESCryptography(mastercardPublic, mastercardPrivate);

            ApiConfig.AddCryptographyInterceptor(interceptor);
        }
コード例 #26
0
        protected void Page_Load(object sender, EventArgs e)
        {
            var authorizationCode = Request["code"];

            if (!string.IsNullOrEmpty(authorizationCode))
            {
                var oAuthAuthentication = new OAuthAuthentication(new WebRequestService(), new OrkutUriAuthentication(), new OrkutExtractTokenFromText());

                if (oAuthAuthentication.Authenticate(authorizationCode, RequestType.Post))
                {
                    string info;
                    using (var webClient = new WebClient()) {
                        info = webClient.DownloadString(string.Format("https://www.orkut.com/social/rest/people/@me?access_token={0}", oAuthAuthentication.Token));
                    }

                    Response.Write(info);
                }
            }
        }
コード例 #27
0
        public void SetUp()
        {
            iMcomConfig                  = new MscMcomConfig();
            iMcomConfig.BaseUrl          = "BaseUrl";
            iMcomConfig.ConsumerKey      = "ConsumerKey";
            iMcomConfig.KeyPassword      = "******";
            iMcomConfig.CertPath         = @"CertPath";
            iMcomConfig.BaseUrl          = "BaseUrl";
            iMcomConfig.UserAgentVersion = "UserAgentVersion";
            iMcomConfig.UrlVersionNumber = "UrlVersionNumber";
            iMcomConfig.Environment      = "Environment";

            iCerteficateReaderMock = new Mock <ICerteficateReader>();
            iCerteficateReaderMock.Setup(f => f.GetPrivateKey(It.IsAny <String>(), It.IsAny <String>()))
            .Returns(xmlStringPrivateKey);

            oAuthAuthentication = new OAuthAuthentication(iMcomConfig,
                                                          iCerteficateReaderMock.Object,
                                                          SecurityProtocolType.Tls12);
            iRestRequest = new RestRequest(uri, Method.GET);
        }
コード例 #28
0
        public async void TestAuthenticateSuccess()
        {
            var serverConnectionMock = CreateServerConnectionMockWithContext();
            var expectedPostUri      = new Uri("https://www.douban.com/service/auth2/token?client_id=testClientId12345&client_secret=testClientSecret12345&redirect_uri=http%3A%2F%2Fwww.testredirecturi.com%2F&grant_type=authorization_code&code=testCode");

            serverConnectionMock.Setup(s => s.Post(It.Is <Uri>(u => u == expectedPostUri), null)).ReturnsAsync(Resource.TestOAuthResponse).Verifiable();
            var oAuth = new OAuthAuthentication(serverConnectionMock.Object)
            {
                GetRedirectedUri = uri => Task.FromResult(new Uri("http://www.testRedirectUri.com?code=testCode"))
            };
            var result = await oAuth.Authenticate();

            Assert.IsNotNull(result);
            Assert.IsNotNull(result);
            Assert.IsNotNull(result.AccessToken);
            Assert.IsNotNull(result.RefreshToken);
            Assert.IsNotNull(result.Username);
            Assert.AreNotEqual(0, result.UserId);
            Assert.AreNotEqual(0, result.ExpiresIn);
            serverConnectionMock.Verify();
        }
コード例 #29
0
        public void setup()
        {
            var authentication = new OAuthAuthentication("L5BsiPgaF-O3qA36znUATgQXwJB6MRoMSdhjd7wt50c97279!50596e52466e3966546d434b7354584c4975693238513d3d", "../../mcapi_sandbox_key.p12", "alias", "password");

            ApiConfig.setAuthentication(authentication);
        }
コード例 #30
0
 public async void TestAuthenticateFailure_FailedToGetAccessToken_Exception()
 {
     var serverConnectionMock = CreateServerConnectionMockWithContext();
     serverConnectionMock.Setup(s => s.Post(It.IsAny<Uri>(), null)).ThrowsAsync(new Exception("Test message.")).Verifiable();
     var oAuth = new OAuthAuthentication(serverConnectionMock.Object)
     {
         GetRedirectedUri = uri => Task.FromResult(new Uri("http://www.testRedirectUri.com?code=testCode"))
     };
     var ex = await AssertEx.ThrowsAsync<Exception>(async () => await oAuth.Authenticate());
     Assert.AreEqual("Test message.", ex.Message);
     serverConnectionMock.Verify();
 }
コード例 #31
0
        /// <summary>
        /// Get Http job authentication.
        /// </summary>
        /// <param name="authenticationParams">Http authentication properties specified via PowerShell.</param>
        /// <returns>HttpAuthentication object.</returns>
        private HttpAuthentication PopulateHttpAuthentication(PSHttpJobAuthenticationParams authenticationParams)
        {
            if (authenticationParams == null ||
                authenticationParams.HttpAuthType == null ||
                authenticationParams.HttpAuthType.Equals(Constants.HttpAuthenticationNone, StringComparison.InvariantCultureIgnoreCase))
            {
                return null;
            }
            else if (authenticationParams.HttpAuthType.Equals(Constants.HttpAuthenticationClientCertificate, StringComparison.InvariantCultureIgnoreCase))
            {
                if(string.IsNullOrWhiteSpace(authenticationParams.ClientCertPfx) ||
                    string.IsNullOrWhiteSpace(authenticationParams.ClientCertPassword))
                {
                    throw new PSManagement.PSArgumentException(Resources.SchedulerInvalidClientCertAuthRequest);
                }

                var clientCert = new ClientCertAuthentication()
                {
                    Type = HttpAuthenticationType.ClientCertificate,
                    Pfx = authenticationParams.ClientCertPfx,
                    Password = authenticationParams.ClientCertPassword
                };

                return clientCert;
            }
            else if (authenticationParams.HttpAuthType.Equals(Constants.HttpAuthenticationActiveDirectoryOAuth, StringComparison.InvariantCultureIgnoreCase))
            {
                if (string.IsNullOrWhiteSpace(authenticationParams.Tenant) ||
                    string.IsNullOrWhiteSpace(authenticationParams.ClientId) ||
                    string.IsNullOrWhiteSpace(authenticationParams.Secret) ||
                    string.IsNullOrWhiteSpace(authenticationParams.Audience))
                {
                    throw new PSManagement.PSArgumentException(Resources.SchedulerInvalidActiveDirectoryOAuthRequest);
                }

                var adOAuth = new OAuthAuthentication()
                {
                    Type = HttpAuthenticationType.ActiveDirectoryOAuth,
                    Audience = authenticationParams.Audience,
                    ClientId = authenticationParams.ClientId,
                    Secret = authenticationParams.Secret,
                    Tenant = authenticationParams.Tenant
                };

                return adOAuth;
            }
            else if (authenticationParams.HttpAuthType.Equals(Constants.HttpAuthenticationBasic, StringComparison.InvariantCultureIgnoreCase))
            {
                if(string.IsNullOrWhiteSpace(authenticationParams.Username) ||
                   string.IsNullOrWhiteSpace(authenticationParams.Password))
                {
                    throw new PSManagement.PSArgumentException(Resources.SchedulerInvalidBasicRequest);
                }

                var basic = new BasicAuthentication()
                {
                    Type = HttpAuthenticationType.Basic,
                    Username = authenticationParams.Username,
                    Password = authenticationParams.Password
                };

                return basic;
            }
            else
            {
                throw new PSManagement.PSArgumentException(Resources.SchedulerInvalidAuthenticationType);
            }
        }
コード例 #32
0
        public void setup()
        {
            var authentication = new OAuthAuthentication("gVaoFbo86jmTfOB4NUyGKaAchVEU8ZVPalHQRLTxeaf750b6!414b543630362f426b4f6636415a5973656c33735661383d", "../../prod_key.p12", "alias", "password");

            ApiConfig.setAuthentication(authentication);
        }
コード例 #33
0
 public void TestGetRedirectUri()
 {
     var serverConnectionMock = CreateServerConnectionMockWithContext();
     var oAuth = new OAuthAuthentication(serverConnectionMock.Object);
     Assert.AreEqual(serverConnectionMock.Object.RedirectUri, oAuth.RedirectUri);
 }
コード例 #34
0
 public async void TestAuthenticateFailure_FailedToGetAccessToken_InvalidJson()
 {
     var serverConnectionMock = CreateServerConnectionMockWithContext();
     serverConnectionMock.Setup(s => s.Post(It.IsAny<Uri>(), null)).ReturnsAsync("###").Verifiable();
     var oAuth = new OAuthAuthentication(serverConnectionMock.Object)
     {
         GetRedirectedUri = uri => Task.FromResult(new Uri("http://www.testRedirectUri.com?code=testCode"))
     };
     await AssertEx.ThrowsAsync<JsonReaderException>(async () => await oAuth.Authenticate());
     serverConnectionMock.Verify();
 }
コード例 #35
0
        /// <summary>
        /// Get Http job authentication.
        /// </summary>
        /// <param name="authenticationParams">Http authentication properties specified via PowerShell.</param>
        /// <returns>HttpAuthentication object.</returns>
        private HttpAuthentication PopulateHttpAuthentication(PSHttpJobAuthenticationParams authenticationParams)
        {
            if (authenticationParams == null ||
                authenticationParams.HttpAuthType == null ||
                authenticationParams.HttpAuthType.Equals(Constants.HttpAuthenticationNone, StringComparison.InvariantCultureIgnoreCase))
            {
                return(null);
            }
            else if (authenticationParams.HttpAuthType.Equals(Constants.HttpAuthenticationClientCertificate, StringComparison.InvariantCultureIgnoreCase))
            {
                if (string.IsNullOrWhiteSpace(authenticationParams.ClientCertPfx) ||
                    string.IsNullOrWhiteSpace(authenticationParams.ClientCertPassword))
                {
                    throw new PSManagement.PSArgumentException(Resources.SchedulerInvalidClientCertAuthRequest);
                }

                var clientCert = new ClientCertAuthentication()
                {
                    Type     = HttpAuthenticationType.ClientCertificate,
                    Pfx      = authenticationParams.ClientCertPfx,
                    Password = authenticationParams.ClientCertPassword
                };

                return(clientCert);
            }
            else if (authenticationParams.HttpAuthType.Equals(Constants.HttpAuthenticationActiveDirectoryOAuth, StringComparison.InvariantCultureIgnoreCase))
            {
                if (string.IsNullOrWhiteSpace(authenticationParams.Tenant) ||
                    string.IsNullOrWhiteSpace(authenticationParams.ClientId) ||
                    string.IsNullOrWhiteSpace(authenticationParams.Secret) ||
                    string.IsNullOrWhiteSpace(authenticationParams.Audience))
                {
                    throw new PSManagement.PSArgumentException(Resources.SchedulerInvalidActiveDirectoryOAuthRequest);
                }

                var adOAuth = new OAuthAuthentication()
                {
                    Type     = HttpAuthenticationType.ActiveDirectoryOAuth,
                    Audience = authenticationParams.Audience,
                    ClientId = authenticationParams.ClientId,
                    Secret   = authenticationParams.Secret,
                    Tenant   = authenticationParams.Tenant
                };

                return(adOAuth);
            }
            else if (authenticationParams.HttpAuthType.Equals(Constants.HttpAuthenticationBasic, StringComparison.InvariantCultureIgnoreCase))
            {
                if (string.IsNullOrWhiteSpace(authenticationParams.Username) ||
                    string.IsNullOrWhiteSpace(authenticationParams.Password))
                {
                    throw new PSManagement.PSArgumentException(Resources.SchedulerInvalidBasicRequest);
                }

                var basic = new BasicAuthentication()
                {
                    Type     = HttpAuthenticationType.Basic,
                    Username = authenticationParams.Username,
                    Password = authenticationParams.Password
                };

                return(basic);
            }
            else
            {
                throw new PSManagement.PSArgumentException(Resources.SchedulerInvalidAuthenticationType);
            }
        }
コード例 #36
0
 public BitbucketCloudClient(string url, OAuthAuthentication oauth)
     : this(url)
 {
     _auth = oauth;
 }