Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Changes for msidentity minimal hosting scenario #1650

Merged
merged 3 commits into from
Sep 29, 2021
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
18 changes: 9 additions & 9 deletions eng/Versions.props
Original file line number Diff line number Diff line change
Expand Up @@ -31,11 +31,11 @@
<!-- Microsoft.Build.Utilities-->
<MicrosoftBuildUtilitiesCorePackageVersion>16.9.0 </MicrosoftBuildUtilitiesCorePackageVersion>
<!-- Microsoft.CodeAnalysis.CSharp -->
<MicrosoftCodeAnalysisCSharpPackageVersion>4.0.0-3.final</MicrosoftCodeAnalysisCSharpPackageVersion>
<MicrosoftCodeAnalysisCSharpPackageVersion>4.0.0-4.final</MicrosoftCodeAnalysisCSharpPackageVersion>
<!-- Microsoft.CodeAnalysis.Razor -->
<MicrosoftCodeAnalysisRazorPackageVersion>6.0.0-rc.1.21452.15</MicrosoftCodeAnalysisRazorPackageVersion>
<!-- Microsoft.CodeAnalysis.CSharp.Workspaces -->
<MicrosoftCodeAnalysisCSharpWorkspacesPackageVersion>4.0.0-3.final</MicrosoftCodeAnalysisCSharpWorkspacesPackageVersion>
<MicrosoftCodeAnalysisCSharpWorkspacesPackageVersion>4.0.0-4.final</MicrosoftCodeAnalysisCSharpWorkspacesPackageVersion>
<!-- Microsoft.Extensions.CommandLineUtils.Sources -->
<MicrosoftExtensionsCommandLineUtilsSourcesPackageVersion>6.0.0-preview.3.21166.3</MicrosoftExtensionsCommandLineUtilsSourcesPackageVersion>
<!-- Microsoft.EntityFrameworkCore.Design -->
Expand Down Expand Up @@ -118,16 +118,16 @@
</PropertyGroup>
<!-- Package versions for MSIdentity projects-->
<PropertyGroup>
<AzureIdentityVersion>1.3.0</AzureIdentityVersion>
<CodeAnalysisVersion>4.0.0-3.final</CodeAnalysisVersion>
<AzureIdentityVersion>1.4.1</AzureIdentityVersion>
<CodeAnalysisVersion>4.0.0-4.final</CodeAnalysisVersion>
<MicrosoftExtensionsConfigurationVersion>3.1.9</MicrosoftExtensionsConfigurationVersion>
<MicrosoftExtensionsConfigurationBinderVersion>3.1.9</MicrosoftExtensionsConfigurationBinderVersion>
<MicrosoftExtensionsConfigurationCommandLineVersion>3.1.9</MicrosoftExtensionsConfigurationCommandLineVersion>
<MicrosoftGraphVersion>3.25.0</MicrosoftGraphVersion>
<MicrosoftIdentityClientExtensionsMsalVersion>2.18.0</MicrosoftIdentityClientExtensionsMsalVersion>
<NuGetProjectModelVersion>5.9.1</NuGetProjectModelVersion>
<SystemTextJsonVersion>4.7.2</SystemTextJsonVersion>
<SystemCommandLineVersion>2.0.0-beta1.20574.7</SystemCommandLineVersion>
<MicrosoftGraphVersion>4.5.0</MicrosoftGraphVersion>
<MicrosoftIdentityClientExtensionsMsalVersion>2.19.1</MicrosoftIdentityClientExtensionsMsalVersion>
<NuGetProjectModelVersion>5.11.0</NuGetProjectModelVersion>
<SystemTextJsonVersion>5.0.2</SystemTextJsonVersion>
<SystemCommandLineVersion>2.0.0-beta1.21308.1</SystemCommandLineVersion>
<NewtonsoftJsonMsIdentityPackageVersion>13.0.1</NewtonsoftJsonMsIdentityPackageVersion>
</PropertyGroup>
</Project>
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,29 @@
"Microsoft.AspNetCore.Authentication.JwtBearer"
]
},
{
"FileName": "Program.cs",
"Methods": {
"Global": {
"CodeChanges": [
{
"Block": "\nWebApplication.CreateBuilder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)\n .AddMicrosoftIdentityWebApi(builder.Configuration.GetSection(\"AzureAd\"));",
"InsertBefore": [ "builder.Services.AddControllers()", "builder.Build()" ]
},
{
"InsertAfter": "app.UseRouting();",
"Block": "app.UseAuthentication();",
"InsertBefore": [ "app.UseAuthorization();", "app.Run();" ]
}
]
}
},
"Usings": [
"Microsoft.AspNetCore.Authentication",
"Microsoft.Identity.Web",
"Microsoft.AspNetCore.Authentication.JwtBearer"
]
},
{
"FileName": "WeatherForecastController.cs",
"ClassAttributes": [ "Authorize" ],
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,47 @@
"Microsoft.AspNetCore.Authorization",
"Microsoft.AspNetCore.Mvc.Authorization"
]
},
{
"FileName": "Program.cs",
"Methods": {
"Global": {
"CodeChanges": [
{
"Block":"\nWebApplication.CreateBuilder.Services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)\n .AddMicrosoftIdentityWebApp(builder.Configuration.GetSection(\"AzureAd\"));",
"InsertBefore": [ "builder.Services.AddAuthorization", "builder.Services.AddRazorPages()", "builder.Build()" ]
},
{
"Block":"\nWebApplication.CreateBuilder.Services.AddAuthorization(options =>\n{\n options.FallbackPolicy = options.DefaultPolicy;\n});\n\r",
"InsertAfter":"builder.Services.AddAuthentication",
"InsertBefore": ["builder.Services.AddRazorPages()", "builder.Build()"]
},
{
"Parent": "WebApplication.CreateBuilder.Services.AddRazorPages()",
"Type": "MemberAccess",
"Block": "AddMicrosoftIdentityUI()"
},
{
"InsertAfter": "app.UseRouting();",
"Block": "app.UseAuthentication();",
"InsertBefore": [ "app.UseAuthorization();", "app.Run();" ]
},
{
"InsertAfter": "app.MapRazorPages();",
"Block": "app.MapControllers();",
"InsertBefore": [ "app.Run();" ]
}
]
}
},
"Usings": [
"Microsoft.AspNetCore.Authentication",
"Microsoft.Identity.Web",
"Microsoft.Identity.Web.UI",
"Microsoft.AspNetCore.Authentication.OpenIdConnect",
"Microsoft.AspNetCore.Authorization",
"Microsoft.AspNetCore.Mvc.Authorization"
]
}
]
}
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,7 @@ public static void InitUserSecrets(string projectPath, IConsoleLogger consoleLog
}
else
{
consoleLogger.LogMessage(Resources.Success, removeNewLine: true);
consoleLogger.LogMessage($"{Resources.Success}\n\n", removeNewLine: true);
}
}

Expand Down Expand Up @@ -133,12 +133,12 @@ public static void AddPackage(string packageName, string tfm, IConsoleLogger con

if (result.ExitCode != 0)
{
consoleLogger.LogMessage(Resources.Success, removeNewLine: true);
consoleLogger.LogMessage($"{Resources.Success}\n\n", removeNewLine: true);
consoleLogger.LogMessage(string.Format(Resources.FailedAddPackage, packageName));
}
else
{
consoleLogger.LogMessage(Resources.Success);
consoleLogger.LogMessage($"{Resources.Success}\n\n");
}
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
using Microsoft.DotNet.MSIdentity.Shared;
using Microsoft.DotNet.MSIdentity.Tool;
using Microsoft.DotNet.Scaffolding.Shared.CodeModifier;
using Microsoft.DotNet.Scaffolding.Shared.CodeModifier.CodeChange;
using Microsoft.DotNet.Scaffolding.Shared.Project;

namespace Microsoft.DotNet.MSIdentity.CodeReaderWriter
Expand Down Expand Up @@ -49,68 +50,134 @@ public async Task AddAuthCodeAsync()
//Initialize CodeAnalysis.Project wrapper
CodeAnalysis.Project project = await CodeAnalysisHelper.LoadCodeAnalysisProjectAsync(_toolOptions.ProjectFilePath);

//is minimal project
var isMinimalApp = await ProjectModifierHelper.IsMinimalApp(project);

//Go through all the files, make changes using DocumentBuilder.
foreach (var file in codeModifierConfig.Files)
{
var fileName = file.FileName;
string className = ProjectModifierHelper.GetClassName(fileName);

//if the file we are modifying is Startup.cs, use Program.cs to find the correct file to edit.
if (!string.IsNullOrEmpty(file.FileName) && file.FileName.Equals("Startup.cs", StringComparison.OrdinalIgnoreCase))
if (!string.IsNullOrEmpty(fileName) && fileName.Equals("Startup.cs", StringComparison.OrdinalIgnoreCase))
{
fileName = await ProjectModifierHelper.GetStartupClass(_toolOptions.ProjectPath, project);
}

if (!string.IsNullOrEmpty(fileName))
if (!string.IsNullOrEmpty(fileName) && !fileName.Equals("Program.cs"))
{
await ModifyCsFile(fileName, file, project);
}
// if file is Program.cs
else if (!string.IsNullOrEmpty(fileName) && fileName.Equals("Program.cs"))
{
string? filePath = Directory.EnumerateFiles(_toolOptions.ProjectPath, fileName, SearchOption.AllDirectories).FirstOrDefault();
//get the file document to get the document root for editing.

if (!string.IsNullOrEmpty(filePath))
//only modify Program.cs file if its a minimal hosting app (as we made changes to the Startup.cs file).
if (isMinimalApp)
{
var fileDoc = project.Documents.Where(d => d.Name.Equals(filePath)).FirstOrDefault();
DocumentEditor documentEditor = await DocumentEditor.CreateAsync(fileDoc);
DocumentBuilder documentBuilder = new DocumentBuilder(documentEditor, file, _consoleLogger);
var docRoot = documentEditor.OriginalRoot as CompilationUnitSyntax;
//adding usings
var newRoot = documentBuilder.AddUsings();
var namespaceNode = newRoot?.Members.OfType<NamespaceDeclarationSyntax>()?.FirstOrDefault();

//get classNode. All class changes are done on the ClassDeclarationSyntax and then that node is replaced using documentEditor.
var classNode = namespaceNode?
.DescendantNodes()?
.Where(node =>
node is ClassDeclarationSyntax cds &&
cds.Identifier.ValueText.Contains(className))
.FirstOrDefault();

if (classNode is ClassDeclarationSyntax classDeclarationSyntax)
{
var modifiedClassDeclarationSyntax = classDeclarationSyntax;

//add class properties
modifiedClassDeclarationSyntax = documentBuilder.AddProperties(modifiedClassDeclarationSyntax);
//add class attributes
modifiedClassDeclarationSyntax = documentBuilder.AddClassAttributes(modifiedClassDeclarationSyntax);

//add code snippets/changes.
if (file.Methods != null && file.Methods.Any())
{
modifiedClassDeclarationSyntax = documentBuilder.AddCodeSnippets(file, modifiedClassDeclarationSyntax); ;
}
//replace class node with all the updates.
documentEditor.ReplaceNode(classDeclarationSyntax, modifiedClassDeclarationSyntax);
}
await ModifyProgramCs(file, project);
}
}
}
}
}
}

/// <summary>
/// Modify Program.cs file to add changes specified in the CodeFile.
/// </summary>
/// <param name="programCsFile"></param>
/// <param name="project"></param>
/// <returns></returns>
internal async Task ModifyProgramCs(CodeFile programCsFile, CodeAnalysis.Project project)
{
string? programCsFilePath = Directory.EnumerateFiles(_toolOptions.ProjectPath, "Program.cs", SearchOption.AllDirectories).FirstOrDefault();
if (!string.IsNullOrEmpty(programCsFilePath))
{
var programDocument = project.Documents.Where(d => d.Name.Equals(programCsFilePath)).FirstOrDefault();
DocumentEditor documentEditor = await DocumentEditor.CreateAsync(programDocument);
DocumentBuilder documentBuilder = new DocumentBuilder(documentEditor, programCsFile, _consoleLogger);
var docRoot = documentEditor.OriginalRoot as CompilationUnitSyntax;
if (docRoot != null && programDocument != null)
{
//get builder variable
var variableDict = ProjectModifierHelper.GetBuilderVariableIdentifier(docRoot.Members);
//add usings
var newRoot = documentBuilder.AddUsings();

if (docRoot != null && newRoot != null)
//add code snippets/changes.
if (programCsFile.Methods != null && programCsFile.Methods.Any())
{
var globalChanges = programCsFile.Methods.TryGetValue("Global", out var globalMethod);
if (globalMethod != null)
{
foreach (var change in globalMethod.CodeChanges)
{
//format CodeChange.Block and CodeChange.Parent for any variables or parameters.
change.Block = ProjectModifierHelper.FormatGlobalStatement(change.Block, variableDict);
if (!string.IsNullOrEmpty(change.Parent))
{
documentEditor.ReplaceNode(docRoot, newRoot);
change.Parent = ProjectModifierHelper.FormatGlobalStatement(change.Parent, variableDict);
}
await documentBuilder.WriteToClassFileAsync(fileName, filePath);
newRoot = DocumentBuilder.AddGlobalStatements(change, newRoot);
}
}

}
//replace root node with all the updates.
documentEditor.ReplaceNode(docRoot, newRoot);
//write to Program.cs file
await documentBuilder.WriteToClassFileAsync(programDocument.Name, programCsFilePath);
}
}
}

internal async Task ModifyCsFile(string fileName, CodeFile file, CodeAnalysis.Project project)
{
string className = ProjectModifierHelper.GetClassName(fileName);
string? filePath = Directory.EnumerateFiles(_toolOptions.ProjectPath, fileName, SearchOption.AllDirectories).FirstOrDefault();
//get the file document to get the document root for editing.

if (!string.IsNullOrEmpty(filePath))
{
var fileDoc = project.Documents.Where(d => d.Name.Equals(filePath)).FirstOrDefault();
DocumentEditor documentEditor = await DocumentEditor.CreateAsync(fileDoc);
DocumentBuilder documentBuilder = new DocumentBuilder(documentEditor, file, _consoleLogger);
var docRoot = documentEditor.OriginalRoot as CompilationUnitSyntax;
//adding usings
var newRoot = documentBuilder.AddUsings();
var namespaceNode = newRoot?.Members.OfType<NamespaceDeclarationSyntax>()?.FirstOrDefault();

//get classNode. All class changes are done on the ClassDeclarationSyntax and then that node is replaced using documentEditor.
var classNode = namespaceNode?
.DescendantNodes()?
.Where(node =>
node is ClassDeclarationSyntax cds &&
cds.Identifier.ValueText.Contains(className))
.FirstOrDefault();

if (classNode is ClassDeclarationSyntax classDeclarationSyntax)
{
var modifiedClassDeclarationSyntax = classDeclarationSyntax;

//add class properties
modifiedClassDeclarationSyntax = documentBuilder.AddProperties(modifiedClassDeclarationSyntax);
//add class attributes
modifiedClassDeclarationSyntax = documentBuilder.AddClassAttributes(modifiedClassDeclarationSyntax);

//add code snippets/changes.
if (file.Methods != null && file.Methods.Any())
{
modifiedClassDeclarationSyntax = documentBuilder.AddCodeSnippets(file, modifiedClassDeclarationSyntax); ;
}
//replace class node with all the updates.
documentEditor.ReplaceNode(classDeclarationSyntax, modifiedClassDeclarationSyntax);
}

if (docRoot != null && newRoot != null)
{
documentEditor.ReplaceNode(docRoot, newRoot);
}
await documentBuilder.WriteToClassFileAsync(fileName, filePath);
}
}

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 @@ -203,7 +203,7 @@
<value>Specify one .csproj file for the --project-path</value>
</data>
<data name="Success" xml:space="preserve">
<value>SUCCESS\n\n</value>
<value>SUCCESS</value>
</data>
<data name="Summary" xml:space="preserve">
<value>Summary</value>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ internal class MsAADTool : IMsAADTool
internal IConsoleLogger ConsoleLogger { get; }
private ProvisioningToolOptions ProvisioningToolOptions { get; set; }
private string CommandName { get; }
public IGraphServiceClient GraphServiceClient { get; set; }
public GraphServiceClient GraphServiceClient { get; set; }
public IAzureManagementAuthenticationProvider AzureManagementAPI { get; set;}
private MsalTokenCredential TokenCredential { get; set; }

Expand Down
1 change: 1 addition & 0 deletions src/Scaffolding/VS.Web.CG.Design/CodeGenCommandExecutor.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
using Microsoft.VisualStudio.Web.CodeGeneration.Templating;
using Microsoft.VisualStudio.Web.CodeGeneration.Templating.Compilation;
using Microsoft.VisualStudio.Web.CodeGeneration.Utils;
using Microsoft.DotNet.Scaffolding.Shared.Project;

namespace Microsoft.VisualStudio.Web.CodeGeneration.Design
{
Expand Down
1 change: 1 addition & 0 deletions src/Scaffolding/VS.Web.CG.EFCore/CodeModelService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.DotNet.Scaffolding.Shared;
using Microsoft.DotNet.Scaffolding.Shared.Project;
using Microsoft.DotNet.Scaffolding.Shared.ProjectModel;
using Microsoft.VisualStudio.Web.CodeGeneration.DotNet;

Expand Down
Loading