title: AD Token based authentication Login failed for user '<token-identified principal>'. in entity framework 6 for Azure SQL
body: <p>I have done Azure AD authentication for my SQL database.
  For that I followed bellow steps.</p>
  <ol>
  <li><p>I set the Azure AD admin for the SQL database in the portal</p>
  </li>
  <li><p>List item</p>
  </li>
  <li><p>get authentication Token</p>
  <pre><code>private static string GetAccessTokenAsync(string clientId, string clientSecret, string authority, 
  string resource, string scope)
  {
      var authContext = new AuthenticationContext(authority, TokenCache.DefaultShared);
      var clientCred = new ClientCredential(clientId, clientSecret);
      var token = authContext.AcquireTokenAsync(resource, clientCred).Result.AccessToken;
  
  
      return token;
  }
  </code></pre>
  </li>
  <li><p>did the sql connection</p>
  <pre><code>    string clientId = ConfigurationManager.AppSettings[&quot;ida:AADClientId&quot;];
      string clientSecret = ConfigurationManager.AppSettings[&quot;ida:AADAppKey&quot;];
      var authority = string.Format(&quot;https://login.microsoftonline.com/{0}&quot;, tenantId);
      var resource = &quot;https://database.windows.net/&quot;;
      var scope = &quot;&quot;;
      try
      {
          var token = GetAccessTokenAsync(clientId, clientSecret, authority, resource, scope);
  
          var builder = new SqlConnectionStringBuilder();
          builder[&quot;Data Source&quot;] = $&quot;{dbServer}.database.windows.net&quot;;
          builder[&quot;Initial Catalog&quot;] = dbName;
          builder[&quot;Connect Timeout&quot;] = 1500;
          builder[&quot;Persist Security Info&quot;] = false;
          builder[&quot;TrustServerCertificate&quot;] = false;
          builder[&quot;Encrypt&quot;] = true;
          builder[&quot;MultipleActiveResultSets&quot;] = false;
  
          SqlConnection con = new SqlConnection(builder.ToString());
          con.AccessToken = token;
          return con;
      }
  </code></pre>
  </li>
  <li><p>DB Context Class</p>
  <pre><code> public partial class DBEntities : DbContext
      {
  //string dbConnectionString = 
        string.Concat(ConfigurationManager.AppSettings[&quot;subdbconnectionstring&quot;], '&quot;', 
  string.Format(ConfigurationManager.AppSettings[&quot;dbconnectionstring&quot;], 
  ConfigurationManager.AppSettings[&quot;DBPassword&quot;]),'&quot;');
  
  //string test = ConfigurationManager.AppSettings[&quot;subdbconnectionstring&quot;] + &quot;\&quot;&quot; + ConfigurationManager.AppSettings[&quot;dbconnectionstring&quot;];
  public DBEntities(SqlConnection con)
       : base(con, true)
  {
      {
          Database.SetInitializer&lt;DBEntities&gt;(null);
          ((IObjectContextAdapter)this).ObjectContext.CommandTimeout = 1800;
      }
   }
  </code></pre>
  </li>
  <li><p>Finally connecting Database table</p>
  <pre><code> var con = AuthenticationHelper.GetSqlConnectionAsync(Constants.CDSDBServer, Constants.CDSDBDatabaseName);
          using (var dbContext = new DBEntities(con))
          {
  
              var teamRolesList = await dbContext.TEAM_ROLE.
                                   Where(t=&gt; t.IsDeleted.Equals(false))
                                  .Select(t =&gt; new TeamRole { RoleId = t.RoleId, RoleName = t.RoleName, IsDeleted = t.IsDeleted, UserInput=t.UserInput,AllowMultiples=t.AllowMultiples }).
                                  ToListAsync();
  </code></pre>
  </li>
  </ol>
  <p>}</p>
  <p>Now I am getting error while connecting to Table,</p>
  <pre><code>The underlying provider failed on Open.Login failed for user '&lt;token-identified principal&gt; 
  
  at System.Data.Entity.Core.EntityClient.EntityConnection.&lt;OpenAsync&gt;d__8.MoveNext()
  --- End of stack trace from previous location where exception was thrown ---
  at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
  at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
  at System.Data.Entity.Core.Objects.ObjectContext.&lt;EnsureConnectionAsync&gt;d__9.MoveNext()
  --- End of stack trace from previous location where exception was thrown ---
  at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
  at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
  at System.Data.Entity.Core.Objects.ObjectContext.&lt;ExecuteInTransactionAsync&gt;d__3d`1.MoveNext()
  --- End of stack trace from previous location where exception was thrown ---
  at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
  at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task 
    task)
  at System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.&lt;ExecuteAsyncImplementation&gt;d__9`1.MoveNext()
  --- End of stack trace from previous location where exception was thrown ---
  at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
  at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
  at System.Data.Entity.Utilities.TaskExtensions.CultureAwaiter`1.GetResult()
  at System.Data.Entity.Core.Objects.ObjectQuery`1.&lt;GetResultsAsync&gt;d__e.MoveNext()
  --- End of stack trace from previous location where exception was thrown ---
  at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
  at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
  at System.Data.Entity.Utilities.TaskExtensions.CultureAwaiter`1.GetResult()
  at System.Data.Entity.Internal.LazyAsyncEnumerator`1.&lt;FirstMoveNextAsync&gt;d__0.MoveNext()
  --- End of stack trace from previous location where exception was thrown ---
  at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
  at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
  at System.Data.Entity.Infrastructure.IDbAsyncEnumerableExtensions.&lt;ForEachAsync&gt;d__5`1.MoveNext()
  --- End of stack trace from previous location where exception was thrown ---
  at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
  at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
  at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
  at CompanyDataService.Controllers.TeamController.&lt;GetAllTeamRoles&gt;d__0.MoveNext() in D:\sol\vs_project\DataService\DataService\Controllers\TeamController.cs:line 32
  </code></pre>