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

Adds the ability to specify an appsettings file for user-jwts #58605

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
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
36 changes: 29 additions & 7 deletions src/Tools/dotnet-user-jwts/src/Commands/ClearCommand.cs
Original file line number Diff line number Diff line change
Expand Up @@ -19,21 +19,43 @@ public static void Register(ProjectCommandLineApplication app)
Resources.ClearCommand_ForceOption_Description,
CommandOptionType.NoValue);

var appsettingsFileOption = cmd.Option(
"--appsettings-file",
Resources.CreateCommand_appsettingsFileOption_Description,
CommandOptionType.SingleValue);

cmd.HelpOption("-h|--help");

cmd.OnExecute(() =>
{
return Execute(cmd.Reporter, cmd.ProjectOption.Value(), forceOption.HasValue());
if (!DevJwtCliHelpers.GetProjectAndSecretsId(cmd.ProjectOption.Value(), cmd.Reporter, out var project, out var userSecretsId))
{
return 1;
}

var appsettingsFile = "appsettings.Development.json";
if (appsettingsFileOption.HasValue())
{
appsettingsFile = appsettingsFileOption.Value();
if (!appsettingsFile.EndsWith(".json", StringComparison.OrdinalIgnoreCase))
{
cmd.Reporter.Error(Resources.RemoveCommand_InvalidAppsettingsFile_Error);
return 1;
}
else if (!File.Exists(Path.Combine(Path.GetDirectoryName(project), appsettingsFile)))
{
cmd.Reporter.Error(Resources.FormatRemoveCommand_AppsettingsFileNotFound_Error(Path.GetDirectoryName(project)));
return 1;
}
}

return Execute(cmd.Reporter, project, userSecretsId, forceOption.HasValue(), appsettingsFile);
});
});
}

private static int Execute(IReporter reporter, string projectPath, bool force)
private static int Execute(IReporter reporter, string project, string userSecretsId, bool force, string appsettingsFile)
{
if (!DevJwtCliHelpers.GetProjectAndSecretsId(projectPath, reporter, out var project, out var userSecretsId))
{
return 1;
}
var jwtStore = new JwtStore(userSecretsId);
var count = jwtStore.Jwts.Count;

Expand All @@ -54,7 +76,7 @@ private static int Execute(IReporter reporter, string projectPath, bool force)
}
}

var appsettingsFilePath = Path.Combine(Path.GetDirectoryName(project), "appsettings.Development.json");
var appsettingsFilePath = Path.Combine(Path.GetDirectoryName(project), appsettingsFile);
foreach (var jwt in jwtStore.Jwts)
{
JwtAuthenticationSchemeSettings.RemoveScheme(appsettingsFilePath, jwt.Value.Scheme);
Expand Down
43 changes: 36 additions & 7 deletions src/Tools/dotnet-user-jwts/src/Commands/CreateCommand.cs
Original file line number Diff line number Diff line change
Expand Up @@ -77,24 +77,29 @@ public static void Register(ProjectCommandLineApplication app, Program program)
Resources.CreateCommand_ValidForOption_Description,
CommandOptionType.SingleValue);

var appsettingsFileOption = cmd.Option(
"--appsettings-file",
Resources.CreateCommand_appsettingsFileOption_Description,
CommandOptionType.SingleValue);

cmd.HelpOption("-h|--help");

cmd.OnExecute(() =>
{
var (options, isValid, optionsString) = ValidateArguments(
cmd.Reporter, cmd.ProjectOption, schemeNameOption, nameOption, audienceOption, issuerOption, notBeforeOption, expiresOnOption, validForOption, rolesOption, scopesOption, claimsOption);
var (options, isValid, optionsString, appsettingsFile) = ValidateArguments(
cmd.Reporter, cmd.ProjectOption, schemeNameOption, nameOption, audienceOption, issuerOption, notBeforeOption, expiresOnOption, validForOption, rolesOption, scopesOption, claimsOption, appsettingsFileOption);

if (!isValid)
{
return 1;
}

return Execute(cmd.Reporter, cmd.ProjectOption.Value(), options, optionsString, cmd.OutputOption.Value(), program);
return Execute(cmd.Reporter, cmd.ProjectOption.Value(), options, optionsString, cmd.OutputOption.Value(), appsettingsFile, program);
});
});
}

private static (JwtCreatorOptions, bool, string) ValidateArguments(
private static (JwtCreatorOptions, bool, string, string) ValidateArguments(
IReporter reporter,
CommandOption projectOption,
CommandOption schemeNameOption,
Expand All @@ -106,7 +111,8 @@ private static (JwtCreatorOptions, bool, string) ValidateArguments(
CommandOption validForOption,
CommandOption rolesOption,
CommandOption scopesOption,
CommandOption claimsOption)
CommandOption claimsOption,
CommandOption appsettingsFileOption)
{
var isValid = true;
var finder = new MsBuildProjectFinder(Directory.GetCurrentDirectory());
Expand All @@ -121,6 +127,7 @@ private static (JwtCreatorOptions, bool, string) ValidateArguments(
return (
null,
isValid,
string.Empty,
string.Empty
);
}
Expand Down Expand Up @@ -209,10 +216,31 @@ private static (JwtCreatorOptions, bool, string) ValidateArguments(
optionsString += $"{Resources.JwtPrint_CustomClaims}: [{string.Join(", ", claims.Select(kvp => $"{kvp.Key}={kvp.Value}"))}]{Environment.NewLine}";
}

var appsettingsFile = "appsettings.Development.json";
if (appsettingsFileOption.HasValue())
{
appsettingsFile = appsettingsFileOption.Value();
if (!appsettingsFile.EndsWith(".json", StringComparison.OrdinalIgnoreCase))
{
reporter.Error(Resources.CreateCommand_InvalidAppsettingsFile_Error);
isValid = false;
}
else if (!File.Exists(Path.Combine(Path.GetDirectoryName(project), appsettingsFile)))
{
reporter.Error(Resources.FormatCreateCommand_AppsettingsFileNotFound_Error(Path.GetDirectoryName(project)));
isValid = false;
}
else
{
optionsString += appsettingsFileOption.HasValue() ? $"{Resources.JwtPrint_appsettingsFile}: {appsettingsFile}{Environment.NewLine}" : string.Empty;
}
}

return (
new JwtCreatorOptions(scheme, name, audience, issuer, notBefore, expiresOn, roles, scopes, claims),
isValid,
optionsString);
optionsString,
appsettingsFile);

static bool ParseDate(string datetime, out DateTime parsedDateTime) =>
DateTime.TryParseExact(datetime, _dateTimeFormats, CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal, out parsedDateTime);
Expand All @@ -224,6 +252,7 @@ private static int Execute(
JwtCreatorOptions options,
string optionsString,
string outputFormat,
string appsettingsFile,
Program program)
{
if (!DevJwtCliHelpers.GetProjectAndSecretsId(projectPath, reporter, out var project, out var userSecretsId))
Expand All @@ -244,7 +273,7 @@ private static int Execute(
jwtStore.Jwts.Add(jwtToken.Id, jwt);
jwtStore.Save();

var appsettingsFilePath = Path.Combine(Path.GetDirectoryName(project), "appsettings.Development.json");
var appsettingsFilePath = Path.Combine(Path.GetDirectoryName(project), appsettingsFile);
var settingsToWrite = new JwtAuthenticationSchemeSettings(options.Scheme, options.Audiences, options.Issuer);
settingsToWrite.Save(appsettingsFilePath);

Expand Down
38 changes: 31 additions & 7 deletions src/Tools/dotnet-user-jwts/src/Commands/RemoveCommand.cs
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,12 @@ public static void Register(ProjectCommandLineApplication app)
cmd.Description = Resources.RemoveCommand_Description;

var idArgument = cmd.Argument("[id]", Resources.RemoveCommand_IdArgument_Description);

var appsettingsFileOption = cmd.Option(
"--appsettings-file",
Resources.CreateCommand_appsettingsFileOption_Description,
CommandOptionType.SingleValue);

cmd.HelpOption("-h|--help");

cmd.OnExecute(() =>
Expand All @@ -24,17 +30,35 @@ public static void Register(ProjectCommandLineApplication app)
cmd.ShowHelp();
return 0;
}
return Execute(cmd.Reporter, cmd.ProjectOption.Value(), idArgument.Value);

if (!DevJwtCliHelpers.GetProjectAndSecretsId(cmd.ProjectOption.Value(), cmd.Reporter, out var project, out var userSecretsId))
{
return 1;
}

var appsettingsFile = "appsettings.Development.json";
if (appsettingsFileOption.HasValue())
{
appsettingsFile = appsettingsFileOption.Value();
if (!appsettingsFile.EndsWith(".json", StringComparison.OrdinalIgnoreCase))
{
cmd.Reporter.Error(Resources.RemoveCommand_InvalidAppsettingsFile_Error);
return 1;
}
else if (!File.Exists(Path.Combine(Path.GetDirectoryName(project), appsettingsFile)))
{
cmd.Reporter.Error(Resources.FormatRemoveCommand_AppsettingsFileNotFound_Error(Path.GetDirectoryName(project)));
return 1;
}
}

return Execute(cmd.Reporter, project, userSecretsId, idArgument.Value, appsettingsFile);
});
});
}

private static int Execute(IReporter reporter, string projectPath, string id)
private static int Execute(IReporter reporter, string project, string userSecretsId, string id, string appsettingsFile)
{
if (!DevJwtCliHelpers.GetProjectAndSecretsId(projectPath, reporter, out var project, out var userSecretsId))
{
return 1;
}
var jwtStore = new JwtStore(userSecretsId);

if (!jwtStore.Jwts.TryGetValue(id, out var jwt))
Expand All @@ -43,7 +67,7 @@ private static int Execute(IReporter reporter, string projectPath, string id)
return 1;
}

var appsettingsFilePath = Path.Combine(Path.GetDirectoryName(project), "appsettings.Development.json");
var appsettingsFilePath = Path.Combine(Path.GetDirectoryName(project), appsettingsFile);
JwtAuthenticationSchemeSettings.RemoveScheme(appsettingsFilePath, jwt.Scheme);
jwtStore.Jwts.Remove(id);
jwtStore.Save();
Expand Down
18 changes: 18 additions & 0 deletions src/Tools/dotnet-user-jwts/src/Resources.resx
Original file line number Diff line number Diff line change
Expand Up @@ -150,6 +150,12 @@
<data name="CreateCommand_ExpiresOnOption_Description" xml:space="preserve">
<value>The UTC date &amp; time the JWT should expire in the format 'yyyy-MM-dd [[[[HH:mm]]:ss]]'. Defaults to 3 months after the --not-before date. Do not use this option in conjunction with the --valid-for option.</value>
</data>
<data name="CreateCommand_InvalidAppsettingsFile_Error" xml:space="preserve">
<value>Invalid Appsettings file extension. Ensure file extension is .json.</value>
</data>
<data name="CreateCommand_AppsettingsFileNotFound_Error" xml:space="preserve">
<value>Could not find Appsettings file in '{0}'. Check the filename and that the file exists.</value>
</data>
<data name="CreateCommand_InvalidClaims_Error" xml:space="preserve">
<value>Malformed claims supplied. Ensure each claim is in the format "name=value".</value>
</data>
Expand Down Expand Up @@ -189,6 +195,9 @@
<data name="CreateCommand_ValidForOption_Description" xml:space="preserve">
<value>The period the JWT should expire after. Specify using a number followed by a duration type like 'd' for days, 'h' for hours, 'm' for minutes, and 's' for seconds, e.g. '365d'. Do not use this option in conjunction with the --expires-on option.</value>
</data>
<data name="CreateCommand_appsettingsFileOption_Description" xml:space="preserve">
<value>The appSettings configuration file to add the test scheme to.</value>
</data>
<data name="JwtPrint_Audiences" xml:space="preserve">
<value>Audience(s)</value>
</data>
Expand Down Expand Up @@ -225,6 +234,9 @@
<data name="JwtPrint_Scopes" xml:space="preserve">
<value>Scopes</value>
</data>
<data name="JwtPrint_appsettingsFile" xml:space="preserve">
<value>Appsettings File</value>
</data>
<data name="JwtPrint_Token" xml:space="preserve">
<value>Token</value>
</data>
Expand Down Expand Up @@ -312,6 +324,12 @@
<data name="RemoveCommand_NoJwtFound" xml:space="preserve">
<value>No JWT with ID '{0}' found.</value>
</data>
<data name="RemoveCommand_InvalidAppsettingsFile_Error" xml:space="preserve">
<value>Invalid Appsettings file extension. Ensure file extension is .json.</value>
</data>
<data name="RemoveCommand_AppsettingsFileNotFound_Error" xml:space="preserve">
<value>Could not find Appsettings file in '{0}'. Check the filename and that the file exists.</value>
</data>
<data name="KeyCommand_IssuerOption_Description" xml:space="preserve">
<value>The issuer associated with the signing key to be reset or displayed. Defaults to 'dotnet-user-jwts'.</value>
</data>
Expand Down
4 changes: 4 additions & 0 deletions src/Tools/dotnet-user-jwts/test/UserJwtsTestFixture.cs
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,10 @@ public string CreateProject(bool hasSecret = true)
Path.Combine(projectPath.FullName, "appsettings.Development.json"),
"{}");

File.WriteAllText(
Path.Combine(projectPath.FullName, "appsettings.Local.json"),
"{}");

if (hasSecret)
{
_disposables.Push(() =>
Expand Down
Loading
Loading