|
| 1 | +using System; |
| 2 | +using System.IO; |
| 3 | +using System.Net; |
| 4 | +using System.Net.Sockets; |
| 5 | +using System.Text; |
| 6 | +using System.Threading; |
| 7 | +using System.Threading.Tasks; |
| 8 | +using Microsoft.Extensions.Hosting; |
| 9 | +using NetCoreForce.Client; |
| 10 | + |
| 11 | +namespace AuthApp.Host |
| 12 | +{ |
| 13 | + /// <summary> |
| 14 | + /// Web Server OAuth Authentication Flow |
| 15 | + /// https://developer.salesforce.com/docs/atlas.en-us.api_rest.meta/api_rest/intro_understanding_web_server_oauth_flow.htm |
| 16 | + /// </summary> |
| 17 | + public class HttpServer : BackgroundService |
| 18 | + { |
| 19 | + private readonly SfConfig _config; |
| 20 | + private bool isCompleted = false; |
| 21 | + |
| 22 | + public HttpServer(SfConfig config) |
| 23 | + { |
| 24 | + _config = config; |
| 25 | + } |
| 26 | + |
| 27 | + protected override async Task ExecuteAsync(CancellationToken stoppingToken) |
| 28 | + { |
| 29 | + Console.WriteLine($"{nameof(HttpServer)} is starting."); |
| 30 | + var http = new HttpListener(); |
| 31 | + var redirectURI = string.Format("http://{0}:{1}/", "localhost", GetRandomUnusedPort()); |
| 32 | + http.Prefixes.Add(redirectURI); |
| 33 | + http.Start(); |
| 34 | + |
| 35 | + var authUrl = GetAuthorizationUrl(redirectURI); |
| 36 | + Console.WriteLine($"Opening a browser window with Url: {authUrl}"); |
| 37 | + ConsoleHandler.HideConsole(); |
| 38 | + |
| 39 | + var process = ConsoleHandler.OpenBrowser(authUrl); |
| 40 | + var context = await http.GetContextAsync(); |
| 41 | + |
| 42 | + while (!stoppingToken.IsCancellationRequested || isCompleted ) |
| 43 | + { |
| 44 | + Console.WriteLine($"{nameof(HttpServer)} is running"); |
| 45 | + |
| 46 | + if (context != null) |
| 47 | + { |
| 48 | + ConsoleHandler.ShowConsole(); |
| 49 | + |
| 50 | + var responseOutput = await ShowBrowserMessage(context); |
| 51 | + |
| 52 | + responseOutput.Close(); |
| 53 | + |
| 54 | + |
| 55 | + if (context.Request.QueryString.Get("error") != null) |
| 56 | + { |
| 57 | + Console.WriteLine(string.Format("OAuth authorization error: {0}.", context.Request.QueryString.Get("error"))); |
| 58 | + } |
| 59 | + if (context.Request.QueryString.Get("code") == null) |
| 60 | + { |
| 61 | + Console.WriteLine("Malformed authorization response. " + context.Request.QueryString); |
| 62 | + } |
| 63 | + |
| 64 | + // Authorization code the consumer must use to obtain the access and refresh tokens. |
| 65 | + // The authorization code expires after 15 minutes. |
| 66 | + var code = context.Request.QueryString.Get("code"); |
| 67 | + |
| 68 | + var auth = new AuthenticationClient(); |
| 69 | + await auth.WebServerAsync(_config.ClientId, |
| 70 | + _config.ClientSecret, |
| 71 | + redirectURI, |
| 72 | + code, |
| 73 | + $"{_config.LoginUrl}/services/oauth2/token"); |
| 74 | + |
| 75 | + |
| 76 | + |
| 77 | + Console.WriteLine($"Your access_token is {auth.AccessInfo.AccessToken}"); |
| 78 | + Console.WriteLine($"Your refresh_token is {auth.AccessInfo.RefreshToken}"); |
| 79 | + |
| 80 | + isCompleted = true; |
| 81 | + } |
| 82 | + await Task.Delay(TimeSpan.FromSeconds(5), stoppingToken); |
| 83 | + } |
| 84 | + |
| 85 | + http.Stop(); |
| 86 | + Console.WriteLine($"{nameof(HttpServer)} is stopping."); |
| 87 | + } |
| 88 | + |
| 89 | + private int GetRandomUnusedPort() |
| 90 | + { |
| 91 | + var listener = new TcpListener(IPAddress.Loopback, 5050); |
| 92 | + listener.Start(); |
| 93 | + var port = ((IPEndPoint)listener.LocalEndpoint).Port; |
| 94 | + listener.Stop(); |
| 95 | + return port; |
| 96 | + } |
| 97 | + |
| 98 | + private string GetAuthorizationUrl(string redirectURI) |
| 99 | + { |
| 100 | + var authEndpoint = $"{_config.LoginUrl}/services/oauth2/authorize"; |
| 101 | + var url = $"{authEndpoint}?response_type=code&access_type=offline&scope=openid%20profile%20api%20refresh_token%20offline_access&redirect_uri={Uri.EscapeDataString(redirectURI)}&client_id={_config.ClientId}"; |
| 102 | + return url; |
| 103 | + } |
| 104 | + |
| 105 | + private static async Task<Stream> ShowBrowserMessage(HttpListenerContext context) |
| 106 | + { |
| 107 | + var response = context.Response; |
| 108 | + var responseString = string.Format(@" |
| 109 | + <html> |
| 110 | + <body>Please return to the console to retrieve access and refresh tokens.</body> |
| 111 | + </html>"); |
| 112 | + |
| 113 | + var buffer = Encoding.UTF8.GetBytes(responseString); |
| 114 | + response.ContentLength64 = buffer.Length; |
| 115 | + var responseOutput = response.OutputStream; |
| 116 | + await responseOutput.WriteAsync(buffer, 0, buffer.Length); |
| 117 | + return responseOutput; |
| 118 | + } |
| 119 | + } |
| 120 | +} |
0 commit comments