Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

'UserPasswordCredential' could not be found

I am attempting to make authentication for Azure Functions in C#, Visual Studio 17. This line gives the error:

    var credentials = new UserPasswordCredential(UserName, Password);

It gives the error as is if I had not included the NuGet package: "The type or namespace name "UserpasswordCredential" could not be found (are you missing a using directive or and assembly reference?)".

I have included the package Microsoft.IdentityModel.Clients.ActiveDirectory (v. 3.19.2 - latest stable). But for some reason this bit is missing (I have also tried the older versions). Microsoft themselves says it should be part of the package https://docs.microsoft.com/en-us/dotnet/api/microsoft.identitymodel.clients.activedirectory.userpasswordcredential?view=azure-dotnet. But it is not.

Does someone know how to fix this?

Full code below:

    /// <summary>
    /// Generates a new Azure Active Directory access token
    /// </summary>
    /// <param name = "url" > A URL for the end-point for which the access token is requested</param>
    /// <returns>The access token</returns>
    public static string GenerateActiveDirectoryAccessToken(string url)
    {
        var authority = AuthorityUrl;
        var authContext = new AuthenticationContext(authority);
        var credentials = new UserPasswordCredential(UserName, Password);
        var authResult = authContext.AcquireTokenAsync(url, ClientId, credentials);
        return authResult.Result.AccessToken;
    }
like image 885
ToFo Avatar asked Mar 16 '18 12:03

ToFo


1 Answers

Are you using .NET Core? The UserPasswordCredential is not supported in .NET Core. FYI: https://github.com/AzureAD/azure-activedirectory-library-for-dotnet/issues/482

I also faced this issue. Hardcoding the username and the password is not a recommended way and you can use the application permissions instead of the delegated permissions. But sometimes some APIs need the delegated permissions. So I want to implement a no-user interaction method to call the Graph APIs. It looks like a deadlock.

like image 84
yanxiaodi Avatar answered Sep 18 '22 01:09

yanxiaodi