Skip to content

Commit

Permalink
dotnet-msidentity 2.0.1 servicing update (#2197)
Browse files Browse the repository at this point in the history
* output error for app registrations, and formatting nit (#2129)

* Fix output for app registrations (#2144)

Adding issue: #2146

* Log token authentication failure to JsonResponse, Refactor getting app registrations (#2149)

* Refactor getting app registrations

* Fix test

* Refactor ConsoleLogger failure logging

* Fix newline (#2181)

* bumping dotnet-msidentity version

* Refactor console logger and catch app provisioning exceptions (#2189)

* Refactor console logger

* Exit environment after logging failure

* Add try/catch to app registration creation

* Refactor LogFailure to LogFailureAndExit

Co-authored-by: Zachary Halzel <zahalzel@microsoft.com>
  • Loading branch information
deepchoudhery and zahalzel committed Jan 6, 2023
1 parent bb994a3 commit c2dc990
Show file tree
Hide file tree
Showing 16 changed files with 515 additions and 349 deletions.
2 changes: 1 addition & 1 deletion eng/Versions.MSIdentity.props
Expand Up @@ -6,7 +6,7 @@
<UsingToolNetFrameworkReferenceAssemblies>true</UsingToolNetFrameworkReferenceAssemblies>
</PropertyGroup>
<PropertyGroup>
<VersionPrefix>2.0.0</VersionPrefix>
<VersionPrefix>2.0.1</VersionPrefix>
<PreReleaseVersionLabel>rtm</PreReleaseVersionLabel>
<IsServicingBuild Condition="'$(PreReleaseVersionLabel)' == 'servicing'">true</IsServicingBuild>
<!--
Expand Down
Expand Up @@ -50,8 +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));
return;
_consoleLogger.LogFailureAndExit(errorMsg);
}

_toolOptions.ProjectFilePath = csProjFiles.First();
Expand Down Expand Up @@ -89,7 +88,7 @@ public async Task AddAuthCodeAsync()
await HandleCodeFileAsync(file, project, options, codeModifierConfig.Identifier);
}

_consoleLogger.LogJsonMessage(new JsonResponse(Commands.UPDATE_PROJECT_COMMAND, State.Success, output: _output.ToString().TrimEnd()));
_consoleLogger.LogJsonMessage(State.Success, output: _output.ToString().TrimEnd());
}

internal static string GetCodeFileString(CodeFile file, string identifier) // todo make all code files strings
Expand Down Expand Up @@ -306,7 +305,7 @@ private async Task HandleCodeFileAsync(CodeFile file, CodeAnalysis.Project proje
break;
}

_output.Append(string.Format(Resources.ModifiedCodeFile, file.FileName));
_output.AppendLine(string.Format(Resources.ModifiedCodeFile, file.FileName));
}
}
catch (Exception e)
Expand Down
@@ -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
@@ -1,15 +1,16 @@
// 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.Properties;
using Microsoft.DotNet.MSIdentity.Shared;
using Microsoft.Identity.Client;
using Microsoft.Identity.Client.Extensions.Msal;

namespace Microsoft.DotNet.MSIdentity.DeveloperCredentials
{
Expand All @@ -19,11 +20,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 +106,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.LogFailureAndExit(
$"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 @@ -109,24 +119,30 @@ public override async ValueTask<AccessToken> GetTokenAsync(TokenRequestContext r
}
catch (MsalServiceException ex)
{
// AAD error codes: https://learn.microsoft.com/en-us/azure/active-directory/develop/reference-aadsts-error-codes
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. ");
Environment.Exit(1); // we want to exit here because this is probably an MSA without an AAD tenant.
// We want to exit here because this is probably an MSA without an AAD tenant.
_consoleLogger.LogFailureAndExit(
"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. ");
}

Console.WriteLine("Error encountered with sign-in. See error message for details:\n{0} ",
ex.Message);
Environment.Exit(1); // we want to exit here. Re-sign in will not resolve the issue.
// we want to exit here. Re-sign in will not resolve the issue.
_consoleLogger.LogFailureAndExit(string.Join(Environment.NewLine, Resources.SignInError, ex.Message));
}
catch (Exception ex)
{
Console.WriteLine("Error encountered with sign-in. See error message for details:\n{0} ",
ex.Message);
Environment.Exit(1);
_consoleLogger.LogFailureAndExit(string.Join(Environment.NewLine, Resources.SignInError, ex.Message));
}
return new AccessToken(result.AccessToken, result.ExpiresOn);

if (result is null)
{
_consoleLogger.LogFailureAndExit(Resources.FailedToAcquireToken);
}

return new AccessToken(result!.AccessToken, result.ExpiresOn);
}
}
}

0 comments on commit c2dc990

Please sign in to comment.