Skip to content

Instantly share code, notes, and snippets.

@preetikr
Last active May 1, 2018 03:43
Show Gist options
  • Save preetikr/28b5679909a116bb21d3906344a72800 to your computer and use it in GitHub Desktop.
Save preetikr/28b5679909a116bb21d3906344a72800 to your computer and use it in GitHub Desktop.
Net472_SQL_ADALConnectivity.cs
class Program
{
static void Test()
{
// Instantiate the provider.
var provider = new ActiveDirectoryAuthProvider();
// Register the provider to auth methods. This only needs to be done once per process.
//This sample shows existing and new keywords. You can use few of these depending on your scenario.
SqlAuthenticationProvider.SetProvider(SqlAuthenticationMethod.ActiveDirectoryIntegrated, provider);
SqlAuthenticationProvider.SetProvider(SqlAuthenticationMethod.ActiveDirectoryInteractive, provider);
SqlAuthenticationProvider.SetProvider(SqlAuthenticationMethod.ActiveDirectoryPassword, provider);
// Start connections.
using (SqlConnection connection = new SqlConnection("test conn string..."))
{
connection.Open();
// query
}
}
// An auth provider implementation that supports all three AD auth methods
class ActiveDirectoryAuthProvider : SqlAuthenticationProvide
{
private readonly string _clientId = "clientId";
private readonly Uri _redirectUri = new Uri("redirect uri");
public override async Task<SqlAuthenticationToken> AcquireTokenAsync(SqlAuthenticationParameters
parameters)
{
AuthenticationContext authContext = new AuthenticationContext(parameters.Authority);
authContext.CorrelationId = parameters.ConnectionId;
AuthenticationResult result;
switch (parameters.AuthenticationMethod)
{
case SqlAuthenticationMethod.ActiveDirectoryInteractive:
result = await authContext.AcquireTokenAsync(parameters.Resource, _clientId,
_redirectUri, new PlatformParameters(PromptBehavior.Auto),
new UserIdentifier(parameters.UserId, UserIdentifierType.RequiredDisplayableId));
break;
case SqlAuthenticationMethod.ActiveDirectoryIntegrated:
result = await authContext.AcquireTokenAsync(parameters.Resource, _clientId,
new UserCredential());
break;
case SqlAuthenticationMethod.ActiveDirectoryPassword:
result = await authContext.AcquireTokenAsync(parameters.Resource, _clientId,
new UserPasswordCredential(parameters.UserId, parameters.Password));
break;
default: throw new InvalidOperationException();
}
return new SqlAuthenticationToken(result.AccessToken, result.ExpiresOn);
}
public override bool IsSupported(SqlAuthenticationMethod authenticationMethod)
{
return authenticationMethod == SqlAuthenticationMethod.ActiveDirectoryIntegrated
|| authenticationMethod == SqlAuthenticationMethod.ActiveDirectoryInteractive
|| authenticationMethod == SqlAuthenticationMethod.ActiveDirectoryPassword;
}
}
}
@zhiweiv
Copy link

zhiweiv commented May 1, 2018

SqlAuthenticationProvide should be SqlAuthenticationProvider

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment