none
Configuring AAD Authentication to Azure SQL Databases using AccessToken - EntityConnection

    Întrebare

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

    Example:

    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.


    joi, 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 = "https://database.windows.net/";    
    
    X509Certificate2 certificate;    
    using (var certificateStore = new X509Store(StoreName.My, StoreLocation.CurrentUser))    
    {        certificateStore.Open(OpenFlags.ReadOnly);        certificate = certificateStore.Certificates            .Find(X509FindType.FindBySubjectDistinguishedName, certificateSDN, false)            
    [0];    
    }  
      
    var authenticationContext = new AuthenticationContext($"https://login.microsoftonline.com/{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
    SqlConnectionStringBuilder()
    {    
    DataSource = "morillo.database.windows.net",    
    InitialCatalog = "morillo",
    };
    using (var sqlConnection = new SqlConnection(connectionStringBuilder.ConnectionString))
    {
    sqlConnection.AccessToken = accessToken;    sqlConnection.Open();
    }



    Hope this helps.



    Regards,

    Alberto Morillo
    SQLCoffee.com


    joi, 14 iunie 2018 19:48