|
| 1 | +//<Snippet1> |
| 2 | +using System; |
| 3 | +using System.Threading.Tasks; |
| 4 | +using Microsoft.Identity.Client; |
| 5 | +using Microsoft.Data.SqlClient; |
| 6 | + |
| 7 | +namespace CustomAuthenticationProviderExamples |
| 8 | +{ |
| 9 | + /// <summary> |
| 10 | + /// Example demonstrating creating a custom device code flow authentication provider and attaching it to the driver. |
| 11 | + /// This is helpful for applications that wish to override the Callback for the Device Code Result implemented by the SqlClient driver. |
| 12 | + /// </summary> |
| 13 | + public class CustomDeviceCodeFlowAzureAuthenticationProvider : SqlAuthenticationProvider |
| 14 | + { |
| 15 | + public override async Task<SqlAuthenticationToken> AcquireTokenAsync(SqlAuthenticationParameters parameters) |
| 16 | + { |
| 17 | + string clientId = "my-client-id"; |
| 18 | + string clientName = "My Application Name"; |
| 19 | + string s_defaultScopeSuffix = "/.default"; |
| 20 | + |
| 21 | + string[] scopes = new string[] { parameters.Resource.EndsWith(s_defaultScopeSuffix) ? parameters.Resource : parameters.Resource + s_defaultScopeSuffix }; |
| 22 | + |
| 23 | + IPublicClientApplication app = PublicClientApplicationBuilder.Create(clientId) |
| 24 | + .WithAuthority(parameters.Authority) |
| 25 | + .WithClientName(clientName) |
| 26 | + .WithRedirectUri("https://login.microsoftonline.com/common/oauth2/nativeclient") |
| 27 | + .Build(); |
| 28 | + |
| 29 | + AuthenticationResult result = await app.AcquireTokenWithDeviceCode(scopes, |
| 30 | + deviceCodeResult => CustomDeviceFlowCallback(deviceCodeResult)).ExecuteAsync(); |
| 31 | + return new SqlAuthenticationToken(result.AccessToken, result.ExpiresOn); |
| 32 | + } |
| 33 | + |
| 34 | + public override bool IsSupported(SqlAuthenticationMethod authenticationMethod) => authenticationMethod.Equals(SqlAuthenticationMethod.ActiveDirectoryDeviceCodeFlow); |
| 35 | + |
| 36 | + private Task CustomDeviceFlowCallback(DeviceCodeResult result) |
| 37 | + { |
| 38 | + Console.WriteLine(result.Message); |
| 39 | + return Task.FromResult(0); |
| 40 | + } |
| 41 | + } |
| 42 | + |
| 43 | + public class Program |
| 44 | + { |
| 45 | + public static void Main() |
| 46 | + { |
| 47 | + // Register our custom authentication provider class to override Active Directory Device Code Flow |
| 48 | + SqlAuthenticationProvider.SetProvider(SqlAuthenticationMethod.ActiveDirectoryDeviceCodeFlow, new CustomDeviceCodeFlowAzureAuthenticationProvider()); |
| 49 | + using (SqlConnection sqlConnection = new SqlConnection("Server=<myserver>.database.windows.net;Authentication=Active Directory Device Code Flow;Database=<db>;")) |
| 50 | + { |
| 51 | + sqlConnection.Open(); |
| 52 | + Console.WriteLine("Connected successfully!"); |
| 53 | + } |
| 54 | + } |
| 55 | + } |
| 56 | +} |
| 57 | +//</Snippet1> |
0 commit comments