Skip to content

Add support for --output option in user-jwts create #42249

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

Merged
merged 2 commits into from
Jun 17, 2022
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
28 changes: 23 additions & 5 deletions src/Tools/dotnet-user-jwts/src/Commands/CreateCommand.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
using System.Globalization;
using System.Linq;
using System.Text;
using System.Text.Json;
using Microsoft.Extensions.CommandLineUtils;
using Microsoft.Extensions.Tools.Internal;

Expand Down Expand Up @@ -77,6 +78,11 @@ public static void Register(ProjectCommandLineApplication app)
Resources.CreateCommand_ValidForOption_Description,
CommandOptionType.SingleValue);

var outputOption = cmd.Option(
"-o|--output",
Resources.CreateCommand_OutputOption_Description,
CommandOptionType.SingleValue);

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

cmd.OnExecute(() =>
Expand All @@ -89,7 +95,7 @@ public static void Register(ProjectCommandLineApplication app)
return 1;
}

return Execute(cmd.Reporter, cmd.ProjectOption.Value(), options, optionsString);
return Execute(cmd.Reporter, cmd.ProjectOption.Value(), options, optionsString, outputOption.Value());
});
});
}
Expand Down Expand Up @@ -208,7 +214,8 @@ private static int Execute(
IReporter reporter,
string projectPath,
JwtCreatorOptions options,
string optionsString)
string optionsString,
string outputFormat)
{
if (!DevJwtCliHelpers.GetProjectAndSecretsId(projectPath, reporter, out var project, out var userSecretsId))
{
Expand All @@ -232,9 +239,20 @@ private static int Execute(
var settingsToWrite = new JwtAuthenticationSchemeSettings(options.Scheme, options.Audiences, options.Issuer);
settingsToWrite.Save(appsettingsFilePath);

reporter.Output(Resources.FormatCreateCommand_Confirmed(jwtToken.Id));
reporter.Output(optionsString);
reporter.Output($"{Resources.JwtPrint_Token}: {jwt.Token}");
switch (outputFormat)
{
case "token":
reporter.Output(jwt.Token);
break;
case "json":
reporter.Output(JsonSerializer.Serialize(jwt, new JsonSerializerOptions { WriteIndented = true }));
break;
default:
reporter.Output(Resources.FormatCreateCommand_Confirmed(jwtToken.Id));
reporter.Output(optionsString);
reporter.Output($"{Resources.JwtPrint_Token}: {jwt.Token}");
break;
}

return 0;
}
Expand Down
59 changes: 31 additions & 28 deletions src/Tools/dotnet-user-jwts/src/Resources.resx
Original file line number Diff line number Diff line change
@@ -1,17 +1,17 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema

<!--
Microsoft ResX Schema
Version 2.0

The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.

Example:

... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
Expand All @@ -26,36 +26,36 @@
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>

There are any number of "resheader" rows that contain simple
There are any number of "resheader" rows that contain simple
name/value pairs.

Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.

The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:

Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.

mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.

mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.

mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
Expand Down Expand Up @@ -174,6 +174,9 @@
<data name="CreateCommand_NotBeforeOption_Description" xml:space="preserve">
<value>The UTC date &amp; time the JWT should not be valid before in the format 'yyyy-MM-dd [[HH:mm[[:ss]]]]'. Defaults to the date &amp; time the JWT is created.</value>
</data>
<data name="CreateCommand_OutputOption_Description" xml:space="preserve">
<value>The format to use for displaying output from the command. Can be one of 'default', 'token', or 'json'.</value>
</data>
<data name="CreateCommand_RoleOption_Description" xml:space="preserve">
<value>A role claim to add to the JWT. Specify once for each role.</value>
</data>
Expand Down Expand Up @@ -300,4 +303,4 @@
<data name="RemoveCommand_NoJwtFound" xml:space="preserve">
<value>No JWT with ID '{0}' found.</value>
</data>
</root>
</root>
30 changes: 30 additions & 0 deletions src/Tools/dotnet-user-jwts/test/UserJwtsTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@
using Xunit;
using Xunit.Abstractions;
using System.Text.RegularExpressions;
using System.Text.Json;
using System.IdentityModel.Tokens.Jwt;

namespace Microsoft.AspNetCore.Authentication.JwtBearer.Tools.Tests;

Expand Down Expand Up @@ -277,4 +279,32 @@ public void PrintComamnd_ShowsAllOptionsWithShowAll()
Assert.Contains($"Roles: [none]", output);
Assert.Contains($"Custom Claims: [foo=bar]", output);
}

[Fact]
public void Create_WithJsonOutput_CanBeSerialized()
{
var project = Path.Combine(_fixture.CreateProject(), "TestProject.csproj");
var app = new Program(_console);

app.Run(new[] { "create", "--project", project, "--output", "json" });
var output = _console.GetOutput();
var deserialized = JsonSerializer.Deserialize<Jwt>(output);

Assert.NotNull(deserialized);
Assert.Equal("Bearer", deserialized.Scheme);
Assert.Equal(Environment.UserName, deserialized.Name);
}

[Fact]
public void Create_WithTokenOutput_ProducesSingleValue()
{
var project = Path.Combine(_fixture.CreateProject(), "TestProject.csproj");
var app = new Program(_console);

app.Run(new[] { "create", "--project", project, "-o", "token" });
var output = _console.GetOutput();

var handler = new JwtSecurityTokenHandler();
Assert.True(handler.CanReadToken(output.Trim()));
}
}