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

        if (!jwtStore.Jwts.ContainsKey(id))
        {
            reporter.Error(Resources.FormatRemoveCommand_NoJwtFound(id));
            return(1);
        }

        var jwt = jwtStore.Jwts[id];
        var appsettingsFilePath = Path.Combine(Path.GetDirectoryName(project), "appsettings.Development.json");

        JwtAuthenticationSchemeSettings.RemoveScheme(appsettingsFilePath, jwt.Scheme);
        jwtStore.Jwts.Remove(id);
        jwtStore.Save();

        reporter.Output(Resources.FormatRemoveCommand_Confirmed(id));

        return(0);
    }
Exemplo n.º 2
0
    private static int Execute(IReporter reporter, string projectPath, string id, bool showFull)
    {
        if (!DevJwtCliHelpers.GetProjectAndSecretsId(projectPath, reporter, out var _, out var userSecretsId))
        {
            return(1);
        }
        var jwtStore = new JwtStore(userSecretsId);

        if (!jwtStore.Jwts.TryGetValue(id, out var jwt))
        {
            reporter.Output(Resources.FormatPrintCommand_NoJwtFound(id));
            return(1);
        }

        reporter.Output(Resources.FormatPrintCommand_Confirmed(id));
        JwtSecurityToken fullToken;

        if (showFull)
        {
            fullToken = JwtIssuer.Extract(jwt.Token);
            DevJwtCliHelpers.PrintJwt(reporter, jwt, fullToken);
        }

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

        if (count == 0)
        {
            reporter.Output(Resources.FormatClearCommand_NoJwtsRemoved(project));
            return(0);
        }

        if (!force)
        {
            reporter.Output(Resources.ClearCommand_Permission);
            reporter.Output("[Y]es / [N]o");
            if (Console.ReadLine().Trim().ToUpperInvariant() != "Y")
            {
                reporter.Output(Resources.ClearCommand_Canceled);
                return(0);
            }
        }

        var appsettingsFilePath = Path.Combine(Path.GetDirectoryName(project), "appsettings.Development.json");

        foreach (var jwt in jwtStore.Jwts)
        {
            JwtAuthenticationSchemeSettings.RemoveScheme(appsettingsFilePath, jwt.Value.Scheme);
        }

        jwtStore.Jwts.Clear();
        jwtStore.Save();

        reporter.Output(Resources.FormatClearCommand_Confirmed(count, project));

        return(0);
    }
Exemplo n.º 4
0
    private static int Execute(IReporter reporter, string projectPath, bool showTokens)
    {
        if (!DevJwtCliHelpers.GetProjectAndSecretsId(projectPath, reporter, out var project, out var userSecretsId))
        {
            return(1);
        }
        var jwtStore = new JwtStore(userSecretsId);

        reporter.Output(Resources.FormatListCommand_Project(project));
        reporter.Output(Resources.FormatListCommand_UserSecretsId(userSecretsId));

        if (jwtStore.Jwts is { Count : > 0 } jwts)
        {
            var table = new ConsoleTable(reporter);
            table.AddColumns(Resources.JwtPrint_Id, Resources.JwtPrint_Scheme, Resources.JwtPrint_Audiences, Resources.JwtPrint_IssuedOn, Resources.JwtPrint_ExpiresOn);

            if (showTokens)
            {
                table.AddColumns(Resources.JwtPrint_Token);
            }

            foreach (var jwtRow in jwts)
            {
                var jwt = jwtRow.Value;
                if (showTokens)
                {
                    table.AddRow(jwt.Id, jwt.Scheme, jwt.Audience, jwt.Issued.ToString("O"), jwt.Expires.ToString("O"), jwt.Token);
                }
                else
                {
                    table.AddRow(jwt.Id, jwt.Scheme, jwt.Audience, jwt.Issued.ToString("O"), jwt.Expires.ToString("O"));
                }
            }

            table.Write();
        }
Exemplo n.º 5
0
    private static int Execute(IReporter reporter, string projectPath, string scheme, string issuer, bool reset, bool force)
    {
        if (!DevJwtCliHelpers.GetProjectAndSecretsId(projectPath, reporter, out var _, out var userSecretsId))
        {
            return(1);
        }

        if (reset == true)
        {
            if (!force)
            {
                reporter.Output(Resources.KeyCommand_Permission);
                reporter.Error("[Y]es / [N]o");
                if (Console.ReadLine().Trim().ToUpperInvariant() != "Y")
                {
                    reporter.Output(Resources.KeyCommand_Canceled);
                    return(0);
                }
            }

            var key = SigningKeysHandler.CreateSigningKeyMaterial(userSecretsId, scheme, issuer, reset: true);
            reporter.Output(Resources.FormatKeyCommand_KeyCreated(Convert.ToBase64String(key)));
            return(0);
        }

        var signingKeyMaterial = SigningKeysHandler.GetSigningKeyMaterial(userSecretsId, scheme, issuer);

        if (signingKeyMaterial is null)
        {
            reporter.Output(Resources.KeyCommand_KeyNotFound);
            return(0);
        }

        reporter.Output(Resources.FormatKeyCommand_Confirmed(signingKeyMaterial));
        return(0);
    }
Exemplo n.º 6
0
    private static (JwtCreatorOptions, bool) ValidateArguments(
        IReporter reporter,
        CommandOption projectOption,
        CommandOption schemeNameOption,
        CommandOption nameOption,
        CommandOption audienceOption,
        CommandOption issuerOption,
        CommandOption notBeforeOption,
        CommandOption expiresOnOption,
        CommandOption validForOption,
        CommandOption rolesOption,
        CommandOption scopesOption,
        CommandOption claimsOption)
    {
        var isValid = true;
        var project = DevJwtCliHelpers.GetProject(projectOption.Value());
        var scheme  = schemeNameOption.HasValue() ? schemeNameOption.Value() : "Bearer";
        var name    = nameOption.HasValue() ? nameOption.Value() : Environment.UserName;

        var audience = audienceOption.HasValue() ? audienceOption.Values : DevJwtCliHelpers.GetAudienceCandidatesFromLaunchSettings(project).ToList();

        if (audience is null)
        {
            reporter.Error(Resources.CreateCommand_NoAudience_Error);
            isValid = false;
        }
        var issuer = issuerOption.HasValue() ? issuerOption.Value() : DevJwtsDefaults.Issuer;

        var notBefore = DateTime.UtcNow;

        if (notBeforeOption.HasValue())
        {
            if (!ParseDate(notBeforeOption.Value(), out notBefore))
            {
                reporter.Error(Resources.FormatCreateCommand_InvalidDate_Error("--not-before"));
                isValid = false;
            }
        }

        var expiresOn = notBefore.AddMonths(3);

        if (expiresOnOption.HasValue())
        {
            if (!ParseDate(expiresOnOption.Value(), out expiresOn))
            {
                reporter.Error(Resources.FormatCreateCommand_InvalidDate_Error("--expires-on"));
                isValid = false;
            }
        }

        if (validForOption.HasValue())
        {
            if (!TimeSpan.TryParseExact(validForOption.Value(), _timeSpanFormats, CultureInfo.InvariantCulture, out var validForValue))
            {
                reporter.Error(Resources.FormatCreateCommand_InvalidPeriod_Error("--valid-for"));
            }
            expiresOn = notBefore.Add(validForValue);
        }

        var roles  = rolesOption.HasValue() ? rolesOption.Values : new List <string>();
        var scopes = scopesOption.HasValue() ? scopesOption.Values : new List <string>();

        var claims = new Dictionary <string, string>();

        if (claimsOption.HasValue())
        {
            if (!DevJwtCliHelpers.TryParseClaims(claimsOption.Values, out claims))
            {
                reporter.Error(Resources.CreateCommand_InvalidClaims_Error);
                isValid = false;
            }
        }

        return(new JwtCreatorOptions(scheme, name, audience, issuer, notBefore, expiresOn, roles, scopes, claims), isValid);
Exemplo n.º 7
0
    private static (JwtCreatorOptions, bool, string) ValidateArguments(
        IReporter reporter,
        CommandOption projectOption,
        CommandOption schemeNameOption,
        CommandOption nameOption,
        CommandOption audienceOption,
        CommandOption issuerOption,
        CommandOption notBeforeOption,
        CommandOption expiresOnOption,
        CommandOption validForOption,
        CommandOption rolesOption,
        CommandOption scopesOption,
        CommandOption claimsOption)
    {
        var isValid = true;
        var project = DevJwtCliHelpers.GetProject(projectOption.Value());

        if (project == null)
        {
            reporter.Error(Resources.ProjectOption_ProjectNotFound);
            isValid = false;
            // Break out early if we haven't been able to resolve a project
            // since we depend on it for the managing of JWT tokens
            return(
                null,
                isValid,
                string.Empty
                );
        }

        var scheme        = schemeNameOption.HasValue() ? schemeNameOption.Value() : "Bearer";
        var optionsString = schemeNameOption.HasValue() ? $"{Resources.JwtPrint_Scheme}: {scheme}{Environment.NewLine}" : string.Empty;

        var name = nameOption.HasValue() ? nameOption.Value() : Environment.UserName;

        optionsString += $"{Resources.JwtPrint_Name}: {name}{Environment.NewLine}";

        var audience = audienceOption.HasValue() ? audienceOption.Values : DevJwtCliHelpers.GetAudienceCandidatesFromLaunchSettings(project);

        optionsString += audienceOption.HasValue() ? $"{Resources.JwtPrint_Audiences}: {string.Join(", ", audience)}{Environment.NewLine}" : string.Empty;
        if (audience is null || audience.Count == 0)
        {
            reporter.Error(Resources.CreateCommand_NoAudience_Error);
            isValid = false;
        }
        var issuer = issuerOption.HasValue() ? issuerOption.Value() : DevJwtsDefaults.Issuer;

        optionsString += issuerOption.HasValue() ? $"{Resources.JwtPrint_Issuer}: {issuer}{Environment.NewLine}" : string.Empty;

        var notBefore = DateTime.UtcNow;

        if (notBeforeOption.HasValue())
        {
            if (!ParseDate(notBeforeOption.Value(), out notBefore))
            {
                reporter.Error(Resources.FormatCreateCommand_InvalidDate_Error("--not-before"));
                isValid = false;
            }
            optionsString += $"{Resources.JwtPrint_NotBefore}: {notBefore:O}{Environment.NewLine}";
        }

        var expiresOn = notBefore.AddMonths(3);

        if (expiresOnOption.HasValue())
        {
            if (!ParseDate(expiresOnOption.Value(), out expiresOn))
            {
                reporter.Error(Resources.FormatCreateCommand_InvalidDate_Error("--expires-on"));
                isValid = false;
            }

            if (validForOption.HasValue())
            {
                reporter.Error(Resources.CreateCommand_InvalidExpiresOn_Error);
                isValid = false;
            }
            else
            {
                optionsString += $"{Resources.JwtPrint_ExpiresOn}: {expiresOn:O}{Environment.NewLine}";
            }
        }

        if (validForOption.HasValue())
        {
            if (!TimeSpan.TryParseExact(validForOption.Value(), _timeSpanFormats, CultureInfo.InvariantCulture, out var validForValue))
            {
                reporter.Error(Resources.FormatCreateCommand_InvalidPeriod_Error("--valid-for"));
            }
            expiresOn = notBefore.Add(validForValue);

            if (expiresOnOption.HasValue())
            {
                reporter.Error(Resources.CreateCommand_InvalidExpiresOn_Error);
                isValid = false;
            }
            else
            {
                optionsString += $"{Resources.JwtPrint_ExpiresOn}: {expiresOn:O}{Environment.NewLine}";
            }
        }

        var roles = rolesOption.HasValue() ? rolesOption.Values : new List <string>();

        optionsString += rolesOption.HasValue() ? $"{Resources.JwtPrint_Roles}: [{string.Join(", ", roles)}]{Environment.NewLine}" : string.Empty;

        var scopes = scopesOption.HasValue() ? scopesOption.Values : new List <string>();

        optionsString += scopesOption.HasValue() ? $"{Resources.JwtPrint_Scopes}: {string.Join(", ", scopes)}{Environment.NewLine}" : string.Empty;

        var claims = new Dictionary <string, string>();

        if (claimsOption.HasValue())
        {
            if (!DevJwtCliHelpers.TryParseClaims(claimsOption.Values, out claims))
            {
                reporter.Error(Resources.CreateCommand_InvalidClaims_Error);
                isValid = false;
            }
            optionsString += $"{Resources.JwtPrint_CustomClaims}: [{string.Join(", ", claims.Select(kvp => $"{kvp.Key}={kvp.Value}"))}]{Environment.NewLine}";
        }

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