public static async Task <string> GetAuthTokenByUserCredentialsInteractiveAsync(Settings input) { var resource = GetResourceUrl(input); if (string.IsNullOrWhiteSpace(input.Tenant) || string.IsNullOrWhiteSpace(input.ClientId) || string.IsNullOrWhiteSpace(resource) || string.IsNullOrWhiteSpace(input.ReplyUrl)) { throw new ArgumentException($"To use the User-credentials interactive-flow, please provide valid Tenant, ClientId, ResourceUrl, ReplyUrl in '{input.AppSettingsFile}'"); } var accessToken = await AuthTokens.GetOrAdd(input.Tenant ?? string.Empty, k => { return(new Lazy <Task <string> >(async() => { var ctx = GetAuthenticationContext(input.Tenant); Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationResult result = null; var promptBehavior = new PlatformParameters(PromptBehavior.SelectAccount, new CustomWebUi()); ColorConsole.Write("Authenticating...\n"); try { result = await ctx.AcquireTokenAsync(resource, input.ClientId, new Uri(input.ReplyUrl), promptBehavior); } catch (UnauthorizedAccessException) { // If the token has expired, prompt the user with a login prompt result = await ctx.AcquireTokenAsync(resource, input.ClientId, new Uri(input.ReplyUrl), promptBehavior); } return result?.AccessToken; })); }).Value; return(accessToken); }
public static async Task <string> GetAuthToken(string tenantId) { var accessToken = await AuthTokens.GetOrAdd(tenantId ?? string.Empty, k => { return(new Lazy <Task <string> >(async() => { var ctx = GetAuthenticationContext(tenantId); Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationResult result = null; var promptBehavior = new PlatformParameters(PromptBehavior.SelectAccount, new CustomWebUi()); Console.Write("Authenticating...\n"); try { result = await ctx.AcquireTokenAsync(ResourceId, ClientId, new Uri(ReplyUri), promptBehavior); } catch (UnauthorizedAccessException) { // If the token has expired, prompt the user with a login prompt result = await ctx.AcquireTokenAsync(ResourceId, ClientId, new Uri(ReplyUri), promptBehavior); } return result?.AccessToken; })); }).Value; return(accessToken); }