Configuring AAD Authentication to Azure SQL Databases using AccessToken - EntityConnection


  • I have found many resources over the internet on how to assign access token to the SqlConnection object of the EntityFramework.


    var con = new SqlConnection(builder.ToString());
        con.AccessToken = token;

    But I need to work with the EntityConnection not SqlConnection. The EntityConnection class dose not have a property called AccessToken, unlike the SqlConnection class.

    So the question is how to assign AccessToken to EntityConnection object.

    14 iunie 2018 14:47

Toate mesajele

  • Hello,

    I don't know how to make it work with EntityConnection but I will show you with SQLConnection.

    You need to acquire the token as shown below:

    static async Task<string> GetAccessToken()
    var certificateSDN = "morillo";    
    var tenantId = "morillo";    
    var clientId = "morillo";    
    var resource = "";    
    X509Certificate2 certificate;    
    using (var certificateStore = new X509Store(StoreName.My, StoreLocation.CurrentUser))    
    {        certificateStore.Open(OpenFlags.ReadOnly);        certificate = certificateStore.Certificates            .Find(X509FindType.FindBySubjectDistinguishedName, certificateSDN, false)            
    var authenticationContext = new AuthenticationContext($"{tenantId}");    
    var clientAssertionCertificate = new ClientAssertionCertificate(clientId, certificate);    
    var authenticationResult = await 
    authenticationContext.AcquireTokenAsync(resource, clientAssertionCertificate);    
    return authenticationResult.AccessToken;

    Then you need to connect as shown below:

    var connectionStringBuilder = new
    DataSource = "",    
    InitialCatalog = "morillo",
    using (var sqlConnection = new SqlConnection(connectionStringBuilder.ConnectionString))
    sqlConnection.AccessToken = accessToken;    sqlConnection.Open();

    Hope this helps.


    Alberto Morillo

    14 iunie 2018 19:48