question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Getting TypeLoadException while using AppAuthentication library

See original GitHub issue

Getting TypeLoadException while trying to use AppAuthentication for accessing SQL Database using Managed Identities.

Link with details on what I am trying to achieve - https://docs.microsoft.com/en-us/azure/app-service/app-service-web-tutorial-connect-msi

Exception or Stack Trace Exception: System.TypeInitializationException: ‘The type initializer for ‘System.Data.SqlClient.SqlAuthenticationProviderManager’ threw an exception.’

InnerException (1 of 2): ArgumentException: Failed to instantiate an authentication provider with type ‘Microsoft.Azure.Services.AppAuthentication.SqlAppAuthenticationProvider, Microsoft.Azure.Services.AppAuthentication’ for ‘ActiveDirectoryInteractive’.

InnerException (2 of 2): TypeLoadException: Could not load type ‘Microsoft.Azure.Services.AppAuthentication.SqlAppAuthenticationProvider’ from assembly ‘Microsoft.Azure.Services.AppAuthentication’.

To Reproduce Steps to reproduce the behavior:

  1. Add “Microsoft.Azure.Services.AppAuthentication” Nuget package to ASP.NET web app project.
  2. Add configuration based on this link

Code Snippet <SqlAuthenticationProviders> <providers> <add name="Active Directory Interactive" type="Microsoft.Azure.Services.AppAuthentication.SqlAppAuthenticationProvider, Microsoft.Azure.Services.AppAuthentication" /> </providers> </SqlAuthenticationProviders>

Expected behavior Application should be able to load SqlAppAuthenticationProvider, as per the documentation from AppAuthentication dll.

Setup (please complete the following information):

  • OS: Windows 10
  • IDE : Visual Studio 2017
  • Microsoft.Azure.Services.AppAuthentication - version 1.2.1

Information Checklist Kindly make sure that you have added all the following information above and checkoff the required fields otherwise we will treat the issuer as an incomplete report

  • Bug Description Added
  • Repro Steps Added
  • Setup information Added

Issue Analytics

  • State:closed
  • Created 4 years ago
  • Comments:12

github_iconTop GitHub Comments

1reaction
asbjornvgcommented, Sep 17, 2019

Changing the web app target framwork to 4.7.2 seems to solve it.

The file sdk/mgmtcommon/AppAuthentication/Azure.Services.AppAuthentication/SqlAppAuthenticationProvider.cs only has contents if the .NET version is 4.7.2.

I’m not sure why 4.7.2 is required, but it should probably fail more gracefully if the target framework is wrong.

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.

#if net472
using System;
using System.Data.SqlClient;
using System.Threading.Tasks;

namespace Microsoft.Azure.Services.AppAuthentication
{
    /// <summary>
    /// An implementation of SqlAuthenticationProvider that implements Active Directory Interactive SQL authentication.
    /// </summary>
    public class SqlAppAuthenticationProvider : SqlAuthenticationProvider
    {
        /// <summary>
        /// The principal used to acquire token. This will be of type "User" for local development scenarios, and "App" when client credentials flow is used. 
        /// </summary>
        public Principal PrincipalUsed { get; private set; }

        /// <summary>
        /// If the userId parameter is a valid GUID, return an token provider connection string to use a user-assigned managed identity
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        internal static string GetConnectionStringByUserId(string userId)
        {
            if (Guid.TryParse(userId, out Guid unused))
            {
                return $"RunAs=App;AppId={userId}";
            }

            return default(string);
        }

        /// <summary>
        /// Acquires an access token for SQL using AzureServiceTokenProvider with the given SQL authentication parameters.
        /// </summary>
        /// <param name="parameters">The parameters needed in order to obtain a SQL access token</param>
        /// <returns></returns>
        public override async Task<SqlAuthenticationToken> AcquireTokenAsync(SqlAuthenticationParameters parameters)
        {
            var appAuthParameters = new SqlAppAuthenticationParameters(parameters);
            return await AcquireTokenAsync(appAuthParameters).ConfigureAwait(false);
        }

        /// <summary>
        /// Acquires an access token for SQL using AzureServiceTokenProvider with the given SQL authentication parameters.
        /// </summary>
        /// <param name="parameters">The parameters needed in order to obtain a SQL access token</param>
        /// <returns></returns>
        internal async Task<SqlAuthenticationToken> AcquireTokenAsync(SqlAppAuthenticationParameters parameters)
        {
            string azureAdInstance = UriHelper.GetAzureAdInstanceByAuthority(parameters.Authority);
            string connectionString = GetConnectionStringByUserId(parameters.UserId);
            string tenantId = UriHelper.GetTenantByAuthority(parameters.Authority);

            if (string.IsNullOrEmpty(azureAdInstance))
            {
                throw new ArgumentException("The Azure AD instance could not be parsed from the authority provided in SqlAuthenticationParameters");
            }

            if (string.IsNullOrEmpty(parameters.Resource))
            {
                throw new ArgumentException("A resource must be specified in SqlAuthenticationParameters");
            }
            
            AzureServiceTokenProvider tokenProvider = new AzureServiceTokenProvider(connectionString, azureAdInstance);

            var authResult = await tokenProvider.GetAuthenticationResultAsync(parameters.Resource, tenantId).ConfigureAwait(false);
            PrincipalUsed = tokenProvider.PrincipalUsed;

            return new SqlAuthenticationToken(authResult.AccessToken, authResult.ExpiresOn);
        }

        /// <summary>
        /// Implements virtual method in SqlAuthenticationProvider. Only Active Directory Interactive Authentication is supported.
        /// </summary>
        /// <param name="authenticationMethod">The SQL authentication method to check whether supported</param>
        /// <returns></returns>
        public override bool IsSupported(SqlAuthenticationMethod authenticationMethod)
        {
            return authenticationMethod == SqlAuthenticationMethod.ActiveDirectoryInteractive;
        }
    }
}
#endif
1reaction
sbhuttancommented, Sep 10, 2019

@elafnitzegger - I closed the issue as it seemed like issue was not reproducible anymore. I will try to upload the sample solution that is working for me. Would you be able to share the sample project where you are facing the issue to compare and get to root of this issue?

I will reopen the issue now for further troubleshooting and let admins decide on when to close.

Read more comments on GitHub >

github_iconTop Results From Across the Web

Getting TypeLoadException while using AppAuthentication ...
Getting TypeLoadException while trying to use AppAuthentication for accessing SQL Database using Managed Identities.
Read more >
TypeLoadException Could not load type ...
[Solved]-TypeLoadException Could not load type 'WebConfigurationManager' when calling .Net Framework Library via Web API Core app-.net-core.
Read more >
App Authentication client library for .NET - version 1.6.0
AppAuthentication library manages authentication automatically, which in turn lets you focus on your solution, rather than your credentials.
Read more >
Could not load type Microsoft.Azure.Services. ...
Inner Exception 1: ArgumentException: Failed to instantiate an authentication provider with type 'Microsoft.Azure.Services.AppAuthentication.
Read more >
ASP.NET Core - RSSing.com
I got the following message below and have no idea what to do? TypeLoadException: Method 'Create' in type 'Microsoft.EntityFrameworkCore.SqlServer.Query.
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found