Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ public async Task AddAuthCodeAsync()
if (csProjFiles.Count() != 1)
{
var errorMsg = string.Format(Resources.ProjectPathError, _toolOptions.ProjectFilePath);
_consoleLogger.LogJsonMessage(new JsonResponse(Commands.UPDATE_PROJECT_COMMAND, State.Fail, output: errorMsg));
_consoleLogger.LogFailure(errorMsg, Commands.UPDATE_PROJECT_COMMAND);
return;
}

Expand Down
Original file line number Diff line number Diff line change
@@ -1,13 +1,14 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

using Azure.Core;
using Microsoft.DotNet.MSIdentity.Shared;

namespace Microsoft.DotNet.MSIdentity.DeveloperCredentials
{
public class DeveloperCredentialsReader
{
public TokenCredential GetDeveloperCredentials(string? username, string? currentApplicationTenantId)
public TokenCredential GetDeveloperCredentials(string? username, string? currentApplicationTenantId, IConsoleLogger consoleLogger)
{
#if AzureSDK
* Tried but does not work if another tenant than the home tenant id is specified
Expand All @@ -28,7 +29,8 @@ public TokenCredential GetDeveloperCredentials(string? username, string? current
#endif
TokenCredential tokenCredential = new MsalTokenCredential(
currentApplicationTenantId,
username);
username,
consoleLogger);
return tokenCredential;
}
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,15 +1,15 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

using Azure.Core;
using Microsoft.Graph;
using Microsoft.Identity.Client;
using Microsoft.Identity.Client.Extensions.Msal;
using System;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Azure.Core;
using Microsoft.DotNet.MSIdentity.Shared;
using Microsoft.Identity.Client;
using Microsoft.Identity.Client.Extensions.Msal;

namespace Microsoft.DotNet.MSIdentity.DeveloperCredentials
{
Expand All @@ -19,11 +19,17 @@ public class MsalTokenCredential : TokenCredential
private const string RedirectUri = "http://localhost";
#pragma warning restore S1075 // URIs should not be hardcoded

public MsalTokenCredential(string? tenantId, string? username, string instance = "https://login.microsoftonline.com")
private readonly IConsoleLogger _consoleLogger;

public MsalTokenCredential(
string? tenantId,
string? username,
IConsoleLogger consoleLogger)
{
_consoleLogger = consoleLogger;
TenantId = tenantId ?? "organizations"; // MSA-passthrough
Username = username;
Instance = instance;
Instance = "https://login.microsoftonline.com";
}

private IPublicClientApplication? App { get; set; }
Expand Down Expand Up @@ -99,7 +105,10 @@ public override async ValueTask<AccessToken> GetTokenAsync(TokenRequestContext r
{
if (account == null && !string.IsNullOrEmpty(Username))
{
Console.WriteLine($"No valid tokens found in the cache.\nPlease sign-in to Visual Studio with this account:\n\n{Username}.\n\nAfter signing-in, re-run the tool.\n");
_consoleLogger.LogFailure(
$"No valid tokens found in the cache.\n" +
$"Please sign-in to Visual Studio with this account: {Username}.\n\n" +
$"After signing-in, re-run the tool.");
}
result = await app.AcquireTokenInteractive(requestContext.Scopes)
.WithAccount(account)
Expand All @@ -111,19 +120,19 @@ public override async ValueTask<AccessToken> GetTokenAsync(TokenRequestContext r
{
if (ex.Message.Contains("AADSTS70002")) // "The client does not exist or is not enabled for consumers"
{
Console.WriteLine("An Azure AD tenant, and a user in that tenant, " +
"needs to be created for this account before an application can be created. See https://aka.ms/ms-identity-app/create-a-tenant. ");
_consoleLogger.LogFailure(
"An Azure AD tenant, and a user in that tenant, " +
"needs to be created for this account before an application can be created. " +
"See https://aka.ms/ms-identity-app/create-a-tenant. ");
Environment.Exit(1); // we want to exit here because this is probably an MSA without an AAD tenant.
}

Console.WriteLine("Error encountered with sign-in. See error message for details:\n{0} ",
ex.Message);
_consoleLogger.LogFailure($"Error encountered with sign-in. See error message for details:\n{ex.Message}");
Environment.Exit(1); // we want to exit here. Re-sign in will not resolve the issue.
}
catch (Exception ex)
{
Console.WriteLine("Error encountered with sign-in. See error message for details:\n{0} ",
ex.Message);
_consoleLogger.LogFailure($"Error encountered with sign-in. See error message for details:\n{ex.Message}");
Environment.Exit(1);
}
return new AccessToken(result.AccessToken, result.ExpiresOn);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@ public class MicrosoftIdentityPlatformApplicationManager

if (createdSp is null)
{
consoleLogger.LogJsonMessage(new JsonResponse(commandName, State.Fail, output: Resources.FailedToGetServicePrincipal));
consoleLogger.LogFailure(Resources.FailedToGetServicePrincipal, commandName);
return null;
}

Expand All @@ -107,7 +107,7 @@ public class MicrosoftIdentityPlatformApplicationManager
// log json console message inside this method since we need the Microsoft.Graph.Application
if (createdApplication is null)
{
consoleLogger.LogJsonMessage(new JsonResponse(commandName, State.Fail, output: Resources.FailedToCreateApp));
consoleLogger.LogFailure(Resources.FailedToCreateApp, commandName);
return null;
}

Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

using Azure.Core;
Expand Down Expand Up @@ -31,7 +31,6 @@ public TokenCredentialAuthenticationProvider(
public async Task AuthenticateRequestAsync(HttpRequestMessage request)
{
// Try with the Shared token cache credentials

TokenRequestContext context = new TokenRequestContext(_initialScopes.ToArray());
AccessToken token = await _tokenCredentials.GetTokenAsync(context, CancellationToken.None);

Expand Down

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Original file line number Diff line number Diff line change
Expand Up @@ -250,6 +250,9 @@
<value>Failed to modify code file {0}, {1} </value>
<comment>0 = File name, 1 = Exception message</comment>
</data>
<data name="FailedToProvisionClientApp" xml:space="preserve">
<value>Failed to provision Client Application</value>
</data>
<data name="FailedToRetrieveADObjectsError" xml:space="preserve">
<value>Failed to retrieve all Azure AD/AD B2C objects(apps/service principals</value>
</data>
Expand All @@ -261,6 +264,9 @@
<value>Failed to update Azure AD app, null {0}</value>
<comment>0 = null object</comment>
</data>
<data name="FailedToUpdateClientAppCode" xml:space="preserve">
<value>Failed to update client app program.cs file</value>
</data>
<data name="InitializeUserSecrets" xml:space="preserve">
<value>Initializing User Secrets . . .</value>
</data>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ public AppProvisioningTool(string commandName, ProvisioningToolOptions provision
if (projectDescription == null)
{
var errorMessage = string.Format(Resources.NoProjectDescriptionFound, ProvisioningToolOptions.ProjectTypeIdentifier);
ConsoleLogger.LogJsonMessage(new JsonResponse(CommandName, State.Fail, output: errorMessage));
ConsoleLogger.LogFailure(errorMessage, CommandName);
Environment.Exit(1);
}

Expand All @@ -74,7 +74,8 @@ public AppProvisioningTool(string commandName, ProvisioningToolOptions provision
// Get developer credentials
TokenCredential tokenCredential = GetTokenCredential(
ProvisioningToolOptions,
ProvisioningToolOptions.TenantId ?? projectSettings.ApplicationParameters.EffectiveTenantId ?? projectSettings.ApplicationParameters.EffectiveDomain);
ProvisioningToolOptions.TenantId ?? projectSettings.ApplicationParameters.EffectiveTenantId ?? projectSettings.ApplicationParameters.EffectiveDomain,
ConsoleLogger);

ApplicationParameters applicationParameters;
switch (CommandName)
Expand Down Expand Up @@ -177,7 +178,7 @@ private bool ValidateProjectPath()
}

var errorMsg = string.Format(Resources.ProjectPathError, ProvisioningToolOptions.ProjectFilePath);
ConsoleLogger.LogJsonMessage(new JsonResponse(CommandName, State.Fail, output: errorMsg));
ConsoleLogger.LogFailure(errorMsg, CommandName);
return false;
}

Expand Down Expand Up @@ -230,12 +231,13 @@ private ProjectAuthenticationSettings InferApplicationParameters(
/// <param name="provisioningToolOptions"></param>
/// <param name="currentApplicationTenantId"></param>
/// <returns></returns>
internal static TokenCredential GetTokenCredential(ProvisioningToolOptions provisioningToolOptions, string? currentApplicationTenantId)
internal static TokenCredential GetTokenCredential(ProvisioningToolOptions provisioningToolOptions, string? currentApplicationTenantId, IConsoleLogger consoleLogger)
{
DeveloperCredentialsReader developerCredentialsReader = new DeveloperCredentialsReader();
return developerCredentialsReader.GetDeveloperCredentials(
provisioningToolOptions.Username,
currentApplicationTenantId ?? provisioningToolOptions.TenantId);
currentApplicationTenantId ?? provisioningToolOptions.TenantId,
consoleLogger);
}

/// <summary>
Expand Down Expand Up @@ -296,6 +298,12 @@ private async Task UpdateAppRegistration(TokenCredential tokenCredential, Applic
}

var clientApplicationParameters = await ConfigureBlazorWasmHostedClientAsync(serverApplicationParameters: applicationParameters);
if (clientApplicationParameters is null)
{
ConsoleLogger.LogFailure("Failed to provision Blazor Wasm hosted scenario");
Environment.Exit(1);
}

ProvisioningToolOptions.BlazorWasmClientAppId = clientApplicationParameters.ClientId;
output.AppendLine(string.Format(Resources.ConfiguredBlazorWasmClient, clientApplicationParameters.ApplicationDisplayName, clientApplicationParameters.ClientId));
}
Expand All @@ -317,7 +325,7 @@ private async Task UpdateAppRegistration(TokenCredential tokenCredential, Applic
/// <param name="serverApplicationParameters"></param>
/// <returns></returns>
/// <exception cref="ArgumentNullException"></exception>
private async Task<ApplicationParameters> ConfigureBlazorWasmHostedClientAsync(ApplicationParameters serverApplicationParameters)
private async Task<ApplicationParameters?> ConfigureBlazorWasmHostedClientAsync(ApplicationParameters serverApplicationParameters)
{
// Processes the Blazorwasm client
var clientToolOptions = ProvisioningToolOptions.Clone();
Expand All @@ -337,10 +345,8 @@ private async Task<ApplicationParameters> ConfigureBlazorWasmHostedClientAsync(A
var clientApplicationParameters = await provisionClientAppRegistration.Run();
if (clientApplicationParameters == null)
{
var exception = new ArgumentNullException(nameof(clientApplicationParameters));

ConsoleLogger.LogJsonMessage(new JsonResponse(CommandName, State.Fail, output: exception.Message));
throw exception;
ConsoleLogger.LogFailure(Resources.FailedToProvisionClientApp, CommandName);
return null;
}

// Update program.cs file
Expand All @@ -349,10 +355,8 @@ private async Task<ApplicationParameters> ConfigureBlazorWasmHostedClientAsync(A
clientApplicationParameters = await updateCode.Run();
if (clientApplicationParameters == null)
{
var exception = new ArgumentNullException(nameof(clientApplicationParameters));

ConsoleLogger.LogJsonMessage(new JsonResponse(CommandName, State.Fail, output: exception.Message));
throw exception;
ConsoleLogger.LogFailure(Resources.FailedToUpdateClientAppCode, CommandName);
return null;
}

return clientApplicationParameters;
Expand Down
Loading