diff --git a/README.md b/README.md index 072d710..50c1b55 100644 --- a/README.md +++ b/README.md @@ -8,13 +8,26 @@ encourages the use of easy to remember, yet secure passphrases instead of hard t ## Installation -Using nuget - - coming soon +Using the dotnet-cli +```bash +dotnet add package StanfordPasswordPolicy +``` +or with the nuget package manager console: +```bash +Install-Package StanfordPasswordPolicy +``` ## Usage - coming soon +```csharp +services.AddIdentity(opt => + { + // If you don't want Identity's defaults to interfere with your new policy + opt.Password = StanfordPasswordValidatorBase.NoDefaultPasswordOptions; + }) + .AddPasswordValidator>(); +``` +You can also check out SampleApp for a more complete example. ## Contributing Pull requests are welcome. For major changes, please open an issue first to discuss what you would like to change. diff --git a/SampleApp/Controllers/AccountController.cs b/SampleApp/Controllers/AccountController.cs new file mode 100644 index 0000000..f8e7410 --- /dev/null +++ b/SampleApp/Controllers/AccountController.cs @@ -0,0 +1,29 @@ +using System.Threading.Tasks; +using Microsoft.AspNetCore.Identity; +using Microsoft.AspNetCore.Mvc; +using SampleApp.Models; +using SampleApp.Models.DTO; + +namespace SampleApp.Controllers +{ + [Route("api/[action]")] + [ApiController] + public class AccountController : ControllerBase + { + // GET api/values + private readonly UserManager _userManager; + + public AccountController(UserManager userManager) + { + _userManager = userManager; + } + + [HttpPost] + public async Task Register([FromBody] AppUserDTO userDto) + { + var user = new AppUser {UserName = userDto.Username}; + var registrationResult = await _userManager.CreateAsync(user, userDto.Password); + return registrationResult.Succeeded ? Ok() : (IActionResult) BadRequest(registrationResult.Errors); + } + } +} \ No newline at end of file diff --git a/SampleApp/Data/AppDbContext.cs b/SampleApp/Data/AppDbContext.cs new file mode 100644 index 0000000..3fa185e --- /dev/null +++ b/SampleApp/Data/AppDbContext.cs @@ -0,0 +1,14 @@ +using Microsoft.EntityFrameworkCore; +using SampleApp.Models; + +namespace SampleApp.Data +{ + public class AppDbContext : DbContext + { + public AppDbContext(DbContextOptions options) : base(options) + { + } + + public DbSet AppUsers { get; set; } + } +} \ No newline at end of file diff --git a/SampleApp/Models/AppUser.cs b/SampleApp/Models/AppUser.cs new file mode 100644 index 0000000..1a5e24b --- /dev/null +++ b/SampleApp/Models/AppUser.cs @@ -0,0 +1,8 @@ +using Microsoft.AspNetCore.Identity; + +namespace SampleApp.Models +{ + public class AppUser : IdentityUser + { + } +} \ No newline at end of file diff --git a/SampleApp/Models/DTO/AppUserDTO.cs b/SampleApp/Models/DTO/AppUserDTO.cs new file mode 100644 index 0000000..9c7f52e --- /dev/null +++ b/SampleApp/Models/DTO/AppUserDTO.cs @@ -0,0 +1,8 @@ +namespace SampleApp.Models.DTO +{ + public class AppUserDTO + { + public string Username { get; set; } + public string Password { get; set; } + } +} \ No newline at end of file diff --git a/SampleApp/Program.cs b/SampleApp/Program.cs new file mode 100644 index 0000000..d23a2cb --- /dev/null +++ b/SampleApp/Program.cs @@ -0,0 +1,17 @@ +using Microsoft.AspNetCore; +using Microsoft.AspNetCore.Hosting; + +namespace SampleApp +{ + public class Program + { + public static void Main(string[] args) + { + CreateWebHostBuilder(args).Build().Run(); + } + + public static IWebHostBuilder CreateWebHostBuilder(string[] args) => + WebHost.CreateDefaultBuilder(args) + .UseStartup(); + } +} \ No newline at end of file diff --git a/SampleApp/SampleApp.csproj b/SampleApp/SampleApp.csproj new file mode 100644 index 0000000..4e9e220 --- /dev/null +++ b/SampleApp/SampleApp.csproj @@ -0,0 +1,14 @@ + + + + netcoreapp2.2 + InProcess + + + + + + + + + diff --git a/SampleApp/Startup.cs b/SampleApp/Startup.cs new file mode 100644 index 0000000..18d9a19 --- /dev/null +++ b/SampleApp/Startup.cs @@ -0,0 +1,51 @@ +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Hosting; +using Microsoft.AspNetCore.Identity; +using Microsoft.AspNetCore.Mvc; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using SampleApp.Data; +using SampleApp.Models; +using StanfordPasswordPolicy; + +namespace SampleApp +{ + public class Startup + { + public Startup(IConfiguration configuration) + { + Configuration = configuration; + } + + public IConfiguration Configuration { get; } + + // This method gets called by the runtime. Use this method to add services to the container. + public void ConfigureServices(IServiceCollection services) + { + services.AddDbContext(opt => opt.UseInMemoryDatabase(databaseName: "SampleAppDb")); + + services.AddIdentity(opt => + { + opt.Password = StanfordPasswordValidatorBase.NoDefaultPasswordOptions; + } + ) + .AddEntityFrameworkStores() + .AddDefaultTokenProviders() + .AddPasswordValidator>(); + + services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2); + } + + // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. + public void Configure(IApplicationBuilder app, IHostingEnvironment env) + { + if (env.IsDevelopment()) + { + app.UseDeveloperExceptionPage(); + } + + app.UseMvc(); + } + } +} \ No newline at end of file diff --git a/SampleApp/appsettings.Development.json b/SampleApp/appsettings.Development.json new file mode 100644 index 0000000..e203e94 --- /dev/null +++ b/SampleApp/appsettings.Development.json @@ -0,0 +1,9 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Debug", + "System": "Information", + "Microsoft": "Information" + } + } +} diff --git a/SampleApp/appsettings.json b/SampleApp/appsettings.json new file mode 100644 index 0000000..def9159 --- /dev/null +++ b/SampleApp/appsettings.json @@ -0,0 +1,8 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Warning" + } + }, + "AllowedHosts": "*" +} diff --git a/StanfordPasswordPolicy.sln b/StanfordPasswordPolicy.sln index cb33b80..55a798b 100644 --- a/StanfordPasswordPolicy.sln +++ b/StanfordPasswordPolicy.sln @@ -7,6 +7,8 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "StanfordPasswordPolicy", "S EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Test", "Test\Test.csproj", "{9FBADD1F-7AB7-4A83-9456-458D3773BD11}" EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SampleApp", "SampleApp\SampleApp.csproj", "{102779CA-963C-4826-AA96-0ECFB4D4FF33}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -21,6 +23,10 @@ Global {9FBADD1F-7AB7-4A83-9456-458D3773BD11}.Debug|Any CPU.Build.0 = Debug|Any CPU {9FBADD1F-7AB7-4A83-9456-458D3773BD11}.Release|Any CPU.ActiveCfg = Release|Any CPU {9FBADD1F-7AB7-4A83-9456-458D3773BD11}.Release|Any CPU.Build.0 = Release|Any CPU + {102779CA-963C-4826-AA96-0ECFB4D4FF33}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {102779CA-963C-4826-AA96-0ECFB4D4FF33}.Debug|Any CPU.Build.0 = Debug|Any CPU + {102779CA-963C-4826-AA96-0ECFB4D4FF33}.Release|Any CPU.ActiveCfg = Release|Any CPU + {102779CA-963C-4826-AA96-0ECFB4D4FF33}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE diff --git a/StanfordPasswordPolicy/StanfordPasswordPolicy.csproj b/StanfordPasswordPolicy/StanfordPasswordPolicy.csproj index b0b82d0..bc64f3d 100644 --- a/StanfordPasswordPolicy/StanfordPasswordPolicy.csproj +++ b/StanfordPasswordPolicy/StanfordPasswordPolicy.csproj @@ -2,10 +2,34 @@ netcoreapp2.2 + Daniel Marczin + + Daniel Marczin, 2019 + LICENSE + https://github.com/dim5/stanford-password-policy-dotnet + Git + https://github.com/dim5/stanford-password-policy-dotnet + Stanford-password-policy-dotnet is a password validator library for ASP.NET Core. +The Stanford password policy is a dynamic password policy that encourages the use of easy to remember, yet secure passphrases instead of hard to remember passwords. + 1.0.0.0 + 1.0.0.0 + 1.0.0 + true + stanford password policy validator + First stable release. + true + snupkg + + + True + + + + diff --git a/StanfordPasswordPolicy/StanfordPasswordValidator.cs b/StanfordPasswordPolicy/StanfordPasswordValidator.cs index a58926a..3de68aa 100644 --- a/StanfordPasswordPolicy/StanfordPasswordValidator.cs +++ b/StanfordPasswordPolicy/StanfordPasswordValidator.cs @@ -5,17 +5,13 @@ namespace StanfordPasswordPolicy { - public class StanfordPasswordValidator : IPasswordValidator where TUser : class + public sealed class StanfordPasswordValidator : StanfordPasswordValidatorBase, IPasswordValidator where TUser : class { - public static class ErrorCode - { - public static readonly string ShortLength = "ShortPassword"; - public static readonly string NoSymbol = "NoSymbols"; - public static readonly string NoNumber = "NoNumbers"; - public static readonly string NoMixedCase = "NotMixedCase"; - } - - public Task ValidateAsync(UserManager manager, TUser user, string password) + /// + /// Validates a password according to the Stanford Password Policy + /// + /// IdentityResult with an array of IdentityErrors if the password isn't valid, else with IdentityResult.Success + public Task ValidateAsync(UserManager manager, TUser user, string password) { var errors = new List(); @@ -58,12 +54,5 @@ public Task ValidateAsync(UserManager manager, TUser user var res = errors.Any() ? IdentityResult.Failed(errors.ToArray()) : IdentityResult.Success; return Task.FromResult(res); } - - private static bool CheckMixedCase(string password) => - password.Any(char.IsUpper) && password.Any(char.IsLower); - - private static bool CheckNumber(string password) => password.Any(char.IsNumber); - - private static bool CheckSymbol(string password) => !password.All(char.IsLetterOrDigit); } } diff --git a/StanfordPasswordPolicy/StanfordPasswordValidatorBase.cs b/StanfordPasswordPolicy/StanfordPasswordValidatorBase.cs new file mode 100644 index 0000000..333410d --- /dev/null +++ b/StanfordPasswordPolicy/StanfordPasswordValidatorBase.cs @@ -0,0 +1,37 @@ +using System.Linq; +using Microsoft.AspNetCore.Identity; + +namespace StanfordPasswordPolicy +{ + public abstract class StanfordPasswordValidatorBase + { + public static class ErrorCode + { + public static readonly string ShortLength = "ShortPassword"; + public static readonly string NoSymbol = "NoSymbols"; + public static readonly string NoNumber = "NoNumbers"; + public static readonly string NoMixedCase = "NotMixedCase"; + } + + /// + /// A clear set of PasswordOptions, to reset Identity's defaults, since StanfordPasswordValidator ignores these options. + /// + public static PasswordOptions NoDefaultPasswordOptions => + new PasswordOptions + { + RequireDigit = false, + RequiredLength = 0, + RequiredUniqueChars = 1, + RequireLowercase = false, + RequireNonAlphanumeric = false, + RequireUppercase = false + }; + + protected static bool CheckMixedCase(string password) => + password.Any(char.IsUpper) && password.Any(char.IsLower); + + protected static bool CheckNumber(string password) => password.Any(char.IsNumber); + + protected static bool CheckSymbol(string password) => !password.All(char.IsLetterOrDigit); + } +} \ No newline at end of file diff --git a/Test/SPPUnitTest.cs b/Test/SPPUnitTest.cs index 5a0b439..9ea5009 100644 --- a/Test/SPPUnitTest.cs +++ b/Test/SPPUnitTest.cs @@ -32,7 +32,7 @@ public async Task TestCorrectAsync(string password) [Fact] public async Task TestLengthAsync() { - var errorCode = StanfordPasswordValidator.ErrorCode.ShortLength; + var errorCode = StanfordPasswordValidatorBase.ErrorCode.ShortLength; var password = string.Empty; IdentityResultAssert.IsFailure(await validator.ValidateAsync(manager, user, password), errorCode); @@ -56,7 +56,7 @@ public async Task TestLengthAsync() [Fact] public async Task TestSymbolAsync() { - var errorCode = StanfordPasswordValidator.ErrorCode.NoSymbol; + var errorCode = StanfordPasswordValidatorBase.ErrorCode.NoSymbol; var password = "aaa"; IdentityResultAssert.IsFailure(await validator.ValidateAsync(manager, user, password), errorCode); @@ -74,7 +74,7 @@ public async Task TestSymbolAsync() [Fact] public async Task TestNumbersAsync() { - var errorCode = StanfordPasswordValidator.ErrorCode.NoNumber; + var errorCode = StanfordPasswordValidatorBase.ErrorCode.NoNumber; var password = "aaa"; IdentityResultAssert.IsFailure(await validator.ValidateAsync(manager, user, password), errorCode); @@ -91,7 +91,7 @@ public async Task TestNumbersAsync() [Fact] public async Task TestMixedAsync() { - var errorCode = StanfordPasswordValidator.ErrorCode.NoMixedCase; + var errorCode = StanfordPasswordValidatorBase.ErrorCode.NoMixedCase; var password = "aaa"; IdentityResultAssert.IsFailure(await validator.ValidateAsync(manager, user, password), errorCode);