Beispiel #1
0
        /// <summary>
        /// Apply this authenticator to the given authentication parameters.
        /// </summary>
        /// <param name="parameters">The complex object containing authentication specific information.</param>
        /// <returns>
        /// An instance of <see cref="AuthenticationResult" /> that represents the access token generated as result of a successful authenication.
        /// </returns>
        public override async Task <AuthenticationResult> AuthenticateAsync(AuthenticationParameters parameters)
        {
            AuthenticationResult   authResult;
            IClientApplicationBase app;
            InteractiveParameters  interactiveParameters = parameters as InteractiveParameters;
            TcpListener            listener = null;
            string redirectUri = null;

            int port = 8399;

            while (++port < 9000)
            {
                try
                {
                    listener = new TcpListener(IPAddress.Loopback, port);
                    listener.Start();
                    redirectUri = string.Format("http://localhost:{0}/", port);
                    listener.Stop();
                    break;
                }
                catch (Exception ex)
                {
                    WriteWarning($"Port {port} is taken with exception '{ex.Message}'; trying to connect to the next port.");
                    listener?.Stop();
                }
            }

            app = GetClient(parameters.Account, parameters.Environment, redirectUri);

            if (app is IConfidentialClientApplication)
            {
                ICustomWebUi customWebUi = new CustomWebUi(interactiveParameters.Message);

                Uri authCodeUrl = await customWebUi.AcquireAuthorizationCodeAsync(
                    await app.AsConfidentialClient().GetAuthorizationRequestUrl(parameters.Scopes).ExecuteAsync(CancellationToken.None).ConfigureAwait(false),
                    new Uri(redirectUri),
                    CancellationToken.None).ConfigureAwait(false);

                NameValueCollection queryStringParameters = HttpUtility.ParseQueryString(authCodeUrl.Query);

                authResult = await app.AsConfidentialClient().AcquireTokenByAuthorizationCode(
                    parameters.Scopes,
                    queryStringParameters["code"]).ExecuteAsync().ConfigureAwait(false);
            }
            else
            {
                authResult = await app.AsPublicClient().AcquireTokenInteractive(parameters.Scopes)
                             .WithCustomWebUi(new CustomWebUi(interactiveParameters.Message))
                             .WithPrompt(Prompt.ForceLogin)
                             .ExecuteAsync().ConfigureAwait(false);
            }

            return(authResult);
        }
Beispiel #2
0
        static async Task Main(string[] args)
        {
            const string tenant   = "3aa4a235-b6e2-48d5-9195-7fcf05b459b0";
            const string resource = "32f2a909-8a98-4eb8-b22d-1208d9350cb0";
            const string clientId = "b5e79b0d-fddb-4f65-8d10-99863858779f";
            //var authority = new Uri($"https://login.windows.net/{tenant}");
            string redirectUri = "https://login.microsoftonline.com/common/oauth2/nativeclient";

            string[] scopes = new string[] { $"{resource}/.default" };

            try
            {
                var app = PublicClientApplicationBuilder.Create(clientId)
                          .WithTenantId(tenant)
                          .WithExtraQueryParameters($"resource={resource}")
                          .WithRedirectUri(redirectUri)
                          .Build();

                AuthenticationResult result = null;
                var accounts = await app.GetAccountsAsync();

                try
                {
                    result = await app.AcquireTokenSilent(scopes, accounts.FirstOrDefault())
                             //.WithClaims("Timeseries.Admin,Timeseries.Read,Timeseries.Read.All")
                             .ExecuteAsync();
                }
                catch (MsalUiRequiredException)
                {
                    var customWebUi = new CustomWebUi();
                    result = await app.AcquireTokenWithDeviceCode(scopes,
                                                                  async (dc) =>
                    {
                        Console.WriteLine($"Enter the following device code on the web page: {dc.UserCode}");
                        OpenBrowser(dc.VerificationUrl);
                    })
                             .ExecuteAsync();
                }

                if (result != null)
                {
                    var httpClient = new HttpClient();
                    httpClient.BaseAddress = new Uri("https://api.gateway.equinor.com/");
                    httpClient.DefaultRequestHeaders.Authorization =
                        new AuthenticationHeaderValue("Bearer", result.AccessToken);
                    Console.WriteLine("Requesting timeseries...");
                    var response = await httpClient.GetAsync("/plant-beta/timeseries/v1.2?limit=10");

                    Console.WriteLine("Reading response body...");
                    var body = await response.Content.ReadAsStringAsync();

                    Console.WriteLine(body);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"[{ex.GetType().Name}] {ex.Message}");
                Console.WriteLine(ex.StackTrace);
            }

            Console.ReadLine();
        }