public Connectors(IUrls urls, OAuth2Client.IStorage storage)
 {
     if (urls == null) throw new ArgumentNullException("urls");
     if (storage == null) throw new ArgumentNullException("storage");
     _urls = urls;
     _storage = storage;
     InitializeInternal();
 }
 public AuthenticationController(Settings settings, ISaveChanges unitOfWork, AuthenticationDao authenticationDao, OAuth2Client oAuth2Client)
     : base(settings, unitOfWork)
 {
     Claws.NotNull(() => authenticationDao);
       Claws.NotNull(() => oAuth2Client);
       this.authenticationDao = authenticationDao;
       this.oAuth2Client = oAuth2Client;
 }
		public V1APIConnector(string urlPrefix, string username = null, string password = null, bool? integratedAuth = null,
							  ProxyProvider proxy = null, OAuth2Client.IStorage storage = null)
			: base(urlPrefix, new CredentialCache(), proxy)
		{
			var cache = _creds as CredentialCache;
			var uri = new Uri(urlPrefix);

			// Try the OAuth2 credential
			OAuth2Client.IStorage oauth2storage = null;
			if (storage != null)
			{
				oauth2storage = storage;
			}
			else
			{
				try
				{
					var s = OAuth2Client.Storage.JsonFileStorage.Default as OAuth2Client.IStorage;
					s.GetSecrets();
					oauth2storage = s;
				}
				catch (System.IO.FileNotFoundException)
				{
					// swallowed - meaning no oauth2 secrets configured.
				}
			}
			if (oauth2storage != null)
			{
				cache.Add(uri,
					"Bearer",
					new OAuth2Client.OAuth2Credential(
						"apiv1",
						oauth2storage,
						proxy != null ? proxy.CreateWebProxy() : null
						)
					);
			}

			if (username == null)
			{
				if (integratedAuth.GetValueOrDefault(true))
				{ // no constructor args - so use default integrated identity unless they say no.
					cache.Add(uri, "NTLM", CredentialCache.DefaultNetworkCredentials);
					cache.Add(uri, "Negotiate", CredentialCache.DefaultNetworkCredentials);
				}
			}
			else
			{
				var userPassCred = new NetworkCredential(username, password);
				cache.Add(uri, "Basic", userPassCred);

				if (!integratedAuth.GetValueOrDefault(false))
				{ // If there's a username, we'll assume the user doesn't want Windows Auth unless they ask.
					cache.Add(uri, "NTLM", userPassCred);
					cache.Add(uri, "Negotiate", userPassCred);
				}
			}
		}
Exemplo n.º 4
0
        //service to service authentication
        static TokenResponse GetToken()
        {
            var client = new OAuth2Client(
                new Uri("https://localhost:44333/connect/token"),
                "silicon",
                "F621F470-9731-4A25-80EF-67A6F7C5F4B8");

            return(client.RequestClientCredentialsAsync("api1").Result);
        }
		public IServices CreateServices(string baseUrl, OAuth2Client.IStorage storage)
		{
			var dataConnector = new V1OAuth2APIConnector(baseUrl + "/rest-1.oauth.v1/", storage);
			var metaConnector = new V1OAuth2APIConnector(baseUrl + "/meta.v1/", storage);
			_metaModel = new MetaModel(metaConnector);
			var services = new Services(_metaModel, dataConnector);

			return services;
		}
Exemplo n.º 6
0
        private async Task <DrsMetadataResponse> QueryEnrollmentServerEndpointAsync(
            string endpoint, RequestContext requestContext)
        {
            var client = new OAuth2Client(ServiceBundle.HttpManager, ServiceBundle.TelemetryManager);

            client.AddQueryParameter("api-version", "1.0");
            return(await client.ExecuteRequestAsync <DrsMetadataResponse>(new Uri(endpoint), HttpMethod.Get, requestContext)
                   .ConfigureAwait(false));
        }
Exemplo n.º 7
0
        static TokenResponse RequestToken()
        {
            var client = new OAuth2Client(
                new Uri(Constants.TokenEndpoint),
                "client",
                "secret");

            return(client.RequestClientCredentialsAsync("read write").Result);
        }
        public void ValidUserNameCredentialMissingClientCredential()
        {
            var client = new OAuth2Client(new Uri(baseAddress));

            var response = client.RequestAccessTokenUserName(
                Constants.Credentials.ValidUserName,
                Constants.Credentials.ValidPassword,
                scope);
        }
Exemplo n.º 9
0
        //human to service authentication
        static TokenResponse GetUserToken()
        {
            var client = new OAuth2Client(
                new Uri("https://localhost:44333/connect/token"),
                "carbon",
                "21B5F798-BE55-42BC-8AA8-0025B903DC3B");

            return(client.RequestResourceOwnerPasswordAsync("bob", "secret", "api1").Result);
        }
Exemplo n.º 10
0
        static TokenResponse RequestToken()
        {
            var client = new OAuth2Client(
                new Uri(Constants.TokenEndpoint),
                "roclient",
                "secret");

            return(client.RequestResourceOwnerPasswordAsync("bob", "bob", "read write").Result);
        }
        public ActionResult RenewToken(string refreshToken)
        {
            var client = new OAuth2Client(
                new Uri("https://idsrv.local/issue/oauth2/token"),
                "codeflowclient",
                "secret");
            var response = client.RequestAccessTokenRefreshToken(refreshToken);

            return(View("Postback", response));
        }
Exemplo n.º 12
0
        public HomeController(ILogger <HomeController> logger, IConfiguration config)
        {
            _logger = logger;
            var clientId     = config.GetValue <string>("QuickBook:ClientId");
            var clientSecret = config.GetValue <string>("QuickBook:ClientSecret");
            var redirectUrl  = config.GetValue <string>("QuickBook:RedirectUrl");
            var environment  = config.GetValue <string>("QuickBook:Environment");

            auth2Client = new OAuth2Client(clientId, clientSecret, redirectUrl, environment);
        }
        public ActionResult RenewToken(string refreshToken)
        {
            var client = new OAuth2Client(
                new Uri(Constants.AS.OAuth2TokenEndpoint),
                Constants.Clients.CodeClient,
                Constants.Clients.CodeClientSecret);
            var response = client.RequestAccessTokenRefreshToken(refreshToken);

            return(View("Postback", response));
        }
Exemplo n.º 14
0
        static TokenResponse RefreshToken(string refreshToken)
        {
            var client = new OAuth2Client(
                new Uri("https://HFL0100:44333/connect/token"),
                "carbon",
                "21B5F798-BE55-42BC-8AA8-0025B903DC3B");

            ServicePointManager.ServerCertificateValidationCallback = delegate { return(true); };
            return(client.RequestRefreshTokenAsync(refreshToken).Result);
        }
        private async Task <TenantDiscoveryResponse> DiscoverEndpoints(string openIdConfigurationEndpoint,
                                                                       RequestContext requestContext)
        {
            OAuth2Client client = new OAuth2Client();

            return
                (await
                 client.ExecuteRequest <TenantDiscoveryResponse>(new Uri(openIdConfigurationEndpoint),
                                                                 HttpMethod.Get, requestContext).ConfigureAwait(false));
        }
Exemplo n.º 16
0
        public static async Task <string> ReRefreshToken()
        {
            var _httpClient = new OAuth2Client(new Uri(m_Uri), m_ClientId, m_ClientSecret);

            _httpClient.BaseAddress = new Uri(m_Uri);
            oAuth2Token             = await _httpClient.RefreshToken(oAuth2Token.RefreshToken);

            httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", oAuth2Token.AccessToken);
            return(oAuth2Token.AccessToken);
        }
Exemplo n.º 17
0
        protected override void SetAdditionalRequestParameters(OAuth2Client client)
        {
            client.AddBodyParameter(OAuth2Parameter.GrantType,
                                    AuthenticationRequestParameters.UserAssertion.AssertionType);
            client.AddBodyParameter(OAuth2Parameter.Assertion, AuthenticationRequestParameters.UserAssertion.Assertion);
            client.AddBodyParameter(OAuth2Parameter.RequestedTokenUse, OAuth2RequestedTokenUse.OnBehalfOf);

            //TODO To request id_token in response
            //requestParameters[OAuth2Parameter.Scope] = OAuth2Value.ScopeOpenId;
        }
Exemplo n.º 18
0
        static TokenResponse GetUserTokenLock()
        {
            var client = new OAuth2Client(
                new Uri("https://HFL0100:44333/connect/token"),
                "carbon",
                "21B5F798-BE55-42BC-8AA8-0025B903DC3B", OAuth2Client.ClientAuthenticationStyle.PostValues);

            ServicePointManager.ServerCertificateValidationCallback = delegate { return(true); };
            return(client.RequestResourceOwnerPasswordAsync("Davidao", "Davide1981!1", "api1").Result);
        }
        public LoginServicePickerViewModel()
        {
            this.googleClient   = this.LoadSafelyFromLocalSettings(OAuth2ServiceConstants.GoogleOAuth2Service);
            this.facebookClient = this.LoadSafelyFromLocalSettings(OAuth2ServiceConstants.FacebookOAuth2Service);
            this.liveClient     = this.LoadSafelyFromLocalSettings(OAuth2ServiceConstants.LiveOAuth2Service);

            this.GoogleLoginCommand   = new RelayCommand(this.GoogleLogin);
            this.FacebookLoginCommand = new RelayCommand(this.FacebookLogin);
            this.LiveLoginCommand     = new RelayCommand(this.LiveLogin);
        }
Exemplo n.º 20
0
        public HalKit.Http.HttpConnection Build()
        {
            DelegatingHandler authenticationHandler;

            switch (_connectionType)
            {
            case ConnectionType.OAuth:
            {
                authenticationHandler = new BasicAuthenticationHandler(_configuration.ClientId, _configuration.ClientSecret);
                break;
            }

            case ConnectionType.Api:
            {
                var oauthConnection = OAuthConnection(_configuration, _product, _serializer)
                                      .LocalizationProvider(_localizationProvider)
                                      .HttpClientHandler(_httpClientHandler)
                                      .AdditionalHandlers(_additionalHandlers)
                                      .Build();
                var oauthClient = new OAuth2Client(oauthConnection, _configuration);
                authenticationHandler = new BearerTokenAuthenticationHandler(oauthClient, _tokenStore, _configuration);
                break;
            }

            default:
            {
                throw new ArgumentOutOfRangeException("_connectionType");
            }
            }

            var halKitConfiguration = new HalKitConfiguration(_configuration.ViagogoApiRootEndpoint)
            {
                CaptureSynchronizationContext = _configuration.CaptureSynchronizationContext
            };

            var responseFactory = new HalKit.Http.ApiResponseFactory(_serializer, halKitConfiguration);

            // IMPORTANT: The order of these handlers is significant!
            var handlers = new List <DelegatingHandler>
            {
                new ErrorHandler(responseFactory, _configuration, _serializer),
                new UserAgentHandler(_product),
                authenticationHandler,
                new LocalizationHandler(_localizationProvider)
            };

            handlers.AddRange(_additionalHandlers ?? new DelegatingHandler[] { });

            return(new HalKit.Http.HttpConnection(
                       handlers,
                       halKitConfiguration,
                       new HalKit.Http.HttpClientFactory(_httpClientHandler),
                       _serializer,
                       responseFactory));
        }
        private static TokenResponse RefreshToken(string refreshToken)
        {
            var client = new OAuth2Client(
                new Uri("http://localhost:2727/token"),
                "client1",
                "secret");

            var response = client.RequestRefreshTokenAsync(refreshToken).Result;

            return(response);
        }
        public async Task <ActionResult> RenewToken(string refreshToken)
        {
            var client = new OAuth2Client(
                new Uri(Constants.AS.OAuth2TokenEndpoint),
                Constants.Clients.CodeClient,
                Constants.Clients.CodeClientSecret);

            var response = await client.RequestRefreshTokenAsync(refreshToken);

            return(View("Postback", response));
        }
Exemplo n.º 23
0
        public ActionResult Index(string scopes)
        {
            var client = new OAuth2Client(new Uri(Constants.AuthorizeEndpoint));
            var url    = client.CreateCodeFlowUrl(
                "codeclient",
                scopes,
                "https://localhost:44312/callback",
                "123");

            return(Redirect(url));
        }
Exemplo n.º 24
0
        public static TokenResponse RefreshToken(string refreshToken)
        {
            var client = new OAuth2Client(
                new Uri(AppConfig.HostAddress_API_Authorize + "token"),
                ConfigurationManager.AppSettings.Get("ClientId"),
                string.Empty);

            var response = client.RequestRefreshTokenAsync(refreshToken).Result;

            return(response);
        }
        private async Task <TenantDiscoveryResponse> DiscoverEndpointsAsync(
            string openIdConfigurationEndpoint,
            RequestContext requestContext)
        {
            var client = new OAuth2Client(requestContext.Logger, _serviceBundle.HttpManager, _serviceBundle.TelemetryManager);

            return(await client.ExecuteRequestAsync <TenantDiscoveryResponse>(
                       new Uri(openIdConfigurationEndpoint),
                       HttpMethod.Get,
                       requestContext).ConfigureAwait(false));
        }
Exemplo n.º 26
0
        private void AuthenticateQB()
        {
            OAuth2Client      oauthClient = new OAuth2Client(clientID, clientSecret, redirectURI, appEnvironment);
            List <OidcScopes> scopes      = new List <OidcScopes>();

            scopes.Add(OidcScopes.Accounting);
            var authorizeUrl       = oauthClient.GetAuthorizationURL(scopes);
            ProcessStartInfo sInfo = new ProcessStartInfo(authorizeUrl);

            Process.Start(sInfo);
        }
        static void Main(string[] args)
        {
            var client = new OAuth2Client(
                new Uri("https://localhost:44333/core/connect/token"),
                "client",
                "secret");

            var result = client.RequestAssertionAsync("custom", "foo", "read").Result;

            ShowResponse(result);
        }
Exemplo n.º 28
0
 /// <summary>
 /// Initializes a new instance of the <see cref="BaseTest"/> class.
 /// </summary>
 protected BaseTest()
 {
     _oAuth2Client     = new OAuth2Client(new Uri(ConfigurationManager.AppSettings["integrationUrl"] + "episerverapi/token"));
     TestDataDirectory = Path.Combine(Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location), "TestData");
     if (String.IsNullOrEmpty(ConfigurationManager.AppSettings["OutputDirectory"]))
     {
         throw new Exception("OutputDirectory was not found in appsettings.  Please enter a value for the output directory");
     }
     OutputDirectory = ConfigurationManager.AppSettings["OutputDirectory"];
     EnsureOutputDirectory();
 }
Exemplo n.º 29
0
        public async Task Should_Validate_And_Issue_Access_Token_When_Resource_Owner_Credentials_Are_Correct()
        {
            using (TestServer server = TestServer.Create <Startup>())
            {
                OAuth2Client  client        = new OAuth2Client(new Uri("http://whatever:5000/token"), server.Handler);
                TokenResponse tokenResponse = await client.RequestResourceOwnerPasswordAsync("bob", "bob");

                Assert.NotNull(tokenResponse);
                Assert.NotNull(tokenResponse.AccessToken);
            }
        }
Exemplo n.º 30
0
        private string CreateAuthUrl(OAuth2Client authClient)
        {
            var requestUrl = authClient.CreateCodeFlowUrl(
                Constant.CodeClientId,
                Constant.Scope,
                Constant.RedirectUriCode);

            Console.WriteLine("Request Authorization code:\n" + requestUrl);

            return(requestUrl);
        }
        private static TokenResponse GetToken()
        {
            var client = new OAuth2Client(
                new Uri("http://localhost:2727/token"),
                "client1",
                "secret");

            var response = client.RequestResourceOwnerPasswordAsync("bob", "bob").Result;

            return(response);
        }
Exemplo n.º 32
0
        /// <summary>
        /// Get a token using Thinktecture OAuth2Client
        /// </summary>
        /// <returns></returns>
        public static string GetToken()
        {
            var client = new OAuth2Client(
                new Uri(ConfigurationManager.AppSettings["Authority"] + "/connect/token"),
                _clientId,
                _clientSecret);

            var response = client.RequestClientCredentialsAsync("bimtoolkitapi").Result;

            return(response.AccessToken);
        }
Exemplo n.º 33
0
        private static TokenResponse RefreshToken(string refreshToken)
        {
            var client = new OAuth2Client(
                new Uri("http://webapiversiontwo.local/token"),
                "client1",
                "secret");

            var response = client.RequestRefreshTokenAsync(refreshToken, null, new CancellationToken()).Result;

            return(response);
        }
Exemplo n.º 34
0
        private static TokenResponse GetToken()
        {
            var client = new OAuth2Client(
                new Uri("http://webapiversiontwo.local/token"),
                "client1",
                "secret");

            var response = client.RequestResourceOwnerPasswordAsync("bob", "bob", null, null, new CancellationToken()).Result;

            return(response);
        }
Exemplo n.º 35
0
        public void DownloadFolder(OAuth2Client client, DropNet.DropNetClient DownloadClient, string Dir, string DestinationDirectory, string API, bool IsConsole)
        {
            if (Directory.Exists(DestinationDirectory) == false)
            {
                if (IsConsole)
                {
                    Console.WriteLine("Creating folder:" + DestinationDirectory);
                }
                Directory.CreateDirectory(DestinationDirectory);
            }

            var Data = client.GetFolderMeta(API, Dir);

            foreach (var item in Data.Contents)
            {
                if (item.IsDirectory)
                {
                    DownloadFolder(client, DownloadClient, item.Path, DestinationDirectory + @"\" + item.Path.Split('/')[item.Path.Split('/').Count() - 1], API, IsConsole);

                }
                else
                {
                    if (IsConsole)
                    {
                        Console.WriteLine("Downloading:" + Path.GetFileName(item.Path));
                    }

                    var NewFile = DownloadClient.GetFile(item.Path);

                    using (var fileStream = new FileStream(
                    DestinationDirectory + @"\" + Path.GetFileName(item.Path), FileMode.CreateNew, FileAccess.ReadWrite))
                    {
                        fileStream.Write(NewFile, 0, NewFile.Length);
                        fileStream.Flush(true);

                    }

                }
            }
        }
Exemplo n.º 36
0
 public ActivityLogClient(OAuth2Client oAuth2Client, UserSession userSession)
     : base(oAuth2Client, userSession)
 {
 }
Exemplo n.º 37
0
 public OAuth2CompletedEventArgs(OAuth2Client.OAuth2TokenResponse response,string state)
 {
     this.Response = response;
     this.State = state;
 }
 protected AuthenticatedClientBase(OAuth2Client oAuth2Client, UserSession userSession)
 {
     this.OAuth2Client = oAuth2Client;
       this.UserSession = userSession;
 }
Exemplo n.º 39
0
 public UserProfileClient(OAuth2Client oAuth2Client, UserSession userSession)
     : base(oAuth2Client, userSession)
 {
 }