Alan Alan - 2 months ago 10
C# Question

Cannot port Lambda function back to normal function

I am authenticating to an azure active directory using the following snippet:

//Client ID values
string applicationId = ***;
string applicationSecret = ***;

var client = new KeyVaultClient
(
async (authority, resource, scope) =>
{
var adCredential = new ClientCredential(applicationId, applicationSecret);
var authenticationContext = new AuthenticationContext(authority, null);
return (await authenticationContext.AcquireTokenAsync(resource, adCredential)).AccessToken;
}
);


This creates a KeyVaultClient which is authenticated to the directory.

My problem is that when I try to move this lambda function into a regular function, something like this:

string authority = "";
ClientCredential adCredential = new ClientCredential(applicationId, applicationSecret);
AuthenticationContext authenticationContext = new AuthenticationContext(authority, null);


And this is where my problem seems to lie. The AuthenticationContext cannot be setup because the authority string is blank. But how can this possibly work in the lambda function and not outside it, it looks to me like the authority string is blank in the lambda function also? The project in question was created for testing, so it doesn't have any definitions that it could be using. Does anybody know what is going on that allows the lambda to work??

Answer Source

The equivalent of your code without the lambda is below

public static async Task<string> AuthenticationCallback(string authority, string resource, string scope) {
    var adCredential = new ClientCredential(applicationId, applicationSecret);
    var authenticationContext = new AuthenticationContext(authority, null);
    return (await authenticationContext.AcquireTokenAsync(resource, adCredential)).AccessToken;
}

var client = new KeyVaultClient(AuthenticationCallback);

Remember that the KeyVaultClient expects a KeyVaultClient.AuthenticationCallback Delegate as the argument.

Not sure why you are replacing a lambda (equivalent of call to a function) with inline lines of code - of course the lambda will be called at some later point with relevant arguments whereas your inline code is executed right at the site (which is not clearly specified in your question)