├── .gitattributes ├── .gitignore ├── CookieAuthSample ├── CookieAuthSampleAPI.sln ├── CookieAuthSampleAPI │ ├── Controllers │ │ ├── AuthController.cs │ │ └── WeatherForecastController.cs │ ├── CookieAuthSampleAPI.csproj │ ├── Data │ │ └── ApplicationDbContext.cs │ ├── Migrations │ │ ├── 20200123192549_First.Designer.cs │ │ ├── 20200123192549_First.cs │ │ └── ApplicationDbContextModelSnapshot.cs │ ├── Models │ │ ├── LoginCredentials.cs │ │ ├── UserDetails.cs │ │ └── WeatherForecast.cs │ ├── Program.cs │ ├── Properties │ │ └── launchSettings.json │ ├── Startup.cs │ ├── appsettings.Development.json │ └── appsettings.json └── Postman-Collection │ └── CookieAuthSample.postman_collection.json ├── IdentityConfigurations ├── IdentityConfigurationSample.sln └── IdentityConfigurationSample │ ├── Controllers │ └── WeatherForecastController.cs │ ├── Data │ └── ApplicationDbContext.cs │ ├── IdentityConfigurationSample.csproj │ ├── Migrations │ ├── 20200123192549_First.Designer.cs │ ├── 20200123192549_First.cs │ └── ApplicationDbContextModelSnapshot.cs │ ├── Models │ └── WeatherForecast.cs │ ├── Program.cs │ ├── Properties │ └── launchSettings.json │ ├── Startup.cs │ ├── appsettings.Development.json │ └── appsettings.json ├── JwtAuthSample ├── JwtAuthSampleAPI.sln ├── JwtAuthSampleAPI │ ├── Configuration │ │ └── JwtBearerTokenSettings.cs │ ├── Controllers │ │ ├── AuthController.cs │ │ └── WeatherForecastController.cs │ ├── Data │ │ └── ApplicationDbContext.cs │ ├── JwtAuthSampleAPI.csproj │ ├── Migrations │ │ ├── 20200123192549_First.Designer.cs │ │ ├── 20200123192549_First.cs │ │ └── ApplicationDbContextModelSnapshot.cs │ ├── Models │ │ ├── LoginCredentials.cs │ │ ├── UserDetails.cs │ │ └── WeatherForecast.cs │ ├── Program.cs │ ├── Properties │ │ └── launchSettings.json │ ├── Startup.cs │ ├── appsettings.Development.json │ └── appsettings.json └── Postman-Collection │ └── JwtAuthSample.postman_collection.json ├── LICENSE ├── README.md └── RefreshJwtAuthSample ├── JwtAuthSampleAPI ├── Configuration │ └── JwtBearerTokenSettings.cs ├── Controllers │ ├── AuthController.cs │ └── WeatherForecastController.cs ├── Data │ ├── ApplicationDbContext.cs │ ├── ApplicationUser.cs │ └── RefreshToken.cs ├── JwtAuthRefreshTokenSampleAPI.csproj ├── Migrations │ ├── 20200123192549_First.Designer.cs │ ├── 20200123192549_First.cs │ ├── 20201128135409_Second.Designer.cs │ ├── 20201128135409_Second.cs │ └── ApplicationDbContextModelSnapshot.cs ├── Models │ ├── LoginCredentials.cs │ ├── UserDetails.cs │ └── WeatherForecast.cs ├── Program.cs ├── Properties │ └── launchSettings.json ├── Startup.cs ├── appsettings.Development.json └── appsettings.json ├── Postman-Collection └── refresh-token-aspnetcore-sample-postman-setup.json └── RefreshJwtAuthSampleAPI.sln /.gitattributes: -------------------------------------------------------------------------------- 1 | # Auto detect text files and perform LF normalization 2 | * text=auto 3 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | ## Ignore Visual Studio temporary files, build results, and 2 | ## files generated by popular Visual Studio add-ons. 3 | ## 4 | ## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore 5 | 6 | # User-specific files 7 | *.rsuser 8 | *.suo 9 | *.user 10 | *.userosscache 11 | *.sln.docstates 12 | 13 | # User-specific files (MonoDevelop/Xamarin Studio) 14 | *.userprefs 15 | 16 | # Mono auto generated files 17 | mono_crash.* 18 | 19 | # Build results 20 | [Dd]ebug/ 21 | [Dd]ebugPublic/ 22 | [Rr]elease/ 23 | [Rr]eleases/ 24 | x64/ 25 | x86/ 26 | [Aa][Rr][Mm]/ 27 | [Aa][Rr][Mm]64/ 28 | bld/ 29 | [Bb]in/ 30 | [Oo]bj/ 31 | [Ll]og/ 32 | [Ll]ogs/ 33 | 34 | # Visual Studio 2015/2017 cache/options directory 35 | .vs/ 36 | # Uncomment if you have tasks that create the project's static files in wwwroot 37 | #wwwroot/ 38 | 39 | # Visual Studio 2017 auto generated files 40 | Generated\ Files/ 41 | 42 | # MSTest test Results 43 | [Tt]est[Rr]esult*/ 44 | [Bb]uild[Ll]og.* 45 | 46 | # NUnit 47 | *.VisualState.xml 48 | TestResult.xml 49 | nunit-*.xml 50 | 51 | # Build Results of an ATL Project 52 | [Dd]ebugPS/ 53 | [Rr]eleasePS/ 54 | dlldata.c 55 | 56 | # Benchmark Results 57 | BenchmarkDotNet.Artifacts/ 58 | 59 | # .NET Core 60 | project.lock.json 61 | project.fragment.lock.json 62 | artifacts/ 63 | 64 | # StyleCop 65 | StyleCopReport.xml 66 | 67 | # Files built by Visual Studio 68 | *_i.c 69 | *_p.c 70 | *_h.h 71 | *.ilk 72 | *.meta 73 | *.obj 74 | *.iobj 75 | *.pch 76 | *.pdb 77 | *.ipdb 78 | *.pgc 79 | *.pgd 80 | *.rsp 81 | *.sbr 82 | *.tlb 83 | *.tli 84 | *.tlh 85 | *.tmp 86 | *.tmp_proj 87 | *_wpftmp.csproj 88 | *.log 89 | *.vspscc 90 | *.vssscc 91 | .builds 92 | *.pidb 93 | *.svclog 94 | *.scc 95 | 96 | # Chutzpah Test files 97 | _Chutzpah* 98 | 99 | # Visual C++ cache files 100 | ipch/ 101 | *.aps 102 | *.ncb 103 | *.opendb 104 | *.opensdf 105 | *.sdf 106 | *.cachefile 107 | *.VC.db 108 | *.VC.VC.opendb 109 | 110 | # Visual Studio profiler 111 | *.psess 112 | *.vsp 113 | *.vspx 114 | *.sap 115 | 116 | # Visual Studio Trace Files 117 | *.e2e 118 | 119 | # TFS 2012 Local Workspace 120 | $tf/ 121 | 122 | # Guidance Automation Toolkit 123 | *.gpState 124 | 125 | # ReSharper is a .NET coding add-in 126 | _ReSharper*/ 127 | *.[Rr]e[Ss]harper 128 | *.DotSettings.user 129 | 130 | # JustCode is a .NET coding add-in 131 | .JustCode 132 | 133 | # TeamCity is a build add-in 134 | _TeamCity* 135 | 136 | # DotCover is a Code Coverage Tool 137 | *.dotCover 138 | 139 | # AxoCover is a Code Coverage Tool 140 | .axoCover/* 141 | !.axoCover/settings.json 142 | 143 | # Visual Studio code coverage results 144 | *.coverage 145 | *.coveragexml 146 | 147 | # NCrunch 148 | _NCrunch_* 149 | .*crunch*.local.xml 150 | nCrunchTemp_* 151 | 152 | # MightyMoose 153 | *.mm.* 154 | AutoTest.Net/ 155 | 156 | # Web workbench (sass) 157 | .sass-cache/ 158 | 159 | # Installshield output folder 160 | [Ee]xpress/ 161 | 162 | # DocProject is a documentation generator add-in 163 | DocProject/buildhelp/ 164 | DocProject/Help/*.HxT 165 | DocProject/Help/*.HxC 166 | DocProject/Help/*.hhc 167 | DocProject/Help/*.hhk 168 | DocProject/Help/*.hhp 169 | DocProject/Help/Html2 170 | DocProject/Help/html 171 | 172 | # Click-Once directory 173 | publish/ 174 | 175 | # Publish Web Output 176 | *.[Pp]ublish.xml 177 | *.azurePubxml 178 | # Note: Comment the next line if you want to checkin your web deploy settings, 179 | # but database connection strings (with potential passwords) will be unencrypted 180 | *.pubxml 181 | *.publishproj 182 | 183 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 184 | # checkin your Azure Web App publish settings, but sensitive information contained 185 | # in these scripts will be unencrypted 186 | PublishScripts/ 187 | 188 | # NuGet Packages 189 | *.nupkg 190 | # NuGet Symbol Packages 191 | *.snupkg 192 | # The packages folder can be ignored because of Package Restore 193 | **/[Pp]ackages/* 194 | # except build/, which is used as an MSBuild target. 195 | !**/[Pp]ackages/build/ 196 | # Uncomment if necessary however generally it will be regenerated when needed 197 | #!**/[Pp]ackages/repositories.config 198 | # NuGet v3's project.json files produces more ignorable files 199 | *.nuget.props 200 | *.nuget.targets 201 | 202 | # Microsoft Azure Build Output 203 | csx/ 204 | *.build.csdef 205 | 206 | # Microsoft Azure Emulator 207 | ecf/ 208 | rcf/ 209 | 210 | # Windows Store app package directories and files 211 | AppPackages/ 212 | BundleArtifacts/ 213 | Package.StoreAssociation.xml 214 | _pkginfo.txt 215 | *.appx 216 | *.appxbundle 217 | *.appxupload 218 | 219 | # Visual Studio cache files 220 | # files ending in .cache can be ignored 221 | *.[Cc]ache 222 | # but keep track of directories ending in .cache 223 | !?*.[Cc]ache/ 224 | 225 | # Others 226 | ClientBin/ 227 | ~$* 228 | *~ 229 | *.dbmdl 230 | *.dbproj.schemaview 231 | *.jfm 232 | *.pfx 233 | *.publishsettings 234 | orleans.codegen.cs 235 | 236 | # Including strong name files can present a security risk 237 | # (https://github.com/github/gitignore/pull/2483#issue-259490424) 238 | #*.snk 239 | 240 | # Since there are multiple workflows, uncomment next line to ignore bower_components 241 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 242 | #bower_components/ 243 | 244 | # RIA/Silverlight projects 245 | Generated_Code/ 246 | 247 | # Backup & report files from converting an old project file 248 | # to a newer Visual Studio version. Backup files are not needed, 249 | # because we have git ;-) 250 | _UpgradeReport_Files/ 251 | Backup*/ 252 | UpgradeLog*.XML 253 | UpgradeLog*.htm 254 | ServiceFabricBackup/ 255 | *.rptproj.bak 256 | 257 | # SQL Server files 258 | *.mdf 259 | *.ldf 260 | *.ndf 261 | 262 | # Business Intelligence projects 263 | *.rdl.data 264 | *.bim.layout 265 | *.bim_*.settings 266 | *.rptproj.rsuser 267 | *- [Bb]ackup.rdl 268 | *- [Bb]ackup ([0-9]).rdl 269 | *- [Bb]ackup ([0-9][0-9]).rdl 270 | 271 | # Microsoft Fakes 272 | FakesAssemblies/ 273 | 274 | # GhostDoc plugin setting file 275 | *.GhostDoc.xml 276 | 277 | # Node.js Tools for Visual Studio 278 | .ntvs_analysis.dat 279 | node_modules/ 280 | 281 | # Visual Studio 6 build log 282 | *.plg 283 | 284 | # Visual Studio 6 workspace options file 285 | *.opt 286 | 287 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.) 288 | *.vbw 289 | 290 | # Visual Studio LightSwitch build output 291 | **/*.HTMLClient/GeneratedArtifacts 292 | **/*.DesktopClient/GeneratedArtifacts 293 | **/*.DesktopClient/ModelManifest.xml 294 | **/*.Server/GeneratedArtifacts 295 | **/*.Server/ModelManifest.xml 296 | _Pvt_Extensions 297 | 298 | # Paket dependency manager 299 | .paket/paket.exe 300 | paket-files/ 301 | 302 | # FAKE - F# Make 303 | .fake/ 304 | 305 | # CodeRush personal settings 306 | .cr/personal 307 | 308 | # Python Tools for Visual Studio (PTVS) 309 | __pycache__/ 310 | *.pyc 311 | 312 | # Cake - Uncomment if you are using it 313 | # tools/** 314 | # !tools/packages.config 315 | 316 | # Tabs Studio 317 | *.tss 318 | 319 | # Telerik's JustMock configuration file 320 | *.jmconfig 321 | 322 | # BizTalk build output 323 | *.btp.cs 324 | *.btm.cs 325 | *.odx.cs 326 | *.xsd.cs 327 | 328 | # OpenCover UI analysis results 329 | OpenCover/ 330 | 331 | # Azure Stream Analytics local run output 332 | ASALocalRun/ 333 | 334 | # MSBuild Binary and Structured Log 335 | *.binlog 336 | 337 | # NVidia Nsight GPU debugger configuration file 338 | *.nvuser 339 | 340 | # MFractors (Xamarin productivity tool) working folder 341 | .mfractor/ 342 | 343 | # Local History for Visual Studio 344 | .localhistory/ 345 | 346 | # BeatPulse healthcheck temp database 347 | healthchecksdb 348 | 349 | # Backup folder for Package Reference Convert tool in Visual Studio 2017 350 | MigrationBackup/ 351 | 352 | # Ionide (cross platform F# VS Code tools) working folder 353 | .ionide/ 354 | -------------------------------------------------------------------------------- /CookieAuthSample/CookieAuthSampleAPI.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio Version 16 4 | VisualStudioVersion = 16.0.29613.14 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "CookieAuthSampleAPI", "CookieAuthSampleAPI\CookieAuthSampleAPI.csproj", "{4278326A-A47C-43BA-958D-8F83E8639E0C}" 7 | EndProject 8 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Postman-Collection", "Postman-Collection", "{288B75D6-78DF-4F8A-821B-FE250A445997}" 9 | ProjectSection(SolutionItems) = preProject 10 | Postman-Collection\CookieAuthSample.postman_collection.json = Postman-Collection\CookieAuthSample.postman_collection.json 11 | EndProjectSection 12 | EndProject 13 | Global 14 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 15 | Debug|Any CPU = Debug|Any CPU 16 | Release|Any CPU = Release|Any CPU 17 | EndGlobalSection 18 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 19 | {4278326A-A47C-43BA-958D-8F83E8639E0C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 20 | {4278326A-A47C-43BA-958D-8F83E8639E0C}.Debug|Any CPU.Build.0 = Debug|Any CPU 21 | {4278326A-A47C-43BA-958D-8F83E8639E0C}.Release|Any CPU.ActiveCfg = Release|Any CPU 22 | {4278326A-A47C-43BA-958D-8F83E8639E0C}.Release|Any CPU.Build.0 = Release|Any CPU 23 | EndGlobalSection 24 | GlobalSection(SolutionProperties) = preSolution 25 | HideSolutionNode = FALSE 26 | EndGlobalSection 27 | GlobalSection(ExtensibilityGlobals) = postSolution 28 | SolutionGuid = {D3545E52-87EF-46B9-A4C5-7BABF1053564} 29 | EndGlobalSection 30 | EndGlobal 31 | -------------------------------------------------------------------------------- /CookieAuthSample/CookieAuthSampleAPI/Controllers/AuthController.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Security.Claims; 5 | using System.Threading.Tasks; 6 | using CookieAuthSampleAPI.Models; 7 | using Microsoft.AspNetCore.Authentication; 8 | using Microsoft.AspNetCore.Authentication.Cookies; 9 | using Microsoft.AspNetCore.Http; 10 | using Microsoft.AspNetCore.Identity; 11 | using Microsoft.AspNetCore.Mvc; 12 | using Microsoft.AspNetCore.Mvc.ModelBinding; 13 | 14 | namespace CookieAuthSampleAPI.Controllers 15 | { 16 | [Route("api/[controller]")] 17 | [ApiController] 18 | public class AuthController : ControllerBase 19 | { 20 | private readonly SignInManager signInManager; 21 | private readonly UserManager userManager; 22 | 23 | public AuthController(SignInManager signInManager, UserManager userManager) 24 | { 25 | this.signInManager = signInManager; 26 | this.userManager = userManager; 27 | } 28 | 29 | [HttpPost] 30 | [Route("Register")] 31 | public async Task Register([FromBody]UserDetails userDetails) 32 | { 33 | if (!ModelState.IsValid || userDetails == null) 34 | { 35 | return new BadRequestObjectResult(new { Message = "User Registration Failed" }); 36 | } 37 | 38 | var identityUser = new IdentityUser() { UserName = userDetails.UserName, Email = userDetails.Email }; 39 | var result = await userManager.CreateAsync(identityUser, userDetails.Password); 40 | if (!result.Succeeded) 41 | { 42 | var dictionary = new ModelStateDictionary(); 43 | foreach (IdentityError error in result.Errors) 44 | { 45 | dictionary.AddModelError(error.Code, error.Description); 46 | } 47 | 48 | return new BadRequestObjectResult(new { Message = "User Registration Failed", Errors = dictionary }); 49 | } 50 | 51 | return Ok(new { Message = "User Reigstration Successful" }); 52 | } 53 | 54 | [HttpPost] 55 | [Route("Login")] 56 | public async Task Login([FromBody]LoginCredentials credentials) 57 | { 58 | if (!ModelState.IsValid || credentials == null) 59 | { 60 | return new BadRequestObjectResult(new { Message = "Login failed" }); 61 | } 62 | 63 | var identityUser = await userManager.FindByNameAsync(credentials.Username); 64 | if (identityUser == null) 65 | { 66 | return new BadRequestObjectResult(new { Message = "Login failed" }); 67 | } 68 | 69 | var result = userManager.PasswordHasher.VerifyHashedPassword(identityUser, identityUser.PasswordHash, credentials.Password); 70 | if (result == PasswordVerificationResult.Failed) 71 | { 72 | return new BadRequestObjectResult(new { Message = "Login failed" }); 73 | } 74 | 75 | var claims = new List 76 | { 77 | new Claim(ClaimTypes.Email, identityUser.Email), 78 | new Claim(ClaimTypes.Name, identityUser.UserName) 79 | }; 80 | 81 | var claimsIdentity = new ClaimsIdentity( 82 | claims, CookieAuthenticationDefaults.AuthenticationScheme); 83 | 84 | await HttpContext.SignInAsync( 85 | CookieAuthenticationDefaults.AuthenticationScheme, 86 | new ClaimsPrincipal(claimsIdentity)); 87 | 88 | return Ok(new { Message = "You are logged in" }); 89 | } 90 | 91 | [HttpPost] 92 | [Route("Logout")] 93 | public async Task Logout() 94 | { 95 | await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme); 96 | return Ok(new { Message = "You are logged out" }); 97 | } 98 | 99 | } 100 | } -------------------------------------------------------------------------------- /CookieAuthSample/CookieAuthSampleAPI/Controllers/WeatherForecastController.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Threading.Tasks; 5 | using CookieAuthSampleAPI.Models; 6 | using Microsoft.AspNetCore.Authentication.Cookies; 7 | using Microsoft.AspNetCore.Authorization; 8 | using Microsoft.AspNetCore.Mvc; 9 | using Microsoft.Extensions.Logging; 10 | 11 | namespace CookieAuthSampleAPI.Controllers 12 | { 13 | [Authorize(AuthenticationSchemes = CookieAuthenticationDefaults.AuthenticationScheme)] 14 | [ApiController] 15 | [Route("api/[controller]")] 16 | public class WeatherForecastController : ControllerBase 17 | { 18 | private static readonly string[] Summaries = new[] 19 | { 20 | "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching" 21 | }; 22 | 23 | private readonly ILogger _logger; 24 | 25 | public WeatherForecastController(ILogger logger) 26 | { 27 | _logger = logger; 28 | } 29 | 30 | [HttpGet] 31 | [Route("")] 32 | public IEnumerable Get() 33 | { 34 | var rng = new Random(); 35 | return Enumerable.Range(1, 5).Select(index => new WeatherForecast 36 | { 37 | Date = DateTime.Now.AddDays(index), 38 | TemperatureC = rng.Next(-20, 55), 39 | Summary = Summaries[rng.Next(Summaries.Length)] 40 | }) 41 | .ToArray(); 42 | } 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /CookieAuthSample/CookieAuthSampleAPI/CookieAuthSampleAPI.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | netcoreapp3.1 5 | 6 | 7 | 8 | 9 | 10 | 11 | all 12 | runtime; build; native; contentfiles; analyzers; buildtransitive 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | -------------------------------------------------------------------------------- /CookieAuthSample/CookieAuthSampleAPI/Data/ApplicationDbContext.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Identity; 2 | using Microsoft.AspNetCore.Identity.EntityFrameworkCore; 3 | using Microsoft.EntityFrameworkCore; 4 | using Microsoft.Extensions.Options; 5 | using System; 6 | using System.Collections.Generic; 7 | using System.Linq; 8 | using System.Threading.Tasks; 9 | 10 | namespace CookieAuthSampleAPI.Data 11 | { 12 | public class ApplicationDbContext : IdentityDbContext 13 | { 14 | public ApplicationDbContext(DbContextOptions options) : base(options) 15 | { 16 | 17 | } 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /CookieAuthSample/CookieAuthSampleAPI/Migrations/20200123192549_First.Designer.cs: -------------------------------------------------------------------------------- 1 | // 2 | using System; 3 | using CookieAuthSampleAPI.Data; 4 | using Microsoft.EntityFrameworkCore; 5 | using Microsoft.EntityFrameworkCore.Infrastructure; 6 | using Microsoft.EntityFrameworkCore.Metadata; 7 | using Microsoft.EntityFrameworkCore.Migrations; 8 | using Microsoft.EntityFrameworkCore.Storage.ValueConversion; 9 | 10 | namespace CookieAuthSampleAPI.Migrations 11 | { 12 | [DbContext(typeof(ApplicationDbContext))] 13 | [Migration("20200123192549_First")] 14 | partial class First 15 | { 16 | protected override void BuildTargetModel(ModelBuilder modelBuilder) 17 | { 18 | #pragma warning disable 612, 618 19 | modelBuilder 20 | .HasAnnotation("ProductVersion", "3.1.1") 21 | .HasAnnotation("Relational:MaxIdentifierLength", 128) 22 | .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); 23 | 24 | modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRole", b => 25 | { 26 | b.Property("Id") 27 | .HasColumnType("nvarchar(450)"); 28 | 29 | b.Property("ConcurrencyStamp") 30 | .IsConcurrencyToken() 31 | .HasColumnType("nvarchar(max)"); 32 | 33 | b.Property("Name") 34 | .HasColumnType("nvarchar(256)") 35 | .HasMaxLength(256); 36 | 37 | b.Property("NormalizedName") 38 | .HasColumnType("nvarchar(256)") 39 | .HasMaxLength(256); 40 | 41 | b.HasKey("Id"); 42 | 43 | b.HasIndex("NormalizedName") 44 | .IsUnique() 45 | .HasName("RoleNameIndex") 46 | .HasFilter("[NormalizedName] IS NOT NULL"); 47 | 48 | b.ToTable("AspNetRoles"); 49 | }); 50 | 51 | modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => 52 | { 53 | b.Property("Id") 54 | .ValueGeneratedOnAdd() 55 | .HasColumnType("int") 56 | .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); 57 | 58 | b.Property("ClaimType") 59 | .HasColumnType("nvarchar(max)"); 60 | 61 | b.Property("ClaimValue") 62 | .HasColumnType("nvarchar(max)"); 63 | 64 | b.Property("RoleId") 65 | .IsRequired() 66 | .HasColumnType("nvarchar(450)"); 67 | 68 | b.HasKey("Id"); 69 | 70 | b.HasIndex("RoleId"); 71 | 72 | b.ToTable("AspNetRoleClaims"); 73 | }); 74 | 75 | modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUser", b => 76 | { 77 | b.Property("Id") 78 | .HasColumnType("nvarchar(450)"); 79 | 80 | b.Property("AccessFailedCount") 81 | .HasColumnType("int"); 82 | 83 | b.Property("ConcurrencyStamp") 84 | .IsConcurrencyToken() 85 | .HasColumnType("nvarchar(max)"); 86 | 87 | b.Property("Email") 88 | .HasColumnType("nvarchar(256)") 89 | .HasMaxLength(256); 90 | 91 | b.Property("EmailConfirmed") 92 | .HasColumnType("bit"); 93 | 94 | b.Property("LockoutEnabled") 95 | .HasColumnType("bit"); 96 | 97 | b.Property("LockoutEnd") 98 | .HasColumnType("datetimeoffset"); 99 | 100 | b.Property("NormalizedEmail") 101 | .HasColumnType("nvarchar(256)") 102 | .HasMaxLength(256); 103 | 104 | b.Property("NormalizedUserName") 105 | .HasColumnType("nvarchar(256)") 106 | .HasMaxLength(256); 107 | 108 | b.Property("PasswordHash") 109 | .HasColumnType("nvarchar(max)"); 110 | 111 | b.Property("PhoneNumber") 112 | .HasColumnType("nvarchar(max)"); 113 | 114 | b.Property("PhoneNumberConfirmed") 115 | .HasColumnType("bit"); 116 | 117 | b.Property("SecurityStamp") 118 | .HasColumnType("nvarchar(max)"); 119 | 120 | b.Property("TwoFactorEnabled") 121 | .HasColumnType("bit"); 122 | 123 | b.Property("UserName") 124 | .HasColumnType("nvarchar(256)") 125 | .HasMaxLength(256); 126 | 127 | b.HasKey("Id"); 128 | 129 | b.HasIndex("NormalizedEmail") 130 | .HasName("EmailIndex"); 131 | 132 | b.HasIndex("NormalizedUserName") 133 | .IsUnique() 134 | .HasName("UserNameIndex") 135 | .HasFilter("[NormalizedUserName] IS NOT NULL"); 136 | 137 | b.ToTable("AspNetUsers"); 138 | }); 139 | 140 | modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => 141 | { 142 | b.Property("Id") 143 | .ValueGeneratedOnAdd() 144 | .HasColumnType("int") 145 | .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); 146 | 147 | b.Property("ClaimType") 148 | .HasColumnType("nvarchar(max)"); 149 | 150 | b.Property("ClaimValue") 151 | .HasColumnType("nvarchar(max)"); 152 | 153 | b.Property("UserId") 154 | .IsRequired() 155 | .HasColumnType("nvarchar(450)"); 156 | 157 | b.HasKey("Id"); 158 | 159 | b.HasIndex("UserId"); 160 | 161 | b.ToTable("AspNetUserClaims"); 162 | }); 163 | 164 | modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => 165 | { 166 | b.Property("LoginProvider") 167 | .HasColumnType("nvarchar(450)"); 168 | 169 | b.Property("ProviderKey") 170 | .HasColumnType("nvarchar(450)"); 171 | 172 | b.Property("ProviderDisplayName") 173 | .HasColumnType("nvarchar(max)"); 174 | 175 | b.Property("UserId") 176 | .IsRequired() 177 | .HasColumnType("nvarchar(450)"); 178 | 179 | b.HasKey("LoginProvider", "ProviderKey"); 180 | 181 | b.HasIndex("UserId"); 182 | 183 | b.ToTable("AspNetUserLogins"); 184 | }); 185 | 186 | modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => 187 | { 188 | b.Property("UserId") 189 | .HasColumnType("nvarchar(450)"); 190 | 191 | b.Property("RoleId") 192 | .HasColumnType("nvarchar(450)"); 193 | 194 | b.HasKey("UserId", "RoleId"); 195 | 196 | b.HasIndex("RoleId"); 197 | 198 | b.ToTable("AspNetUserRoles"); 199 | }); 200 | 201 | modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => 202 | { 203 | b.Property("UserId") 204 | .HasColumnType("nvarchar(450)"); 205 | 206 | b.Property("LoginProvider") 207 | .HasColumnType("nvarchar(450)"); 208 | 209 | b.Property("Name") 210 | .HasColumnType("nvarchar(450)"); 211 | 212 | b.Property("Value") 213 | .HasColumnType("nvarchar(max)"); 214 | 215 | b.HasKey("UserId", "LoginProvider", "Name"); 216 | 217 | b.ToTable("AspNetUserTokens"); 218 | }); 219 | 220 | modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => 221 | { 222 | b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) 223 | .WithMany() 224 | .HasForeignKey("RoleId") 225 | .OnDelete(DeleteBehavior.Cascade) 226 | .IsRequired(); 227 | }); 228 | 229 | modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => 230 | { 231 | b.HasOne("Microsoft.AspNetCore.Identity.IdentityUser", null) 232 | .WithMany() 233 | .HasForeignKey("UserId") 234 | .OnDelete(DeleteBehavior.Cascade) 235 | .IsRequired(); 236 | }); 237 | 238 | modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => 239 | { 240 | b.HasOne("Microsoft.AspNetCore.Identity.IdentityUser", null) 241 | .WithMany() 242 | .HasForeignKey("UserId") 243 | .OnDelete(DeleteBehavior.Cascade) 244 | .IsRequired(); 245 | }); 246 | 247 | modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => 248 | { 249 | b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) 250 | .WithMany() 251 | .HasForeignKey("RoleId") 252 | .OnDelete(DeleteBehavior.Cascade) 253 | .IsRequired(); 254 | 255 | b.HasOne("Microsoft.AspNetCore.Identity.IdentityUser", null) 256 | .WithMany() 257 | .HasForeignKey("UserId") 258 | .OnDelete(DeleteBehavior.Cascade) 259 | .IsRequired(); 260 | }); 261 | 262 | modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => 263 | { 264 | b.HasOne("Microsoft.AspNetCore.Identity.IdentityUser", null) 265 | .WithMany() 266 | .HasForeignKey("UserId") 267 | .OnDelete(DeleteBehavior.Cascade) 268 | .IsRequired(); 269 | }); 270 | #pragma warning restore 612, 618 271 | } 272 | } 273 | } 274 | -------------------------------------------------------------------------------- /CookieAuthSample/CookieAuthSampleAPI/Migrations/20200123192549_First.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using Microsoft.EntityFrameworkCore.Migrations; 3 | 4 | namespace CookieAuthSampleAPI.Migrations 5 | { 6 | public partial class First : Migration 7 | { 8 | protected override void Up(MigrationBuilder migrationBuilder) 9 | { 10 | migrationBuilder.CreateTable( 11 | name: "AspNetRoles", 12 | columns: table => new 13 | { 14 | Id = table.Column(nullable: false), 15 | Name = table.Column(maxLength: 256, nullable: true), 16 | NormalizedName = table.Column(maxLength: 256, nullable: true), 17 | ConcurrencyStamp = table.Column(nullable: true) 18 | }, 19 | constraints: table => 20 | { 21 | table.PrimaryKey("PK_AspNetRoles", x => x.Id); 22 | }); 23 | 24 | migrationBuilder.CreateTable( 25 | name: "AspNetUsers", 26 | columns: table => new 27 | { 28 | Id = table.Column(nullable: false), 29 | UserName = table.Column(maxLength: 256, nullable: true), 30 | NormalizedUserName = table.Column(maxLength: 256, nullable: true), 31 | Email = table.Column(maxLength: 256, nullable: true), 32 | NormalizedEmail = table.Column(maxLength: 256, nullable: true), 33 | EmailConfirmed = table.Column(nullable: false), 34 | PasswordHash = table.Column(nullable: true), 35 | SecurityStamp = table.Column(nullable: true), 36 | ConcurrencyStamp = table.Column(nullable: true), 37 | PhoneNumber = table.Column(nullable: true), 38 | PhoneNumberConfirmed = table.Column(nullable: false), 39 | TwoFactorEnabled = table.Column(nullable: false), 40 | LockoutEnd = table.Column(nullable: true), 41 | LockoutEnabled = table.Column(nullable: false), 42 | AccessFailedCount = table.Column(nullable: false) 43 | }, 44 | constraints: table => 45 | { 46 | table.PrimaryKey("PK_AspNetUsers", x => x.Id); 47 | }); 48 | 49 | migrationBuilder.CreateTable( 50 | name: "AspNetRoleClaims", 51 | columns: table => new 52 | { 53 | Id = table.Column(nullable: false) 54 | .Annotation("SqlServer:Identity", "1, 1"), 55 | RoleId = table.Column(nullable: false), 56 | ClaimType = table.Column(nullable: true), 57 | ClaimValue = table.Column(nullable: true) 58 | }, 59 | constraints: table => 60 | { 61 | table.PrimaryKey("PK_AspNetRoleClaims", x => x.Id); 62 | table.ForeignKey( 63 | name: "FK_AspNetRoleClaims_AspNetRoles_RoleId", 64 | column: x => x.RoleId, 65 | principalTable: "AspNetRoles", 66 | principalColumn: "Id", 67 | onDelete: ReferentialAction.Cascade); 68 | }); 69 | 70 | migrationBuilder.CreateTable( 71 | name: "AspNetUserClaims", 72 | columns: table => new 73 | { 74 | Id = table.Column(nullable: false) 75 | .Annotation("SqlServer:Identity", "1, 1"), 76 | UserId = table.Column(nullable: false), 77 | ClaimType = table.Column(nullable: true), 78 | ClaimValue = table.Column(nullable: true) 79 | }, 80 | constraints: table => 81 | { 82 | table.PrimaryKey("PK_AspNetUserClaims", x => x.Id); 83 | table.ForeignKey( 84 | name: "FK_AspNetUserClaims_AspNetUsers_UserId", 85 | column: x => x.UserId, 86 | principalTable: "AspNetUsers", 87 | principalColumn: "Id", 88 | onDelete: ReferentialAction.Cascade); 89 | }); 90 | 91 | migrationBuilder.CreateTable( 92 | name: "AspNetUserLogins", 93 | columns: table => new 94 | { 95 | LoginProvider = table.Column(nullable: false), 96 | ProviderKey = table.Column(nullable: false), 97 | ProviderDisplayName = table.Column(nullable: true), 98 | UserId = table.Column(nullable: false) 99 | }, 100 | constraints: table => 101 | { 102 | table.PrimaryKey("PK_AspNetUserLogins", x => new { x.LoginProvider, x.ProviderKey }); 103 | table.ForeignKey( 104 | name: "FK_AspNetUserLogins_AspNetUsers_UserId", 105 | column: x => x.UserId, 106 | principalTable: "AspNetUsers", 107 | principalColumn: "Id", 108 | onDelete: ReferentialAction.Cascade); 109 | }); 110 | 111 | migrationBuilder.CreateTable( 112 | name: "AspNetUserRoles", 113 | columns: table => new 114 | { 115 | UserId = table.Column(nullable: false), 116 | RoleId = table.Column(nullable: false) 117 | }, 118 | constraints: table => 119 | { 120 | table.PrimaryKey("PK_AspNetUserRoles", x => new { x.UserId, x.RoleId }); 121 | table.ForeignKey( 122 | name: "FK_AspNetUserRoles_AspNetRoles_RoleId", 123 | column: x => x.RoleId, 124 | principalTable: "AspNetRoles", 125 | principalColumn: "Id", 126 | onDelete: ReferentialAction.Cascade); 127 | table.ForeignKey( 128 | name: "FK_AspNetUserRoles_AspNetUsers_UserId", 129 | column: x => x.UserId, 130 | principalTable: "AspNetUsers", 131 | principalColumn: "Id", 132 | onDelete: ReferentialAction.Cascade); 133 | }); 134 | 135 | migrationBuilder.CreateTable( 136 | name: "AspNetUserTokens", 137 | columns: table => new 138 | { 139 | UserId = table.Column(nullable: false), 140 | LoginProvider = table.Column(nullable: false), 141 | Name = table.Column(nullable: false), 142 | Value = table.Column(nullable: true) 143 | }, 144 | constraints: table => 145 | { 146 | table.PrimaryKey("PK_AspNetUserTokens", x => new { x.UserId, x.LoginProvider, x.Name }); 147 | table.ForeignKey( 148 | name: "FK_AspNetUserTokens_AspNetUsers_UserId", 149 | column: x => x.UserId, 150 | principalTable: "AspNetUsers", 151 | principalColumn: "Id", 152 | onDelete: ReferentialAction.Cascade); 153 | }); 154 | 155 | migrationBuilder.CreateIndex( 156 | name: "IX_AspNetRoleClaims_RoleId", 157 | table: "AspNetRoleClaims", 158 | column: "RoleId"); 159 | 160 | migrationBuilder.CreateIndex( 161 | name: "RoleNameIndex", 162 | table: "AspNetRoles", 163 | column: "NormalizedName", 164 | unique: true, 165 | filter: "[NormalizedName] IS NOT NULL"); 166 | 167 | migrationBuilder.CreateIndex( 168 | name: "IX_AspNetUserClaims_UserId", 169 | table: "AspNetUserClaims", 170 | column: "UserId"); 171 | 172 | migrationBuilder.CreateIndex( 173 | name: "IX_AspNetUserLogins_UserId", 174 | table: "AspNetUserLogins", 175 | column: "UserId"); 176 | 177 | migrationBuilder.CreateIndex( 178 | name: "IX_AspNetUserRoles_RoleId", 179 | table: "AspNetUserRoles", 180 | column: "RoleId"); 181 | 182 | migrationBuilder.CreateIndex( 183 | name: "EmailIndex", 184 | table: "AspNetUsers", 185 | column: "NormalizedEmail"); 186 | 187 | migrationBuilder.CreateIndex( 188 | name: "UserNameIndex", 189 | table: "AspNetUsers", 190 | column: "NormalizedUserName", 191 | unique: true, 192 | filter: "[NormalizedUserName] IS NOT NULL"); 193 | } 194 | 195 | protected override void Down(MigrationBuilder migrationBuilder) 196 | { 197 | migrationBuilder.DropTable( 198 | name: "AspNetRoleClaims"); 199 | 200 | migrationBuilder.DropTable( 201 | name: "AspNetUserClaims"); 202 | 203 | migrationBuilder.DropTable( 204 | name: "AspNetUserLogins"); 205 | 206 | migrationBuilder.DropTable( 207 | name: "AspNetUserRoles"); 208 | 209 | migrationBuilder.DropTable( 210 | name: "AspNetUserTokens"); 211 | 212 | migrationBuilder.DropTable( 213 | name: "AspNetRoles"); 214 | 215 | migrationBuilder.DropTable( 216 | name: "AspNetUsers"); 217 | } 218 | } 219 | } 220 | -------------------------------------------------------------------------------- /CookieAuthSample/CookieAuthSampleAPI/Migrations/ApplicationDbContextModelSnapshot.cs: -------------------------------------------------------------------------------- 1 | // 2 | using System; 3 | using CookieAuthSampleAPI.Data; 4 | using Microsoft.EntityFrameworkCore; 5 | using Microsoft.EntityFrameworkCore.Infrastructure; 6 | using Microsoft.EntityFrameworkCore.Metadata; 7 | using Microsoft.EntityFrameworkCore.Storage.ValueConversion; 8 | 9 | namespace CookieAuthSampleAPI.Migrations 10 | { 11 | [DbContext(typeof(ApplicationDbContext))] 12 | partial class ApplicationDbContextModelSnapshot : ModelSnapshot 13 | { 14 | protected override void BuildModel(ModelBuilder modelBuilder) 15 | { 16 | #pragma warning disable 612, 618 17 | modelBuilder 18 | .HasAnnotation("ProductVersion", "3.1.1") 19 | .HasAnnotation("Relational:MaxIdentifierLength", 128) 20 | .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); 21 | 22 | modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRole", b => 23 | { 24 | b.Property("Id") 25 | .HasColumnType("nvarchar(450)"); 26 | 27 | b.Property("ConcurrencyStamp") 28 | .IsConcurrencyToken() 29 | .HasColumnType("nvarchar(max)"); 30 | 31 | b.Property("Name") 32 | .HasColumnType("nvarchar(256)") 33 | .HasMaxLength(256); 34 | 35 | b.Property("NormalizedName") 36 | .HasColumnType("nvarchar(256)") 37 | .HasMaxLength(256); 38 | 39 | b.HasKey("Id"); 40 | 41 | b.HasIndex("NormalizedName") 42 | .IsUnique() 43 | .HasName("RoleNameIndex") 44 | .HasFilter("[NormalizedName] IS NOT NULL"); 45 | 46 | b.ToTable("AspNetRoles"); 47 | }); 48 | 49 | modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => 50 | { 51 | b.Property("Id") 52 | .ValueGeneratedOnAdd() 53 | .HasColumnType("int") 54 | .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); 55 | 56 | b.Property("ClaimType") 57 | .HasColumnType("nvarchar(max)"); 58 | 59 | b.Property("ClaimValue") 60 | .HasColumnType("nvarchar(max)"); 61 | 62 | b.Property("RoleId") 63 | .IsRequired() 64 | .HasColumnType("nvarchar(450)"); 65 | 66 | b.HasKey("Id"); 67 | 68 | b.HasIndex("RoleId"); 69 | 70 | b.ToTable("AspNetRoleClaims"); 71 | }); 72 | 73 | modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUser", b => 74 | { 75 | b.Property("Id") 76 | .HasColumnType("nvarchar(450)"); 77 | 78 | b.Property("AccessFailedCount") 79 | .HasColumnType("int"); 80 | 81 | b.Property("ConcurrencyStamp") 82 | .IsConcurrencyToken() 83 | .HasColumnType("nvarchar(max)"); 84 | 85 | b.Property("Email") 86 | .HasColumnType("nvarchar(256)") 87 | .HasMaxLength(256); 88 | 89 | b.Property("EmailConfirmed") 90 | .HasColumnType("bit"); 91 | 92 | b.Property("LockoutEnabled") 93 | .HasColumnType("bit"); 94 | 95 | b.Property("LockoutEnd") 96 | .HasColumnType("datetimeoffset"); 97 | 98 | b.Property("NormalizedEmail") 99 | .HasColumnType("nvarchar(256)") 100 | .HasMaxLength(256); 101 | 102 | b.Property("NormalizedUserName") 103 | .HasColumnType("nvarchar(256)") 104 | .HasMaxLength(256); 105 | 106 | b.Property("PasswordHash") 107 | .HasColumnType("nvarchar(max)"); 108 | 109 | b.Property("PhoneNumber") 110 | .HasColumnType("nvarchar(max)"); 111 | 112 | b.Property("PhoneNumberConfirmed") 113 | .HasColumnType("bit"); 114 | 115 | b.Property("SecurityStamp") 116 | .HasColumnType("nvarchar(max)"); 117 | 118 | b.Property("TwoFactorEnabled") 119 | .HasColumnType("bit"); 120 | 121 | b.Property("UserName") 122 | .HasColumnType("nvarchar(256)") 123 | .HasMaxLength(256); 124 | 125 | b.HasKey("Id"); 126 | 127 | b.HasIndex("NormalizedEmail") 128 | .HasName("EmailIndex"); 129 | 130 | b.HasIndex("NormalizedUserName") 131 | .IsUnique() 132 | .HasName("UserNameIndex") 133 | .HasFilter("[NormalizedUserName] IS NOT NULL"); 134 | 135 | b.ToTable("AspNetUsers"); 136 | }); 137 | 138 | modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => 139 | { 140 | b.Property("Id") 141 | .ValueGeneratedOnAdd() 142 | .HasColumnType("int") 143 | .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); 144 | 145 | b.Property("ClaimType") 146 | .HasColumnType("nvarchar(max)"); 147 | 148 | b.Property("ClaimValue") 149 | .HasColumnType("nvarchar(max)"); 150 | 151 | b.Property("UserId") 152 | .IsRequired() 153 | .HasColumnType("nvarchar(450)"); 154 | 155 | b.HasKey("Id"); 156 | 157 | b.HasIndex("UserId"); 158 | 159 | b.ToTable("AspNetUserClaims"); 160 | }); 161 | 162 | modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => 163 | { 164 | b.Property("LoginProvider") 165 | .HasColumnType("nvarchar(450)"); 166 | 167 | b.Property("ProviderKey") 168 | .HasColumnType("nvarchar(450)"); 169 | 170 | b.Property("ProviderDisplayName") 171 | .HasColumnType("nvarchar(max)"); 172 | 173 | b.Property("UserId") 174 | .IsRequired() 175 | .HasColumnType("nvarchar(450)"); 176 | 177 | b.HasKey("LoginProvider", "ProviderKey"); 178 | 179 | b.HasIndex("UserId"); 180 | 181 | b.ToTable("AspNetUserLogins"); 182 | }); 183 | 184 | modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => 185 | { 186 | b.Property("UserId") 187 | .HasColumnType("nvarchar(450)"); 188 | 189 | b.Property("RoleId") 190 | .HasColumnType("nvarchar(450)"); 191 | 192 | b.HasKey("UserId", "RoleId"); 193 | 194 | b.HasIndex("RoleId"); 195 | 196 | b.ToTable("AspNetUserRoles"); 197 | }); 198 | 199 | modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => 200 | { 201 | b.Property("UserId") 202 | .HasColumnType("nvarchar(450)"); 203 | 204 | b.Property("LoginProvider") 205 | .HasColumnType("nvarchar(450)"); 206 | 207 | b.Property("Name") 208 | .HasColumnType("nvarchar(450)"); 209 | 210 | b.Property("Value") 211 | .HasColumnType("nvarchar(max)"); 212 | 213 | b.HasKey("UserId", "LoginProvider", "Name"); 214 | 215 | b.ToTable("AspNetUserTokens"); 216 | }); 217 | 218 | modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => 219 | { 220 | b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) 221 | .WithMany() 222 | .HasForeignKey("RoleId") 223 | .OnDelete(DeleteBehavior.Cascade) 224 | .IsRequired(); 225 | }); 226 | 227 | modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => 228 | { 229 | b.HasOne("Microsoft.AspNetCore.Identity.IdentityUser", null) 230 | .WithMany() 231 | .HasForeignKey("UserId") 232 | .OnDelete(DeleteBehavior.Cascade) 233 | .IsRequired(); 234 | }); 235 | 236 | modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => 237 | { 238 | b.HasOne("Microsoft.AspNetCore.Identity.IdentityUser", null) 239 | .WithMany() 240 | .HasForeignKey("UserId") 241 | .OnDelete(DeleteBehavior.Cascade) 242 | .IsRequired(); 243 | }); 244 | 245 | modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => 246 | { 247 | b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) 248 | .WithMany() 249 | .HasForeignKey("RoleId") 250 | .OnDelete(DeleteBehavior.Cascade) 251 | .IsRequired(); 252 | 253 | b.HasOne("Microsoft.AspNetCore.Identity.IdentityUser", null) 254 | .WithMany() 255 | .HasForeignKey("UserId") 256 | .OnDelete(DeleteBehavior.Cascade) 257 | .IsRequired(); 258 | }); 259 | 260 | modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => 261 | { 262 | b.HasOne("Microsoft.AspNetCore.Identity.IdentityUser", null) 263 | .WithMany() 264 | .HasForeignKey("UserId") 265 | .OnDelete(DeleteBehavior.Cascade) 266 | .IsRequired(); 267 | }); 268 | #pragma warning restore 612, 618 269 | } 270 | } 271 | } 272 | -------------------------------------------------------------------------------- /CookieAuthSample/CookieAuthSampleAPI/Models/LoginCredentials.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Threading.Tasks; 5 | 6 | namespace CookieAuthSampleAPI.Models 7 | { 8 | public class LoginCredentials 9 | { 10 | public string Username { get; set; } 11 | 12 | public string Password { get; set; } 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /CookieAuthSample/CookieAuthSampleAPI/Models/UserDetails.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.ComponentModel.DataAnnotations; 4 | using System.Linq; 5 | using System.Threading.Tasks; 6 | 7 | namespace CookieAuthSampleAPI.Models 8 | { 9 | public class UserDetails 10 | { 11 | [Required] 12 | public string UserName { get; set; } 13 | 14 | [Required] 15 | public string Password { get; set; } 16 | 17 | [Required] 18 | public string Email { get; set; } 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /CookieAuthSample/CookieAuthSampleAPI/Models/WeatherForecast.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace CookieAuthSampleAPI.Models 4 | { 5 | public class WeatherForecast 6 | { 7 | public DateTime Date { get; set; } 8 | 9 | public int TemperatureC { get; set; } 10 | 11 | public int TemperatureF => 32 + (int)(TemperatureC / 0.5556); 12 | 13 | public string Summary { get; set; } 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /CookieAuthSample/CookieAuthSampleAPI/Program.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Threading.Tasks; 5 | using Microsoft.AspNetCore.Hosting; 6 | using Microsoft.Extensions.Configuration; 7 | using Microsoft.Extensions.Hosting; 8 | using Microsoft.Extensions.Logging; 9 | 10 | namespace CookieAuthSampleAPI 11 | { 12 | public class Program 13 | { 14 | public static void Main(string[] args) 15 | { 16 | CreateHostBuilder(args).Build().Run(); 17 | } 18 | 19 | public static IHostBuilder CreateHostBuilder(string[] args) => 20 | Host.CreateDefaultBuilder(args) 21 | .ConfigureWebHostDefaults(webBuilder => 22 | { 23 | webBuilder.UseStartup(); 24 | }); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /CookieAuthSample/CookieAuthSampleAPI/Properties/launchSettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "http://json.schemastore.org/launchsettings.json", 3 | "iisSettings": { 4 | "windowsAuthentication": false, 5 | "anonymousAuthentication": true, 6 | "iisExpress": { 7 | "applicationUrl": "http://localhost:61610", 8 | "sslPort": 44322 9 | } 10 | }, 11 | "profiles": { 12 | "IIS Express": { 13 | "commandName": "IISExpress", 14 | "launchBrowser": true, 15 | "launchUrl": "weatherforecast", 16 | "environmentVariables": { 17 | "ASPNETCORE_ENVIRONMENT": "Development" 18 | } 19 | }, 20 | "CookieAuthSampleAPI": { 21 | "commandName": "Project", 22 | "launchBrowser": true, 23 | "launchUrl": "weatherforecast", 24 | "applicationUrl": "https://localhost:5001;http://localhost:5000", 25 | "environmentVariables": { 26 | "ASPNETCORE_ENVIRONMENT": "Development" 27 | } 28 | } 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /CookieAuthSample/CookieAuthSampleAPI/Startup.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Threading.Tasks; 5 | using CookieAuthSampleAPI.Data; 6 | using Microsoft.AspNetCore.Authentication.Cookies; 7 | using Microsoft.AspNetCore.Builder; 8 | using Microsoft.AspNetCore.Hosting; 9 | using Microsoft.AspNetCore.HttpsPolicy; 10 | using Microsoft.AspNetCore.Identity; 11 | using Microsoft.AspNetCore.Mvc; 12 | using Microsoft.EntityFrameworkCore; 13 | using Microsoft.Extensions.Configuration; 14 | using Microsoft.Extensions.DependencyInjection; 15 | using Microsoft.Extensions.Hosting; 16 | using Microsoft.Extensions.Logging; 17 | 18 | namespace CookieAuthSampleAPI 19 | { 20 | public class Startup 21 | { 22 | public Startup(IConfiguration configuration) 23 | { 24 | Configuration = configuration; 25 | } 26 | 27 | public IConfiguration Configuration { get; } 28 | 29 | // This method gets called by the runtime. Use this method to add services to the container. 30 | public void ConfigureServices(IServiceCollection services) 31 | { 32 | services.AddDbContext(options => 33 | options.UseSqlServer(Configuration.GetConnectionString("SqlConnection"))); 34 | 35 | services.AddIdentity(options => options.SignIn.RequireConfirmedAccount = true) 36 | .AddEntityFrameworkStores(); 37 | 38 | services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme) 39 | .AddCookie(CookieAuthenticationDefaults.AuthenticationScheme, options => 40 | { 41 | options.SlidingExpiration = true; 42 | options.ExpireTimeSpan = new TimeSpan(0, 1, 0); 43 | }); 44 | 45 | services.AddControllers(); 46 | } 47 | 48 | // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. 49 | public void Configure(IApplicationBuilder app, IWebHostEnvironment env) 50 | { 51 | if (env.IsDevelopment()) 52 | { 53 | app.UseDeveloperExceptionPage(); 54 | } 55 | 56 | app.UseHttpsRedirection(); 57 | 58 | app.UseRouting(); 59 | 60 | app.UseAuthentication(); 61 | 62 | app.UseAuthorization(); 63 | 64 | app.UseEndpoints(endpoints => 65 | { 66 | endpoints.MapControllers(); 67 | }); 68 | } 69 | } 70 | } 71 | -------------------------------------------------------------------------------- /CookieAuthSample/CookieAuthSampleAPI/appsettings.Development.json: -------------------------------------------------------------------------------- 1 | { 2 | "Logging": { 3 | "LogLevel": { 4 | "Default": "Information", 5 | "Microsoft": "Warning", 6 | "Microsoft.Hosting.Lifetime": "Information" 7 | } 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /CookieAuthSample/CookieAuthSampleAPI/appsettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "Logging": { 3 | "LogLevel": { 4 | "Default": "Information", 5 | "Microsoft": "Warning", 6 | "Microsoft.Hosting.Lifetime": "Information" 7 | } 8 | }, 9 | 10 | "ConnectionStrings": { 11 | "SqlConnection": "Server=(localdb)\\MSSQLLocalDB;Initial Catalog=MyAppDb; Integrated Security=true;" 12 | }, 13 | 14 | "AllowedHosts": "*" 15 | } 16 | -------------------------------------------------------------------------------- /CookieAuthSample/Postman-Collection/CookieAuthSample.postman_collection.json: -------------------------------------------------------------------------------- 1 | { 2 | "info": { 3 | "_postman_id": "60255ce2-ab95-426f-9bcc-6a75d849c95e", 4 | "name": "CookieAuthSample", 5 | "schema": "https://schema.getpostman.com/json/collection/v2.1.0/collection.json" 6 | }, 7 | "item": [ 8 | { 9 | "name": "User Registration", 10 | "request": { 11 | "method": "POST", 12 | "header": [ 13 | { 14 | "key": "Accept", 15 | "value": "application/json", 16 | "type": "text" 17 | }, 18 | { 19 | "key": "Content-Type", 20 | "value": "application/json", 21 | "type": "text" 22 | } 23 | ], 24 | "body": { 25 | "mode": "raw", 26 | "raw": "{\n\t\"username\": \"test\",\n\t\"password\": \"Test@12345\",\n\t\"email\": \"abc@abc.com\"\n}" 27 | }, 28 | "url": { 29 | "raw": "https://localhost:44322/api/auth/register", 30 | "protocol": "https", 31 | "host": [ 32 | "localhost" 33 | ], 34 | "port": "44322", 35 | "path": [ 36 | "api", 37 | "auth", 38 | "register" 39 | ], 40 | "query": [ 41 | { 42 | "key": "username", 43 | "value": "test", 44 | "disabled": true 45 | }, 46 | { 47 | "key": "password", 48 | "value": "testpassword", 49 | "disabled": true 50 | } 51 | ] 52 | } 53 | }, 54 | "response": [] 55 | }, 56 | { 57 | "name": "Login", 58 | "request": { 59 | "method": "POST", 60 | "header": [ 61 | { 62 | "key": "Accept", 63 | "value": "application/json", 64 | "type": "text" 65 | }, 66 | { 67 | "key": "Content-Type", 68 | "value": "application/json", 69 | "type": "text" 70 | } 71 | ], 72 | "body": { 73 | "mode": "raw", 74 | "raw": "{\n\t\"username\": \"test\",\n\t\"password\": \"Test@12345\"\n}" 75 | }, 76 | "url": { 77 | "raw": "https://localhost:44322/api/auth/login", 78 | "protocol": "https", 79 | "host": [ 80 | "localhost" 81 | ], 82 | "port": "44322", 83 | "path": [ 84 | "api", 85 | "auth", 86 | "login" 87 | ] 88 | }, 89 | "description": "Login to get the cookie" 90 | }, 91 | "response": [] 92 | }, 93 | { 94 | "name": "Weather Forecast", 95 | "request": { 96 | "method": "GET", 97 | "header": [], 98 | "url": { 99 | "raw": "https://localhost:44322/api/weatherforecast", 100 | "protocol": "https", 101 | "host": [ 102 | "localhost" 103 | ], 104 | "port": "44322", 105 | "path": [ 106 | "api", 107 | "weatherforecast" 108 | ] 109 | } 110 | }, 111 | "response": [] 112 | }, 113 | { 114 | "name": "Logout", 115 | "request": { 116 | "method": "POST", 117 | "header": [ 118 | { 119 | "key": "Accept", 120 | "value": "application/json", 121 | "type": "text" 122 | }, 123 | { 124 | "key": "Content-Type", 125 | "value": "application/json", 126 | "type": "text" 127 | } 128 | ], 129 | "body": { 130 | "mode": "raw", 131 | "raw": "{\n\t\"username\": \"test\",\n\t\"password\": \"Test@12345\"\n}" 132 | }, 133 | "url": { 134 | "raw": "https://localhost:44322/api/auth/login", 135 | "protocol": "https", 136 | "host": [ 137 | "localhost" 138 | ], 139 | "port": "44322", 140 | "path": [ 141 | "api", 142 | "auth", 143 | "login" 144 | ] 145 | }, 146 | "description": "Login to get the cookie" 147 | }, 148 | "response": [] 149 | } 150 | ], 151 | "protocolProfileBehavior": {} 152 | } -------------------------------------------------------------------------------- /IdentityConfigurations/IdentityConfigurationSample.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio Version 16 4 | VisualStudioVersion = 16.0.29613.14 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "IdentityConfigurationSample", "IdentityConfigurationSample\IdentityConfigurationSample.csproj", "{37A59213-4E19-4D6F-A7D5-3EC636FDDFBD}" 7 | EndProject 8 | Global 9 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 10 | Debug|Any CPU = Debug|Any CPU 11 | Release|Any CPU = Release|Any CPU 12 | EndGlobalSection 13 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 14 | {37A59213-4E19-4D6F-A7D5-3EC636FDDFBD}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 15 | {37A59213-4E19-4D6F-A7D5-3EC636FDDFBD}.Debug|Any CPU.Build.0 = Debug|Any CPU 16 | {37A59213-4E19-4D6F-A7D5-3EC636FDDFBD}.Release|Any CPU.ActiveCfg = Release|Any CPU 17 | {37A59213-4E19-4D6F-A7D5-3EC636FDDFBD}.Release|Any CPU.Build.0 = Release|Any CPU 18 | EndGlobalSection 19 | GlobalSection(SolutionProperties) = preSolution 20 | HideSolutionNode = FALSE 21 | EndGlobalSection 22 | GlobalSection(ExtensibilityGlobals) = postSolution 23 | SolutionGuid = {D3545E52-87EF-46B9-A4C5-7BABF1053564} 24 | EndGlobalSection 25 | EndGlobal 26 | -------------------------------------------------------------------------------- /IdentityConfigurations/IdentityConfigurationSample/Controllers/WeatherForecastController.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using IdentityConfigurationSample.Models; 5 | using Microsoft.AspNetCore.Mvc; 6 | using Microsoft.Extensions.Logging; 7 | 8 | namespace IdentityConfigurationSample.Controllers 9 | { 10 | [ApiController] 11 | [Route("api/[controller]")] 12 | public class WeatherForecastController : ControllerBase 13 | { 14 | private static readonly string[] Summaries = new[] 15 | { 16 | "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching" 17 | }; 18 | 19 | private readonly ILogger _logger; 20 | 21 | public WeatherForecastController(ILogger logger) 22 | { 23 | _logger = logger; 24 | } 25 | 26 | [HttpGet] 27 | public IEnumerable Get() 28 | { 29 | var rng = new Random(); 30 | return Enumerable.Range(1, 5).Select(index => new WeatherForecast 31 | { 32 | Date = DateTime.Now.AddDays(index), 33 | TemperatureC = rng.Next(-20, 55), 34 | Summary = Summaries[rng.Next(Summaries.Length)] 35 | }) 36 | .ToArray(); 37 | } 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /IdentityConfigurations/IdentityConfigurationSample/Data/ApplicationDbContext.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Identity; 2 | using Microsoft.AspNetCore.Identity.EntityFrameworkCore; 3 | using Microsoft.EntityFrameworkCore; 4 | 5 | namespace IdentityConfigurationSample.Data 6 | { 7 | public class ApplicationDbContext : IdentityDbContext 8 | { 9 | public ApplicationDbContext(DbContextOptions options) : base(options) 10 | { 11 | 12 | } 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /IdentityConfigurations/IdentityConfigurationSample/IdentityConfigurationSample.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | netcoreapp3.1 5 | 6 | 7 | 8 | 9 | 10 | 11 | all 12 | runtime; build; native; contentfiles; analyzers; buildtransitive 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | -------------------------------------------------------------------------------- /IdentityConfigurations/IdentityConfigurationSample/Migrations/20200123192549_First.Designer.cs: -------------------------------------------------------------------------------- 1 | // 2 | using System; 3 | using IdentityConfigurationSample.Data; 4 | using Microsoft.EntityFrameworkCore; 5 | using Microsoft.EntityFrameworkCore.Infrastructure; 6 | using Microsoft.EntityFrameworkCore.Metadata; 7 | using Microsoft.EntityFrameworkCore.Migrations; 8 | using Microsoft.EntityFrameworkCore.Storage.ValueConversion; 9 | 10 | namespace IdentityConfigurationSample.Migrations 11 | { 12 | [DbContext(typeof(ApplicationDbContext))] 13 | [Migration("20200123192549_First")] 14 | partial class First 15 | { 16 | protected override void BuildTargetModel(ModelBuilder modelBuilder) 17 | { 18 | #pragma warning disable 612, 618 19 | modelBuilder 20 | .HasAnnotation("ProductVersion", "3.1.1") 21 | .HasAnnotation("Relational:MaxIdentifierLength", 128) 22 | .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); 23 | 24 | modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRole", b => 25 | { 26 | b.Property("Id") 27 | .HasColumnType("nvarchar(450)"); 28 | 29 | b.Property("ConcurrencyStamp") 30 | .IsConcurrencyToken() 31 | .HasColumnType("nvarchar(max)"); 32 | 33 | b.Property("Name") 34 | .HasColumnType("nvarchar(256)") 35 | .HasMaxLength(256); 36 | 37 | b.Property("NormalizedName") 38 | .HasColumnType("nvarchar(256)") 39 | .HasMaxLength(256); 40 | 41 | b.HasKey("Id"); 42 | 43 | b.HasIndex("NormalizedName") 44 | .IsUnique() 45 | .HasName("RoleNameIndex") 46 | .HasFilter("[NormalizedName] IS NOT NULL"); 47 | 48 | b.ToTable("AspNetRoles"); 49 | }); 50 | 51 | modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => 52 | { 53 | b.Property("Id") 54 | .ValueGeneratedOnAdd() 55 | .HasColumnType("int") 56 | .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); 57 | 58 | b.Property("ClaimType") 59 | .HasColumnType("nvarchar(max)"); 60 | 61 | b.Property("ClaimValue") 62 | .HasColumnType("nvarchar(max)"); 63 | 64 | b.Property("RoleId") 65 | .IsRequired() 66 | .HasColumnType("nvarchar(450)"); 67 | 68 | b.HasKey("Id"); 69 | 70 | b.HasIndex("RoleId"); 71 | 72 | b.ToTable("AspNetRoleClaims"); 73 | }); 74 | 75 | modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUser", b => 76 | { 77 | b.Property("Id") 78 | .HasColumnType("nvarchar(450)"); 79 | 80 | b.Property("AccessFailedCount") 81 | .HasColumnType("int"); 82 | 83 | b.Property("ConcurrencyStamp") 84 | .IsConcurrencyToken() 85 | .HasColumnType("nvarchar(max)"); 86 | 87 | b.Property("Email") 88 | .HasColumnType("nvarchar(256)") 89 | .HasMaxLength(256); 90 | 91 | b.Property("EmailConfirmed") 92 | .HasColumnType("bit"); 93 | 94 | b.Property("LockoutEnabled") 95 | .HasColumnType("bit"); 96 | 97 | b.Property("LockoutEnd") 98 | .HasColumnType("datetimeoffset"); 99 | 100 | b.Property("NormalizedEmail") 101 | .HasColumnType("nvarchar(256)") 102 | .HasMaxLength(256); 103 | 104 | b.Property("NormalizedUserName") 105 | .HasColumnType("nvarchar(256)") 106 | .HasMaxLength(256); 107 | 108 | b.Property("PasswordHash") 109 | .HasColumnType("nvarchar(max)"); 110 | 111 | b.Property("PhoneNumber") 112 | .HasColumnType("nvarchar(max)"); 113 | 114 | b.Property("PhoneNumberConfirmed") 115 | .HasColumnType("bit"); 116 | 117 | b.Property("SecurityStamp") 118 | .HasColumnType("nvarchar(max)"); 119 | 120 | b.Property("TwoFactorEnabled") 121 | .HasColumnType("bit"); 122 | 123 | b.Property("UserName") 124 | .HasColumnType("nvarchar(256)") 125 | .HasMaxLength(256); 126 | 127 | b.HasKey("Id"); 128 | 129 | b.HasIndex("NormalizedEmail") 130 | .HasName("EmailIndex"); 131 | 132 | b.HasIndex("NormalizedUserName") 133 | .IsUnique() 134 | .HasName("UserNameIndex") 135 | .HasFilter("[NormalizedUserName] IS NOT NULL"); 136 | 137 | b.ToTable("AspNetUsers"); 138 | }); 139 | 140 | modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => 141 | { 142 | b.Property("Id") 143 | .ValueGeneratedOnAdd() 144 | .HasColumnType("int") 145 | .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); 146 | 147 | b.Property("ClaimType") 148 | .HasColumnType("nvarchar(max)"); 149 | 150 | b.Property("ClaimValue") 151 | .HasColumnType("nvarchar(max)"); 152 | 153 | b.Property("UserId") 154 | .IsRequired() 155 | .HasColumnType("nvarchar(450)"); 156 | 157 | b.HasKey("Id"); 158 | 159 | b.HasIndex("UserId"); 160 | 161 | b.ToTable("AspNetUserClaims"); 162 | }); 163 | 164 | modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => 165 | { 166 | b.Property("LoginProvider") 167 | .HasColumnType("nvarchar(450)"); 168 | 169 | b.Property("ProviderKey") 170 | .HasColumnType("nvarchar(450)"); 171 | 172 | b.Property("ProviderDisplayName") 173 | .HasColumnType("nvarchar(max)"); 174 | 175 | b.Property("UserId") 176 | .IsRequired() 177 | .HasColumnType("nvarchar(450)"); 178 | 179 | b.HasKey("LoginProvider", "ProviderKey"); 180 | 181 | b.HasIndex("UserId"); 182 | 183 | b.ToTable("AspNetUserLogins"); 184 | }); 185 | 186 | modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => 187 | { 188 | b.Property("UserId") 189 | .HasColumnType("nvarchar(450)"); 190 | 191 | b.Property("RoleId") 192 | .HasColumnType("nvarchar(450)"); 193 | 194 | b.HasKey("UserId", "RoleId"); 195 | 196 | b.HasIndex("RoleId"); 197 | 198 | b.ToTable("AspNetUserRoles"); 199 | }); 200 | 201 | modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => 202 | { 203 | b.Property("UserId") 204 | .HasColumnType("nvarchar(450)"); 205 | 206 | b.Property("LoginProvider") 207 | .HasColumnType("nvarchar(450)"); 208 | 209 | b.Property("Name") 210 | .HasColumnType("nvarchar(450)"); 211 | 212 | b.Property("Value") 213 | .HasColumnType("nvarchar(max)"); 214 | 215 | b.HasKey("UserId", "LoginProvider", "Name"); 216 | 217 | b.ToTable("AspNetUserTokens"); 218 | }); 219 | 220 | modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => 221 | { 222 | b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) 223 | .WithMany() 224 | .HasForeignKey("RoleId") 225 | .OnDelete(DeleteBehavior.Cascade) 226 | .IsRequired(); 227 | }); 228 | 229 | modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => 230 | { 231 | b.HasOne("Microsoft.AspNetCore.Identity.IdentityUser", null) 232 | .WithMany() 233 | .HasForeignKey("UserId") 234 | .OnDelete(DeleteBehavior.Cascade) 235 | .IsRequired(); 236 | }); 237 | 238 | modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => 239 | { 240 | b.HasOne("Microsoft.AspNetCore.Identity.IdentityUser", null) 241 | .WithMany() 242 | .HasForeignKey("UserId") 243 | .OnDelete(DeleteBehavior.Cascade) 244 | .IsRequired(); 245 | }); 246 | 247 | modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => 248 | { 249 | b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) 250 | .WithMany() 251 | .HasForeignKey("RoleId") 252 | .OnDelete(DeleteBehavior.Cascade) 253 | .IsRequired(); 254 | 255 | b.HasOne("Microsoft.AspNetCore.Identity.IdentityUser", null) 256 | .WithMany() 257 | .HasForeignKey("UserId") 258 | .OnDelete(DeleteBehavior.Cascade) 259 | .IsRequired(); 260 | }); 261 | 262 | modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => 263 | { 264 | b.HasOne("Microsoft.AspNetCore.Identity.IdentityUser", null) 265 | .WithMany() 266 | .HasForeignKey("UserId") 267 | .OnDelete(DeleteBehavior.Cascade) 268 | .IsRequired(); 269 | }); 270 | #pragma warning restore 612, 618 271 | } 272 | } 273 | } 274 | -------------------------------------------------------------------------------- /IdentityConfigurations/IdentityConfigurationSample/Migrations/20200123192549_First.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using Microsoft.EntityFrameworkCore.Migrations; 3 | 4 | namespace IdentityConfigurationSample.Migrations 5 | { 6 | public partial class First : Migration 7 | { 8 | protected override void Up(MigrationBuilder migrationBuilder) 9 | { 10 | migrationBuilder.CreateTable( 11 | name: "AspNetRoles", 12 | columns: table => new 13 | { 14 | Id = table.Column(nullable: false), 15 | Name = table.Column(maxLength: 256, nullable: true), 16 | NormalizedName = table.Column(maxLength: 256, nullable: true), 17 | ConcurrencyStamp = table.Column(nullable: true) 18 | }, 19 | constraints: table => 20 | { 21 | table.PrimaryKey("PK_AspNetRoles", x => x.Id); 22 | }); 23 | 24 | migrationBuilder.CreateTable( 25 | name: "AspNetUsers", 26 | columns: table => new 27 | { 28 | Id = table.Column(nullable: false), 29 | UserName = table.Column(maxLength: 256, nullable: true), 30 | NormalizedUserName = table.Column(maxLength: 256, nullable: true), 31 | Email = table.Column(maxLength: 256, nullable: true), 32 | NormalizedEmail = table.Column(maxLength: 256, nullable: true), 33 | EmailConfirmed = table.Column(nullable: false), 34 | PasswordHash = table.Column(nullable: true), 35 | SecurityStamp = table.Column(nullable: true), 36 | ConcurrencyStamp = table.Column(nullable: true), 37 | PhoneNumber = table.Column(nullable: true), 38 | PhoneNumberConfirmed = table.Column(nullable: false), 39 | TwoFactorEnabled = table.Column(nullable: false), 40 | LockoutEnd = table.Column(nullable: true), 41 | LockoutEnabled = table.Column(nullable: false), 42 | AccessFailedCount = table.Column(nullable: false) 43 | }, 44 | constraints: table => 45 | { 46 | table.PrimaryKey("PK_AspNetUsers", x => x.Id); 47 | }); 48 | 49 | migrationBuilder.CreateTable( 50 | name: "AspNetRoleClaims", 51 | columns: table => new 52 | { 53 | Id = table.Column(nullable: false) 54 | .Annotation("SqlServer:Identity", "1, 1"), 55 | RoleId = table.Column(nullable: false), 56 | ClaimType = table.Column(nullable: true), 57 | ClaimValue = table.Column(nullable: true) 58 | }, 59 | constraints: table => 60 | { 61 | table.PrimaryKey("PK_AspNetRoleClaims", x => x.Id); 62 | table.ForeignKey( 63 | name: "FK_AspNetRoleClaims_AspNetRoles_RoleId", 64 | column: x => x.RoleId, 65 | principalTable: "AspNetRoles", 66 | principalColumn: "Id", 67 | onDelete: ReferentialAction.Cascade); 68 | }); 69 | 70 | migrationBuilder.CreateTable( 71 | name: "AspNetUserClaims", 72 | columns: table => new 73 | { 74 | Id = table.Column(nullable: false) 75 | .Annotation("SqlServer:Identity", "1, 1"), 76 | UserId = table.Column(nullable: false), 77 | ClaimType = table.Column(nullable: true), 78 | ClaimValue = table.Column(nullable: true) 79 | }, 80 | constraints: table => 81 | { 82 | table.PrimaryKey("PK_AspNetUserClaims", x => x.Id); 83 | table.ForeignKey( 84 | name: "FK_AspNetUserClaims_AspNetUsers_UserId", 85 | column: x => x.UserId, 86 | principalTable: "AspNetUsers", 87 | principalColumn: "Id", 88 | onDelete: ReferentialAction.Cascade); 89 | }); 90 | 91 | migrationBuilder.CreateTable( 92 | name: "AspNetUserLogins", 93 | columns: table => new 94 | { 95 | LoginProvider = table.Column(nullable: false), 96 | ProviderKey = table.Column(nullable: false), 97 | ProviderDisplayName = table.Column(nullable: true), 98 | UserId = table.Column(nullable: false) 99 | }, 100 | constraints: table => 101 | { 102 | table.PrimaryKey("PK_AspNetUserLogins", x => new { x.LoginProvider, x.ProviderKey }); 103 | table.ForeignKey( 104 | name: "FK_AspNetUserLogins_AspNetUsers_UserId", 105 | column: x => x.UserId, 106 | principalTable: "AspNetUsers", 107 | principalColumn: "Id", 108 | onDelete: ReferentialAction.Cascade); 109 | }); 110 | 111 | migrationBuilder.CreateTable( 112 | name: "AspNetUserRoles", 113 | columns: table => new 114 | { 115 | UserId = table.Column(nullable: false), 116 | RoleId = table.Column(nullable: false) 117 | }, 118 | constraints: table => 119 | { 120 | table.PrimaryKey("PK_AspNetUserRoles", x => new { x.UserId, x.RoleId }); 121 | table.ForeignKey( 122 | name: "FK_AspNetUserRoles_AspNetRoles_RoleId", 123 | column: x => x.RoleId, 124 | principalTable: "AspNetRoles", 125 | principalColumn: "Id", 126 | onDelete: ReferentialAction.Cascade); 127 | table.ForeignKey( 128 | name: "FK_AspNetUserRoles_AspNetUsers_UserId", 129 | column: x => x.UserId, 130 | principalTable: "AspNetUsers", 131 | principalColumn: "Id", 132 | onDelete: ReferentialAction.Cascade); 133 | }); 134 | 135 | migrationBuilder.CreateTable( 136 | name: "AspNetUserTokens", 137 | columns: table => new 138 | { 139 | UserId = table.Column(nullable: false), 140 | LoginProvider = table.Column(nullable: false), 141 | Name = table.Column(nullable: false), 142 | Value = table.Column(nullable: true) 143 | }, 144 | constraints: table => 145 | { 146 | table.PrimaryKey("PK_AspNetUserTokens", x => new { x.UserId, x.LoginProvider, x.Name }); 147 | table.ForeignKey( 148 | name: "FK_AspNetUserTokens_AspNetUsers_UserId", 149 | column: x => x.UserId, 150 | principalTable: "AspNetUsers", 151 | principalColumn: "Id", 152 | onDelete: ReferentialAction.Cascade); 153 | }); 154 | 155 | migrationBuilder.CreateIndex( 156 | name: "IX_AspNetRoleClaims_RoleId", 157 | table: "AspNetRoleClaims", 158 | column: "RoleId"); 159 | 160 | migrationBuilder.CreateIndex( 161 | name: "RoleNameIndex", 162 | table: "AspNetRoles", 163 | column: "NormalizedName", 164 | unique: true, 165 | filter: "[NormalizedName] IS NOT NULL"); 166 | 167 | migrationBuilder.CreateIndex( 168 | name: "IX_AspNetUserClaims_UserId", 169 | table: "AspNetUserClaims", 170 | column: "UserId"); 171 | 172 | migrationBuilder.CreateIndex( 173 | name: "IX_AspNetUserLogins_UserId", 174 | table: "AspNetUserLogins", 175 | column: "UserId"); 176 | 177 | migrationBuilder.CreateIndex( 178 | name: "IX_AspNetUserRoles_RoleId", 179 | table: "AspNetUserRoles", 180 | column: "RoleId"); 181 | 182 | migrationBuilder.CreateIndex( 183 | name: "EmailIndex", 184 | table: "AspNetUsers", 185 | column: "NormalizedEmail"); 186 | 187 | migrationBuilder.CreateIndex( 188 | name: "UserNameIndex", 189 | table: "AspNetUsers", 190 | column: "NormalizedUserName", 191 | unique: true, 192 | filter: "[NormalizedUserName] IS NOT NULL"); 193 | } 194 | 195 | protected override void Down(MigrationBuilder migrationBuilder) 196 | { 197 | migrationBuilder.DropTable( 198 | name: "AspNetRoleClaims"); 199 | 200 | migrationBuilder.DropTable( 201 | name: "AspNetUserClaims"); 202 | 203 | migrationBuilder.DropTable( 204 | name: "AspNetUserLogins"); 205 | 206 | migrationBuilder.DropTable( 207 | name: "AspNetUserRoles"); 208 | 209 | migrationBuilder.DropTable( 210 | name: "AspNetUserTokens"); 211 | 212 | migrationBuilder.DropTable( 213 | name: "AspNetRoles"); 214 | 215 | migrationBuilder.DropTable( 216 | name: "AspNetUsers"); 217 | } 218 | } 219 | } 220 | -------------------------------------------------------------------------------- /IdentityConfigurations/IdentityConfigurationSample/Migrations/ApplicationDbContextModelSnapshot.cs: -------------------------------------------------------------------------------- 1 | // 2 | using System; 3 | using IdentityConfigurationSample.Data; 4 | using Microsoft.EntityFrameworkCore; 5 | using Microsoft.EntityFrameworkCore.Infrastructure; 6 | using Microsoft.EntityFrameworkCore.Metadata; 7 | using Microsoft.EntityFrameworkCore.Storage.ValueConversion; 8 | 9 | namespace CookieAuthSampleAPI.Migrations 10 | { 11 | [DbContext(typeof(ApplicationDbContext))] 12 | partial class ApplicationDbContextModelSnapshot : ModelSnapshot 13 | { 14 | protected override void BuildModel(ModelBuilder modelBuilder) 15 | { 16 | #pragma warning disable 612, 618 17 | modelBuilder 18 | .HasAnnotation("ProductVersion", "3.1.1") 19 | .HasAnnotation("Relational:MaxIdentifierLength", 128) 20 | .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); 21 | 22 | modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRole", b => 23 | { 24 | b.Property("Id") 25 | .HasColumnType("nvarchar(450)"); 26 | 27 | b.Property("ConcurrencyStamp") 28 | .IsConcurrencyToken() 29 | .HasColumnType("nvarchar(max)"); 30 | 31 | b.Property("Name") 32 | .HasColumnType("nvarchar(256)") 33 | .HasMaxLength(256); 34 | 35 | b.Property("NormalizedName") 36 | .HasColumnType("nvarchar(256)") 37 | .HasMaxLength(256); 38 | 39 | b.HasKey("Id"); 40 | 41 | b.HasIndex("NormalizedName") 42 | .IsUnique() 43 | .HasName("RoleNameIndex") 44 | .HasFilter("[NormalizedName] IS NOT NULL"); 45 | 46 | b.ToTable("AspNetRoles"); 47 | }); 48 | 49 | modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => 50 | { 51 | b.Property("Id") 52 | .ValueGeneratedOnAdd() 53 | .HasColumnType("int") 54 | .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); 55 | 56 | b.Property("ClaimType") 57 | .HasColumnType("nvarchar(max)"); 58 | 59 | b.Property("ClaimValue") 60 | .HasColumnType("nvarchar(max)"); 61 | 62 | b.Property("RoleId") 63 | .IsRequired() 64 | .HasColumnType("nvarchar(450)"); 65 | 66 | b.HasKey("Id"); 67 | 68 | b.HasIndex("RoleId"); 69 | 70 | b.ToTable("AspNetRoleClaims"); 71 | }); 72 | 73 | modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUser", b => 74 | { 75 | b.Property("Id") 76 | .HasColumnType("nvarchar(450)"); 77 | 78 | b.Property("AccessFailedCount") 79 | .HasColumnType("int"); 80 | 81 | b.Property("ConcurrencyStamp") 82 | .IsConcurrencyToken() 83 | .HasColumnType("nvarchar(max)"); 84 | 85 | b.Property("Email") 86 | .HasColumnType("nvarchar(256)") 87 | .HasMaxLength(256); 88 | 89 | b.Property("EmailConfirmed") 90 | .HasColumnType("bit"); 91 | 92 | b.Property("LockoutEnabled") 93 | .HasColumnType("bit"); 94 | 95 | b.Property("LockoutEnd") 96 | .HasColumnType("datetimeoffset"); 97 | 98 | b.Property("NormalizedEmail") 99 | .HasColumnType("nvarchar(256)") 100 | .HasMaxLength(256); 101 | 102 | b.Property("NormalizedUserName") 103 | .HasColumnType("nvarchar(256)") 104 | .HasMaxLength(256); 105 | 106 | b.Property("PasswordHash") 107 | .HasColumnType("nvarchar(max)"); 108 | 109 | b.Property("PhoneNumber") 110 | .HasColumnType("nvarchar(max)"); 111 | 112 | b.Property("PhoneNumberConfirmed") 113 | .HasColumnType("bit"); 114 | 115 | b.Property("SecurityStamp") 116 | .HasColumnType("nvarchar(max)"); 117 | 118 | b.Property("TwoFactorEnabled") 119 | .HasColumnType("bit"); 120 | 121 | b.Property("UserName") 122 | .HasColumnType("nvarchar(256)") 123 | .HasMaxLength(256); 124 | 125 | b.HasKey("Id"); 126 | 127 | b.HasIndex("NormalizedEmail") 128 | .HasName("EmailIndex"); 129 | 130 | b.HasIndex("NormalizedUserName") 131 | .IsUnique() 132 | .HasName("UserNameIndex") 133 | .HasFilter("[NormalizedUserName] IS NOT NULL"); 134 | 135 | b.ToTable("AspNetUsers"); 136 | }); 137 | 138 | modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => 139 | { 140 | b.Property("Id") 141 | .ValueGeneratedOnAdd() 142 | .HasColumnType("int") 143 | .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); 144 | 145 | b.Property("ClaimType") 146 | .HasColumnType("nvarchar(max)"); 147 | 148 | b.Property("ClaimValue") 149 | .HasColumnType("nvarchar(max)"); 150 | 151 | b.Property("UserId") 152 | .IsRequired() 153 | .HasColumnType("nvarchar(450)"); 154 | 155 | b.HasKey("Id"); 156 | 157 | b.HasIndex("UserId"); 158 | 159 | b.ToTable("AspNetUserClaims"); 160 | }); 161 | 162 | modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => 163 | { 164 | b.Property("LoginProvider") 165 | .HasColumnType("nvarchar(450)"); 166 | 167 | b.Property("ProviderKey") 168 | .HasColumnType("nvarchar(450)"); 169 | 170 | b.Property("ProviderDisplayName") 171 | .HasColumnType("nvarchar(max)"); 172 | 173 | b.Property("UserId") 174 | .IsRequired() 175 | .HasColumnType("nvarchar(450)"); 176 | 177 | b.HasKey("LoginProvider", "ProviderKey"); 178 | 179 | b.HasIndex("UserId"); 180 | 181 | b.ToTable("AspNetUserLogins"); 182 | }); 183 | 184 | modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => 185 | { 186 | b.Property("UserId") 187 | .HasColumnType("nvarchar(450)"); 188 | 189 | b.Property("RoleId") 190 | .HasColumnType("nvarchar(450)"); 191 | 192 | b.HasKey("UserId", "RoleId"); 193 | 194 | b.HasIndex("RoleId"); 195 | 196 | b.ToTable("AspNetUserRoles"); 197 | }); 198 | 199 | modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => 200 | { 201 | b.Property("UserId") 202 | .HasColumnType("nvarchar(450)"); 203 | 204 | b.Property("LoginProvider") 205 | .HasColumnType("nvarchar(450)"); 206 | 207 | b.Property("Name") 208 | .HasColumnType("nvarchar(450)"); 209 | 210 | b.Property("Value") 211 | .HasColumnType("nvarchar(max)"); 212 | 213 | b.HasKey("UserId", "LoginProvider", "Name"); 214 | 215 | b.ToTable("AspNetUserTokens"); 216 | }); 217 | 218 | modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => 219 | { 220 | b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) 221 | .WithMany() 222 | .HasForeignKey("RoleId") 223 | .OnDelete(DeleteBehavior.Cascade) 224 | .IsRequired(); 225 | }); 226 | 227 | modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => 228 | { 229 | b.HasOne("Microsoft.AspNetCore.Identity.IdentityUser", null) 230 | .WithMany() 231 | .HasForeignKey("UserId") 232 | .OnDelete(DeleteBehavior.Cascade) 233 | .IsRequired(); 234 | }); 235 | 236 | modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => 237 | { 238 | b.HasOne("Microsoft.AspNetCore.Identity.IdentityUser", null) 239 | .WithMany() 240 | .HasForeignKey("UserId") 241 | .OnDelete(DeleteBehavior.Cascade) 242 | .IsRequired(); 243 | }); 244 | 245 | modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => 246 | { 247 | b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) 248 | .WithMany() 249 | .HasForeignKey("RoleId") 250 | .OnDelete(DeleteBehavior.Cascade) 251 | .IsRequired(); 252 | 253 | b.HasOne("Microsoft.AspNetCore.Identity.IdentityUser", null) 254 | .WithMany() 255 | .HasForeignKey("UserId") 256 | .OnDelete(DeleteBehavior.Cascade) 257 | .IsRequired(); 258 | }); 259 | 260 | modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => 261 | { 262 | b.HasOne("Microsoft.AspNetCore.Identity.IdentityUser", null) 263 | .WithMany() 264 | .HasForeignKey("UserId") 265 | .OnDelete(DeleteBehavior.Cascade) 266 | .IsRequired(); 267 | }); 268 | #pragma warning restore 612, 618 269 | } 270 | } 271 | } 272 | -------------------------------------------------------------------------------- /IdentityConfigurations/IdentityConfigurationSample/Models/WeatherForecast.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace IdentityConfigurationSample.Models 4 | { 5 | public class WeatherForecast 6 | { 7 | public DateTime Date { get; set; } 8 | 9 | public int TemperatureC { get; set; } 10 | 11 | public int TemperatureF => 32 + (int)(TemperatureC / 0.5556); 12 | 13 | public string Summary { get; set; } 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /IdentityConfigurations/IdentityConfigurationSample/Program.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Hosting; 2 | using Microsoft.Extensions.Hosting; 3 | 4 | namespace IdentityConfigurationSample 5 | { 6 | public class Program 7 | { 8 | public static void Main(string[] args) 9 | { 10 | CreateHostBuilder(args).Build().Run(); 11 | } 12 | 13 | public static IHostBuilder CreateHostBuilder(string[] args) => 14 | Host.CreateDefaultBuilder(args) 15 | .ConfigureWebHostDefaults(webBuilder => 16 | { 17 | webBuilder.UseStartup(); 18 | }); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /IdentityConfigurations/IdentityConfigurationSample/Properties/launchSettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "http://json.schemastore.org/launchsettings.json", 3 | "iisSettings": { 4 | "windowsAuthentication": false, 5 | "anonymousAuthentication": true, 6 | "iisExpress": { 7 | "applicationUrl": "http://localhost:61610", 8 | "sslPort": 44322 9 | } 10 | }, 11 | "profiles": { 12 | "IIS Express": { 13 | "commandName": "IISExpress", 14 | "launchBrowser": true, 15 | "launchUrl": "weatherforecast", 16 | "environmentVariables": { 17 | "ASPNETCORE_ENVIRONMENT": "Development" 18 | } 19 | }, 20 | "CookieAuthSampleAPI": { 21 | "commandName": "Project", 22 | "launchBrowser": true, 23 | "launchUrl": "weatherforecast", 24 | "applicationUrl": "https://localhost:5001;http://localhost:5000", 25 | "environmentVariables": { 26 | "ASPNETCORE_ENVIRONMENT": "Development" 27 | } 28 | } 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /IdentityConfigurations/IdentityConfigurationSample/Startup.cs: -------------------------------------------------------------------------------- 1 | using IdentityConfigurationSample.Data; 2 | using Microsoft.AspNetCore.Builder; 3 | using Microsoft.AspNetCore.Hosting; 4 | using Microsoft.AspNetCore.Identity; 5 | using Microsoft.EntityFrameworkCore; 6 | using Microsoft.Extensions.Configuration; 7 | using Microsoft.Extensions.DependencyInjection; 8 | using Microsoft.Extensions.Hosting; 9 | 10 | namespace IdentityConfigurationSample 11 | { 12 | public class Startup 13 | { 14 | public Startup(IConfiguration configuration) 15 | { 16 | Configuration = configuration; 17 | } 18 | 19 | public IConfiguration Configuration { get; } 20 | 21 | // This method gets called by the runtime. Use this method to add services to the container. 22 | public void ConfigureServices(IServiceCollection services) 23 | { 24 | services.AddDbContext(options => options.UseSqlServer(Configuration.GetConnectionString("SqlConnection"))); 25 | 26 | services.AddIdentity(options => options.SignIn.RequireConfirmedAccount = true) 27 | .AddEntityFrameworkStores(); 28 | 29 | services.AddControllers(); 30 | } 31 | 32 | // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. 33 | public void Configure(IApplicationBuilder app, IWebHostEnvironment env) 34 | { 35 | if (env.IsDevelopment()) 36 | { 37 | app.UseDeveloperExceptionPage(); 38 | } 39 | 40 | app.UseHttpsRedirection(); 41 | 42 | app.UseRouting(); 43 | 44 | app.UseAuthorization(); 45 | 46 | app.UseEndpoints(endpoints => 47 | { 48 | endpoints.MapControllers(); 49 | }); 50 | } 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /IdentityConfigurations/IdentityConfigurationSample/appsettings.Development.json: -------------------------------------------------------------------------------- 1 | { 2 | "Logging": { 3 | "LogLevel": { 4 | "Default": "Information", 5 | "Microsoft": "Warning", 6 | "Microsoft.Hosting.Lifetime": "Information" 7 | } 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /IdentityConfigurations/IdentityConfigurationSample/appsettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "Logging": { 3 | "LogLevel": { 4 | "Default": "Information", 5 | "Microsoft": "Warning", 6 | "Microsoft.Hosting.Lifetime": "Information" 7 | } 8 | }, 9 | 10 | "ConnectionStrings": { 11 | "SqlConnection": "Server=(localdb)\\MSSQLLocalDB;Initial Catalog=MyAppDb; Integrated Security=true;" 12 | }, 13 | 14 | "AllowedHosts": "*" 15 | } 16 | -------------------------------------------------------------------------------- /JwtAuthSample/JwtAuthSampleAPI.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio Version 16 4 | VisualStudioVersion = 16.0.29613.14 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Postman-Collection", "Postman-Collection", "{288B75D6-78DF-4F8A-821B-FE250A445997}" 7 | ProjectSection(SolutionItems) = preProject 8 | Postman-Collection\JwtAuthSample.postman_collection.json = Postman-Collection\JwtAuthSample.postman_collection.json 9 | EndProjectSection 10 | EndProject 11 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "JwtAuthSampleAPI", "JwtAuthSampleAPI\JwtAuthSampleAPI.csproj", "{57E8F9AB-42FF-448B-8673-3888EC00934D}" 12 | EndProject 13 | Global 14 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 15 | Debug|Any CPU = Debug|Any CPU 16 | Release|Any CPU = Release|Any CPU 17 | EndGlobalSection 18 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 19 | {57E8F9AB-42FF-448B-8673-3888EC00934D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 20 | {57E8F9AB-42FF-448B-8673-3888EC00934D}.Debug|Any CPU.Build.0 = Debug|Any CPU 21 | {57E8F9AB-42FF-448B-8673-3888EC00934D}.Release|Any CPU.ActiveCfg = Release|Any CPU 22 | {57E8F9AB-42FF-448B-8673-3888EC00934D}.Release|Any CPU.Build.0 = Release|Any CPU 23 | EndGlobalSection 24 | GlobalSection(SolutionProperties) = preSolution 25 | HideSolutionNode = FALSE 26 | EndGlobalSection 27 | GlobalSection(ExtensibilityGlobals) = postSolution 28 | SolutionGuid = {D3545E52-87EF-46B9-A4C5-7BABF1053564} 29 | EndGlobalSection 30 | EndGlobal 31 | -------------------------------------------------------------------------------- /JwtAuthSample/JwtAuthSampleAPI/Configuration/JwtBearerTokenSettings.cs: -------------------------------------------------------------------------------- 1 | namespace JwtAuthSampleAPI.Configuration 2 | { 3 | public class JwtBearerTokenSettings 4 | { 5 | public string SecretKey { get; set; } 6 | public string Audience { get; set; } 7 | public string Issuer { get; set; } 8 | public int ExpiryTimeInSeconds { get; set; } 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /JwtAuthSample/JwtAuthSampleAPI/Controllers/AuthController.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.IdentityModel.Tokens.Jwt; 3 | using System.Security.Claims; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | using JwtAuthSampleAPI.Configuration; 7 | using JwtAuthSampleAPI.Models; 8 | using Microsoft.AspNetCore.Identity; 9 | using Microsoft.AspNetCore.Mvc; 10 | using Microsoft.AspNetCore.Mvc.ModelBinding; 11 | using Microsoft.Extensions.Options; 12 | using Microsoft.IdentityModel.Tokens; 13 | 14 | namespace JwtAuthSampleAPI.Controllers 15 | { 16 | [Route("api/[controller]")] 17 | [ApiController] 18 | public class AuthController : ControllerBase 19 | { 20 | private readonly JwtBearerTokenSettings jwtBearerTokenSettings; 21 | private readonly UserManager userManager; 22 | 23 | public AuthController(IOptions jwtTokenOptions, UserManager userManager) 24 | { 25 | this.jwtBearerTokenSettings = jwtTokenOptions.Value; 26 | this.userManager = userManager; 27 | } 28 | 29 | [HttpPost] 30 | [Route("Register")] 31 | public async Task Register([FromBody]UserDetails userDetails) 32 | { 33 | if (!ModelState.IsValid || userDetails == null) 34 | { 35 | return new BadRequestObjectResult(new { Message = "User Registration Failed" }); 36 | } 37 | 38 | var identityUser = new IdentityUser() { UserName = userDetails.UserName, Email = userDetails.Email }; 39 | var result = await userManager.CreateAsync(identityUser, userDetails.Password); 40 | if (!result.Succeeded) 41 | { 42 | var dictionary = new ModelStateDictionary(); 43 | foreach (IdentityError error in result.Errors) 44 | { 45 | dictionary.AddModelError(error.Code, error.Description); 46 | } 47 | 48 | return new BadRequestObjectResult(new { Message = "User Registration Failed", Errors = dictionary }); 49 | } 50 | 51 | return Ok(new { Message = "User Reigstration Successful" }); 52 | } 53 | 54 | [HttpPost] 55 | [Route("Login")] 56 | public async Task Login([FromBody]LoginCredentials credentials) 57 | { 58 | IdentityUser identityUser; 59 | 60 | if (!ModelState.IsValid 61 | || credentials == null 62 | || (identityUser = await ValidateUser(credentials)) == null) 63 | { 64 | return new BadRequestObjectResult(new { Message = "Login failed" }); 65 | } 66 | 67 | var token = GenerateToken(identityUser); 68 | return Ok(new { Token = token, Message = "Success" }); 69 | } 70 | 71 | [HttpPost] 72 | [Route("Logout")] 73 | public async Task Logout() 74 | { 75 | // Well, What do you want to do here ? 76 | // Wait for token to get expired OR 77 | // Maintain token cache and invalidate the tokens after logout method is called 78 | return Ok(new { Token = "", Message = "Logged Out" }); 79 | } 80 | 81 | private async Task ValidateUser(LoginCredentials credentials) 82 | { 83 | var identityUser = await userManager.FindByNameAsync(credentials.Username); 84 | if (identityUser != null) 85 | { 86 | var result = userManager.PasswordHasher.VerifyHashedPassword(identityUser, identityUser.PasswordHash, credentials.Password); 87 | return result == PasswordVerificationResult.Failed ? null : identityUser; 88 | } 89 | 90 | return null; 91 | } 92 | 93 | 94 | private object GenerateToken(IdentityUser identityUser) 95 | { 96 | var tokenHandler = new JwtSecurityTokenHandler(); 97 | var key = Encoding.ASCII.GetBytes(jwtBearerTokenSettings.SecretKey); 98 | 99 | var tokenDescriptor = new SecurityTokenDescriptor 100 | { 101 | Subject = new ClaimsIdentity(new Claim[] 102 | { 103 | new Claim(ClaimTypes.Name, identityUser.UserName.ToString()), 104 | new Claim(ClaimTypes.Email, identityUser.Email) 105 | }), 106 | 107 | Expires = DateTime.UtcNow.AddSeconds(jwtBearerTokenSettings.ExpiryTimeInSeconds), 108 | SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature), 109 | Audience = jwtBearerTokenSettings.Audience, 110 | Issuer = jwtBearerTokenSettings.Issuer 111 | }; 112 | 113 | var token = tokenHandler.CreateToken(tokenDescriptor); 114 | return tokenHandler.WriteToken(token); 115 | } 116 | } 117 | } -------------------------------------------------------------------------------- /JwtAuthSample/JwtAuthSampleAPI/Controllers/WeatherForecastController.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using JwtAuthSampleAPI.Models; 5 | using Microsoft.AspNetCore.Authorization; 6 | using Microsoft.AspNetCore.Mvc; 7 | using Microsoft.Extensions.Logging; 8 | 9 | namespace JwtAuthSampleAPI.Controllers 10 | { 11 | [Authorize] 12 | [ApiController] 13 | [Route("api/[controller]")] 14 | public class WeatherForecastController : ControllerBase 15 | { 16 | private static readonly string[] Summaries = new[] 17 | { 18 | "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching" 19 | }; 20 | 21 | private readonly ILogger _logger; 22 | 23 | public WeatherForecastController(ILogger logger) 24 | { 25 | _logger = logger; 26 | } 27 | 28 | [HttpGet] 29 | [Route("")] 30 | public IEnumerable Get() 31 | { 32 | var rng = new Random(); 33 | return Enumerable.Range(1, 5).Select(index => new WeatherForecast 34 | { 35 | Date = DateTime.Now.AddDays(index), 36 | TemperatureC = rng.Next(-20, 55), 37 | Summary = Summaries[rng.Next(Summaries.Length)] 38 | }) 39 | .ToArray(); 40 | } 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /JwtAuthSample/JwtAuthSampleAPI/Data/ApplicationDbContext.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Identity; 2 | using Microsoft.AspNetCore.Identity.EntityFrameworkCore; 3 | using Microsoft.EntityFrameworkCore; 4 | 5 | namespace JwtAuthSampleAPI.Data 6 | { 7 | public class ApplicationDbContext : IdentityDbContext 8 | { 9 | public ApplicationDbContext(DbContextOptions options) : base(options) 10 | { 11 | 12 | } 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /JwtAuthSample/JwtAuthSampleAPI/JwtAuthSampleAPI.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | netcoreapp3.1 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | all 13 | runtime; build; native; contentfiles; analyzers; buildtransitive 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | -------------------------------------------------------------------------------- /JwtAuthSample/JwtAuthSampleAPI/Migrations/20200123192549_First.Designer.cs: -------------------------------------------------------------------------------- 1 | // 2 | using System; 3 | using JwtAuthSampleAPI.Data; 4 | using Microsoft.EntityFrameworkCore; 5 | using Microsoft.EntityFrameworkCore.Infrastructure; 6 | using Microsoft.EntityFrameworkCore.Metadata; 7 | using Microsoft.EntityFrameworkCore.Migrations; 8 | using Microsoft.EntityFrameworkCore.Storage.ValueConversion; 9 | 10 | namespace JwtAuthSampleAPI.Migrations 11 | { 12 | [DbContext(typeof(ApplicationDbContext))] 13 | [Migration("20200123192549_First")] 14 | partial class First 15 | { 16 | protected override void BuildTargetModel(ModelBuilder modelBuilder) 17 | { 18 | #pragma warning disable 612, 618 19 | modelBuilder 20 | .HasAnnotation("ProductVersion", "3.1.1") 21 | .HasAnnotation("Relational:MaxIdentifierLength", 128) 22 | .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); 23 | 24 | modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRole", b => 25 | { 26 | b.Property("Id") 27 | .HasColumnType("nvarchar(450)"); 28 | 29 | b.Property("ConcurrencyStamp") 30 | .IsConcurrencyToken() 31 | .HasColumnType("nvarchar(max)"); 32 | 33 | b.Property("Name") 34 | .HasColumnType("nvarchar(256)") 35 | .HasMaxLength(256); 36 | 37 | b.Property("NormalizedName") 38 | .HasColumnType("nvarchar(256)") 39 | .HasMaxLength(256); 40 | 41 | b.HasKey("Id"); 42 | 43 | b.HasIndex("NormalizedName") 44 | .IsUnique() 45 | .HasName("RoleNameIndex") 46 | .HasFilter("[NormalizedName] IS NOT NULL"); 47 | 48 | b.ToTable("AspNetRoles"); 49 | }); 50 | 51 | modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => 52 | { 53 | b.Property("Id") 54 | .ValueGeneratedOnAdd() 55 | .HasColumnType("int") 56 | .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); 57 | 58 | b.Property("ClaimType") 59 | .HasColumnType("nvarchar(max)"); 60 | 61 | b.Property("ClaimValue") 62 | .HasColumnType("nvarchar(max)"); 63 | 64 | b.Property("RoleId") 65 | .IsRequired() 66 | .HasColumnType("nvarchar(450)"); 67 | 68 | b.HasKey("Id"); 69 | 70 | b.HasIndex("RoleId"); 71 | 72 | b.ToTable("AspNetRoleClaims"); 73 | }); 74 | 75 | modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUser", b => 76 | { 77 | b.Property("Id") 78 | .HasColumnType("nvarchar(450)"); 79 | 80 | b.Property("AccessFailedCount") 81 | .HasColumnType("int"); 82 | 83 | b.Property("ConcurrencyStamp") 84 | .IsConcurrencyToken() 85 | .HasColumnType("nvarchar(max)"); 86 | 87 | b.Property("Email") 88 | .HasColumnType("nvarchar(256)") 89 | .HasMaxLength(256); 90 | 91 | b.Property("EmailConfirmed") 92 | .HasColumnType("bit"); 93 | 94 | b.Property("LockoutEnabled") 95 | .HasColumnType("bit"); 96 | 97 | b.Property("LockoutEnd") 98 | .HasColumnType("datetimeoffset"); 99 | 100 | b.Property("NormalizedEmail") 101 | .HasColumnType("nvarchar(256)") 102 | .HasMaxLength(256); 103 | 104 | b.Property("NormalizedUserName") 105 | .HasColumnType("nvarchar(256)") 106 | .HasMaxLength(256); 107 | 108 | b.Property("PasswordHash") 109 | .HasColumnType("nvarchar(max)"); 110 | 111 | b.Property("PhoneNumber") 112 | .HasColumnType("nvarchar(max)"); 113 | 114 | b.Property("PhoneNumberConfirmed") 115 | .HasColumnType("bit"); 116 | 117 | b.Property("SecurityStamp") 118 | .HasColumnType("nvarchar(max)"); 119 | 120 | b.Property("TwoFactorEnabled") 121 | .HasColumnType("bit"); 122 | 123 | b.Property("UserName") 124 | .HasColumnType("nvarchar(256)") 125 | .HasMaxLength(256); 126 | 127 | b.HasKey("Id"); 128 | 129 | b.HasIndex("NormalizedEmail") 130 | .HasName("EmailIndex"); 131 | 132 | b.HasIndex("NormalizedUserName") 133 | .IsUnique() 134 | .HasName("UserNameIndex") 135 | .HasFilter("[NormalizedUserName] IS NOT NULL"); 136 | 137 | b.ToTable("AspNetUsers"); 138 | }); 139 | 140 | modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => 141 | { 142 | b.Property("Id") 143 | .ValueGeneratedOnAdd() 144 | .HasColumnType("int") 145 | .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); 146 | 147 | b.Property("ClaimType") 148 | .HasColumnType("nvarchar(max)"); 149 | 150 | b.Property("ClaimValue") 151 | .HasColumnType("nvarchar(max)"); 152 | 153 | b.Property("UserId") 154 | .IsRequired() 155 | .HasColumnType("nvarchar(450)"); 156 | 157 | b.HasKey("Id"); 158 | 159 | b.HasIndex("UserId"); 160 | 161 | b.ToTable("AspNetUserClaims"); 162 | }); 163 | 164 | modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => 165 | { 166 | b.Property("LoginProvider") 167 | .HasColumnType("nvarchar(450)"); 168 | 169 | b.Property("ProviderKey") 170 | .HasColumnType("nvarchar(450)"); 171 | 172 | b.Property("ProviderDisplayName") 173 | .HasColumnType("nvarchar(max)"); 174 | 175 | b.Property("UserId") 176 | .IsRequired() 177 | .HasColumnType("nvarchar(450)"); 178 | 179 | b.HasKey("LoginProvider", "ProviderKey"); 180 | 181 | b.HasIndex("UserId"); 182 | 183 | b.ToTable("AspNetUserLogins"); 184 | }); 185 | 186 | modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => 187 | { 188 | b.Property("UserId") 189 | .HasColumnType("nvarchar(450)"); 190 | 191 | b.Property("RoleId") 192 | .HasColumnType("nvarchar(450)"); 193 | 194 | b.HasKey("UserId", "RoleId"); 195 | 196 | b.HasIndex("RoleId"); 197 | 198 | b.ToTable("AspNetUserRoles"); 199 | }); 200 | 201 | modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => 202 | { 203 | b.Property("UserId") 204 | .HasColumnType("nvarchar(450)"); 205 | 206 | b.Property("LoginProvider") 207 | .HasColumnType("nvarchar(450)"); 208 | 209 | b.Property("Name") 210 | .HasColumnType("nvarchar(450)"); 211 | 212 | b.Property("Value") 213 | .HasColumnType("nvarchar(max)"); 214 | 215 | b.HasKey("UserId", "LoginProvider", "Name"); 216 | 217 | b.ToTable("AspNetUserTokens"); 218 | }); 219 | 220 | modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => 221 | { 222 | b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) 223 | .WithMany() 224 | .HasForeignKey("RoleId") 225 | .OnDelete(DeleteBehavior.Cascade) 226 | .IsRequired(); 227 | }); 228 | 229 | modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => 230 | { 231 | b.HasOne("Microsoft.AspNetCore.Identity.IdentityUser", null) 232 | .WithMany() 233 | .HasForeignKey("UserId") 234 | .OnDelete(DeleteBehavior.Cascade) 235 | .IsRequired(); 236 | }); 237 | 238 | modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => 239 | { 240 | b.HasOne("Microsoft.AspNetCore.Identity.IdentityUser", null) 241 | .WithMany() 242 | .HasForeignKey("UserId") 243 | .OnDelete(DeleteBehavior.Cascade) 244 | .IsRequired(); 245 | }); 246 | 247 | modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => 248 | { 249 | b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) 250 | .WithMany() 251 | .HasForeignKey("RoleId") 252 | .OnDelete(DeleteBehavior.Cascade) 253 | .IsRequired(); 254 | 255 | b.HasOne("Microsoft.AspNetCore.Identity.IdentityUser", null) 256 | .WithMany() 257 | .HasForeignKey("UserId") 258 | .OnDelete(DeleteBehavior.Cascade) 259 | .IsRequired(); 260 | }); 261 | 262 | modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => 263 | { 264 | b.HasOne("Microsoft.AspNetCore.Identity.IdentityUser", null) 265 | .WithMany() 266 | .HasForeignKey("UserId") 267 | .OnDelete(DeleteBehavior.Cascade) 268 | .IsRequired(); 269 | }); 270 | #pragma warning restore 612, 618 271 | } 272 | } 273 | } 274 | -------------------------------------------------------------------------------- /JwtAuthSample/JwtAuthSampleAPI/Migrations/20200123192549_First.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using Microsoft.EntityFrameworkCore.Migrations; 3 | 4 | namespace JwtAuthSampleAPI.Migrations 5 | { 6 | public partial class First : Migration 7 | { 8 | protected override void Up(MigrationBuilder migrationBuilder) 9 | { 10 | migrationBuilder.CreateTable( 11 | name: "AspNetRoles", 12 | columns: table => new 13 | { 14 | Id = table.Column(nullable: false), 15 | Name = table.Column(maxLength: 256, nullable: true), 16 | NormalizedName = table.Column(maxLength: 256, nullable: true), 17 | ConcurrencyStamp = table.Column(nullable: true) 18 | }, 19 | constraints: table => 20 | { 21 | table.PrimaryKey("PK_AspNetRoles", x => x.Id); 22 | }); 23 | 24 | migrationBuilder.CreateTable( 25 | name: "AspNetUsers", 26 | columns: table => new 27 | { 28 | Id = table.Column(nullable: false), 29 | UserName = table.Column(maxLength: 256, nullable: true), 30 | NormalizedUserName = table.Column(maxLength: 256, nullable: true), 31 | Email = table.Column(maxLength: 256, nullable: true), 32 | NormalizedEmail = table.Column(maxLength: 256, nullable: true), 33 | EmailConfirmed = table.Column(nullable: false), 34 | PasswordHash = table.Column(nullable: true), 35 | SecurityStamp = table.Column(nullable: true), 36 | ConcurrencyStamp = table.Column(nullable: true), 37 | PhoneNumber = table.Column(nullable: true), 38 | PhoneNumberConfirmed = table.Column(nullable: false), 39 | TwoFactorEnabled = table.Column(nullable: false), 40 | LockoutEnd = table.Column(nullable: true), 41 | LockoutEnabled = table.Column(nullable: false), 42 | AccessFailedCount = table.Column(nullable: false) 43 | }, 44 | constraints: table => 45 | { 46 | table.PrimaryKey("PK_AspNetUsers", x => x.Id); 47 | }); 48 | 49 | migrationBuilder.CreateTable( 50 | name: "AspNetRoleClaims", 51 | columns: table => new 52 | { 53 | Id = table.Column(nullable: false) 54 | .Annotation("SqlServer:Identity", "1, 1"), 55 | RoleId = table.Column(nullable: false), 56 | ClaimType = table.Column(nullable: true), 57 | ClaimValue = table.Column(nullable: true) 58 | }, 59 | constraints: table => 60 | { 61 | table.PrimaryKey("PK_AspNetRoleClaims", x => x.Id); 62 | table.ForeignKey( 63 | name: "FK_AspNetRoleClaims_AspNetRoles_RoleId", 64 | column: x => x.RoleId, 65 | principalTable: "AspNetRoles", 66 | principalColumn: "Id", 67 | onDelete: ReferentialAction.Cascade); 68 | }); 69 | 70 | migrationBuilder.CreateTable( 71 | name: "AspNetUserClaims", 72 | columns: table => new 73 | { 74 | Id = table.Column(nullable: false) 75 | .Annotation("SqlServer:Identity", "1, 1"), 76 | UserId = table.Column(nullable: false), 77 | ClaimType = table.Column(nullable: true), 78 | ClaimValue = table.Column(nullable: true) 79 | }, 80 | constraints: table => 81 | { 82 | table.PrimaryKey("PK_AspNetUserClaims", x => x.Id); 83 | table.ForeignKey( 84 | name: "FK_AspNetUserClaims_AspNetUsers_UserId", 85 | column: x => x.UserId, 86 | principalTable: "AspNetUsers", 87 | principalColumn: "Id", 88 | onDelete: ReferentialAction.Cascade); 89 | }); 90 | 91 | migrationBuilder.CreateTable( 92 | name: "AspNetUserLogins", 93 | columns: table => new 94 | { 95 | LoginProvider = table.Column(nullable: false), 96 | ProviderKey = table.Column(nullable: false), 97 | ProviderDisplayName = table.Column(nullable: true), 98 | UserId = table.Column(nullable: false) 99 | }, 100 | constraints: table => 101 | { 102 | table.PrimaryKey("PK_AspNetUserLogins", x => new { x.LoginProvider, x.ProviderKey }); 103 | table.ForeignKey( 104 | name: "FK_AspNetUserLogins_AspNetUsers_UserId", 105 | column: x => x.UserId, 106 | principalTable: "AspNetUsers", 107 | principalColumn: "Id", 108 | onDelete: ReferentialAction.Cascade); 109 | }); 110 | 111 | migrationBuilder.CreateTable( 112 | name: "AspNetUserRoles", 113 | columns: table => new 114 | { 115 | UserId = table.Column(nullable: false), 116 | RoleId = table.Column(nullable: false) 117 | }, 118 | constraints: table => 119 | { 120 | table.PrimaryKey("PK_AspNetUserRoles", x => new { x.UserId, x.RoleId }); 121 | table.ForeignKey( 122 | name: "FK_AspNetUserRoles_AspNetRoles_RoleId", 123 | column: x => x.RoleId, 124 | principalTable: "AspNetRoles", 125 | principalColumn: "Id", 126 | onDelete: ReferentialAction.Cascade); 127 | table.ForeignKey( 128 | name: "FK_AspNetUserRoles_AspNetUsers_UserId", 129 | column: x => x.UserId, 130 | principalTable: "AspNetUsers", 131 | principalColumn: "Id", 132 | onDelete: ReferentialAction.Cascade); 133 | }); 134 | 135 | migrationBuilder.CreateTable( 136 | name: "AspNetUserTokens", 137 | columns: table => new 138 | { 139 | UserId = table.Column(nullable: false), 140 | LoginProvider = table.Column(nullable: false), 141 | Name = table.Column(nullable: false), 142 | Value = table.Column(nullable: true) 143 | }, 144 | constraints: table => 145 | { 146 | table.PrimaryKey("PK_AspNetUserTokens", x => new { x.UserId, x.LoginProvider, x.Name }); 147 | table.ForeignKey( 148 | name: "FK_AspNetUserTokens_AspNetUsers_UserId", 149 | column: x => x.UserId, 150 | principalTable: "AspNetUsers", 151 | principalColumn: "Id", 152 | onDelete: ReferentialAction.Cascade); 153 | }); 154 | 155 | migrationBuilder.CreateIndex( 156 | name: "IX_AspNetRoleClaims_RoleId", 157 | table: "AspNetRoleClaims", 158 | column: "RoleId"); 159 | 160 | migrationBuilder.CreateIndex( 161 | name: "RoleNameIndex", 162 | table: "AspNetRoles", 163 | column: "NormalizedName", 164 | unique: true, 165 | filter: "[NormalizedName] IS NOT NULL"); 166 | 167 | migrationBuilder.CreateIndex( 168 | name: "IX_AspNetUserClaims_UserId", 169 | table: "AspNetUserClaims", 170 | column: "UserId"); 171 | 172 | migrationBuilder.CreateIndex( 173 | name: "IX_AspNetUserLogins_UserId", 174 | table: "AspNetUserLogins", 175 | column: "UserId"); 176 | 177 | migrationBuilder.CreateIndex( 178 | name: "IX_AspNetUserRoles_RoleId", 179 | table: "AspNetUserRoles", 180 | column: "RoleId"); 181 | 182 | migrationBuilder.CreateIndex( 183 | name: "EmailIndex", 184 | table: "AspNetUsers", 185 | column: "NormalizedEmail"); 186 | 187 | migrationBuilder.CreateIndex( 188 | name: "UserNameIndex", 189 | table: "AspNetUsers", 190 | column: "NormalizedUserName", 191 | unique: true, 192 | filter: "[NormalizedUserName] IS NOT NULL"); 193 | } 194 | 195 | protected override void Down(MigrationBuilder migrationBuilder) 196 | { 197 | migrationBuilder.DropTable( 198 | name: "AspNetRoleClaims"); 199 | 200 | migrationBuilder.DropTable( 201 | name: "AspNetUserClaims"); 202 | 203 | migrationBuilder.DropTable( 204 | name: "AspNetUserLogins"); 205 | 206 | migrationBuilder.DropTable( 207 | name: "AspNetUserRoles"); 208 | 209 | migrationBuilder.DropTable( 210 | name: "AspNetUserTokens"); 211 | 212 | migrationBuilder.DropTable( 213 | name: "AspNetRoles"); 214 | 215 | migrationBuilder.DropTable( 216 | name: "AspNetUsers"); 217 | } 218 | } 219 | } 220 | -------------------------------------------------------------------------------- /JwtAuthSample/JwtAuthSampleAPI/Migrations/ApplicationDbContextModelSnapshot.cs: -------------------------------------------------------------------------------- 1 | // 2 | using System; 3 | using JwtAuthSampleAPI.Data; 4 | using Microsoft.EntityFrameworkCore; 5 | using Microsoft.EntityFrameworkCore.Infrastructure; 6 | using Microsoft.EntityFrameworkCore.Metadata; 7 | using Microsoft.EntityFrameworkCore.Storage.ValueConversion; 8 | 9 | namespace JwtAuthSampleAPI.Migrations 10 | { 11 | [DbContext(typeof(ApplicationDbContext))] 12 | partial class ApplicationDbContextModelSnapshot : ModelSnapshot 13 | { 14 | protected override void BuildModel(ModelBuilder modelBuilder) 15 | { 16 | #pragma warning disable 612, 618 17 | modelBuilder 18 | .HasAnnotation("ProductVersion", "3.1.1") 19 | .HasAnnotation("Relational:MaxIdentifierLength", 128) 20 | .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); 21 | 22 | modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRole", b => 23 | { 24 | b.Property("Id") 25 | .HasColumnType("nvarchar(450)"); 26 | 27 | b.Property("ConcurrencyStamp") 28 | .IsConcurrencyToken() 29 | .HasColumnType("nvarchar(max)"); 30 | 31 | b.Property("Name") 32 | .HasColumnType("nvarchar(256)") 33 | .HasMaxLength(256); 34 | 35 | b.Property("NormalizedName") 36 | .HasColumnType("nvarchar(256)") 37 | .HasMaxLength(256); 38 | 39 | b.HasKey("Id"); 40 | 41 | b.HasIndex("NormalizedName") 42 | .IsUnique() 43 | .HasName("RoleNameIndex") 44 | .HasFilter("[NormalizedName] IS NOT NULL"); 45 | 46 | b.ToTable("AspNetRoles"); 47 | }); 48 | 49 | modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => 50 | { 51 | b.Property("Id") 52 | .ValueGeneratedOnAdd() 53 | .HasColumnType("int") 54 | .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); 55 | 56 | b.Property("ClaimType") 57 | .HasColumnType("nvarchar(max)"); 58 | 59 | b.Property("ClaimValue") 60 | .HasColumnType("nvarchar(max)"); 61 | 62 | b.Property("RoleId") 63 | .IsRequired() 64 | .HasColumnType("nvarchar(450)"); 65 | 66 | b.HasKey("Id"); 67 | 68 | b.HasIndex("RoleId"); 69 | 70 | b.ToTable("AspNetRoleClaims"); 71 | }); 72 | 73 | modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUser", b => 74 | { 75 | b.Property("Id") 76 | .HasColumnType("nvarchar(450)"); 77 | 78 | b.Property("AccessFailedCount") 79 | .HasColumnType("int"); 80 | 81 | b.Property("ConcurrencyStamp") 82 | .IsConcurrencyToken() 83 | .HasColumnType("nvarchar(max)"); 84 | 85 | b.Property("Email") 86 | .HasColumnType("nvarchar(256)") 87 | .HasMaxLength(256); 88 | 89 | b.Property("EmailConfirmed") 90 | .HasColumnType("bit"); 91 | 92 | b.Property("LockoutEnabled") 93 | .HasColumnType("bit"); 94 | 95 | b.Property("LockoutEnd") 96 | .HasColumnType("datetimeoffset"); 97 | 98 | b.Property("NormalizedEmail") 99 | .HasColumnType("nvarchar(256)") 100 | .HasMaxLength(256); 101 | 102 | b.Property("NormalizedUserName") 103 | .HasColumnType("nvarchar(256)") 104 | .HasMaxLength(256); 105 | 106 | b.Property("PasswordHash") 107 | .HasColumnType("nvarchar(max)"); 108 | 109 | b.Property("PhoneNumber") 110 | .HasColumnType("nvarchar(max)"); 111 | 112 | b.Property("PhoneNumberConfirmed") 113 | .HasColumnType("bit"); 114 | 115 | b.Property("SecurityStamp") 116 | .HasColumnType("nvarchar(max)"); 117 | 118 | b.Property("TwoFactorEnabled") 119 | .HasColumnType("bit"); 120 | 121 | b.Property("UserName") 122 | .HasColumnType("nvarchar(256)") 123 | .HasMaxLength(256); 124 | 125 | b.HasKey("Id"); 126 | 127 | b.HasIndex("NormalizedEmail") 128 | .HasName("EmailIndex"); 129 | 130 | b.HasIndex("NormalizedUserName") 131 | .IsUnique() 132 | .HasName("UserNameIndex") 133 | .HasFilter("[NormalizedUserName] IS NOT NULL"); 134 | 135 | b.ToTable("AspNetUsers"); 136 | }); 137 | 138 | modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => 139 | { 140 | b.Property("Id") 141 | .ValueGeneratedOnAdd() 142 | .HasColumnType("int") 143 | .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); 144 | 145 | b.Property("ClaimType") 146 | .HasColumnType("nvarchar(max)"); 147 | 148 | b.Property("ClaimValue") 149 | .HasColumnType("nvarchar(max)"); 150 | 151 | b.Property("UserId") 152 | .IsRequired() 153 | .HasColumnType("nvarchar(450)"); 154 | 155 | b.HasKey("Id"); 156 | 157 | b.HasIndex("UserId"); 158 | 159 | b.ToTable("AspNetUserClaims"); 160 | }); 161 | 162 | modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => 163 | { 164 | b.Property("LoginProvider") 165 | .HasColumnType("nvarchar(450)"); 166 | 167 | b.Property("ProviderKey") 168 | .HasColumnType("nvarchar(450)"); 169 | 170 | b.Property("ProviderDisplayName") 171 | .HasColumnType("nvarchar(max)"); 172 | 173 | b.Property("UserId") 174 | .IsRequired() 175 | .HasColumnType("nvarchar(450)"); 176 | 177 | b.HasKey("LoginProvider", "ProviderKey"); 178 | 179 | b.HasIndex("UserId"); 180 | 181 | b.ToTable("AspNetUserLogins"); 182 | }); 183 | 184 | modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => 185 | { 186 | b.Property("UserId") 187 | .HasColumnType("nvarchar(450)"); 188 | 189 | b.Property("RoleId") 190 | .HasColumnType("nvarchar(450)"); 191 | 192 | b.HasKey("UserId", "RoleId"); 193 | 194 | b.HasIndex("RoleId"); 195 | 196 | b.ToTable("AspNetUserRoles"); 197 | }); 198 | 199 | modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => 200 | { 201 | b.Property("UserId") 202 | .HasColumnType("nvarchar(450)"); 203 | 204 | b.Property("LoginProvider") 205 | .HasColumnType("nvarchar(450)"); 206 | 207 | b.Property("Name") 208 | .HasColumnType("nvarchar(450)"); 209 | 210 | b.Property("Value") 211 | .HasColumnType("nvarchar(max)"); 212 | 213 | b.HasKey("UserId", "LoginProvider", "Name"); 214 | 215 | b.ToTable("AspNetUserTokens"); 216 | }); 217 | 218 | modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => 219 | { 220 | b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) 221 | .WithMany() 222 | .HasForeignKey("RoleId") 223 | .OnDelete(DeleteBehavior.Cascade) 224 | .IsRequired(); 225 | }); 226 | 227 | modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => 228 | { 229 | b.HasOne("Microsoft.AspNetCore.Identity.IdentityUser", null) 230 | .WithMany() 231 | .HasForeignKey("UserId") 232 | .OnDelete(DeleteBehavior.Cascade) 233 | .IsRequired(); 234 | }); 235 | 236 | modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => 237 | { 238 | b.HasOne("Microsoft.AspNetCore.Identity.IdentityUser", null) 239 | .WithMany() 240 | .HasForeignKey("UserId") 241 | .OnDelete(DeleteBehavior.Cascade) 242 | .IsRequired(); 243 | }); 244 | 245 | modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => 246 | { 247 | b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) 248 | .WithMany() 249 | .HasForeignKey("RoleId") 250 | .OnDelete(DeleteBehavior.Cascade) 251 | .IsRequired(); 252 | 253 | b.HasOne("Microsoft.AspNetCore.Identity.IdentityUser", null) 254 | .WithMany() 255 | .HasForeignKey("UserId") 256 | .OnDelete(DeleteBehavior.Cascade) 257 | .IsRequired(); 258 | }); 259 | 260 | modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => 261 | { 262 | b.HasOne("Microsoft.AspNetCore.Identity.IdentityUser", null) 263 | .WithMany() 264 | .HasForeignKey("UserId") 265 | .OnDelete(DeleteBehavior.Cascade) 266 | .IsRequired(); 267 | }); 268 | #pragma warning restore 612, 618 269 | } 270 | } 271 | } 272 | -------------------------------------------------------------------------------- /JwtAuthSample/JwtAuthSampleAPI/Models/LoginCredentials.cs: -------------------------------------------------------------------------------- 1 | namespace JwtAuthSampleAPI.Models 2 | { 3 | public class LoginCredentials 4 | { 5 | public string Username { get; set; } 6 | 7 | public string Password { get; set; } 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /JwtAuthSample/JwtAuthSampleAPI/Models/UserDetails.cs: -------------------------------------------------------------------------------- 1 | using System.ComponentModel.DataAnnotations; 2 | 3 | namespace JwtAuthSampleAPI.Models 4 | { 5 | public class UserDetails 6 | { 7 | [Required] 8 | public string UserName { get; set; } 9 | 10 | [Required] 11 | public string Password { get; set; } 12 | 13 | [Required] 14 | public string Email { get; set; } 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /JwtAuthSample/JwtAuthSampleAPI/Models/WeatherForecast.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace JwtAuthSampleAPI.Models 4 | { 5 | public class WeatherForecast 6 | { 7 | public DateTime Date { get; set; } 8 | 9 | public int TemperatureC { get; set; } 10 | 11 | public int TemperatureF => 32 + (int)(TemperatureC / 0.5556); 12 | 13 | public string Summary { get; set; } 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /JwtAuthSample/JwtAuthSampleAPI/Program.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Hosting; 2 | using Microsoft.Extensions.Hosting; 3 | 4 | namespace JwtAuthSampleAPI 5 | { 6 | public class Program 7 | { 8 | public static void Main(string[] args) 9 | { 10 | CreateHostBuilder(args).Build().Run(); 11 | } 12 | 13 | public static IHostBuilder CreateHostBuilder(string[] args) => 14 | Host.CreateDefaultBuilder(args) 15 | .ConfigureWebHostDefaults(webBuilder => 16 | { 17 | webBuilder.UseStartup(); 18 | }); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /JwtAuthSample/JwtAuthSampleAPI/Properties/launchSettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "http://json.schemastore.org/launchsettings.json", 3 | "iisSettings": { 4 | "windowsAuthentication": false, 5 | "anonymousAuthentication": true, 6 | "iisExpress": { 7 | "applicationUrl": "http://localhost:61610", 8 | "sslPort": 44322 9 | } 10 | }, 11 | "profiles": { 12 | "IIS Express": { 13 | "commandName": "IISExpress", 14 | "launchBrowser": true, 15 | "launchUrl": "weatherforecast", 16 | "environmentVariables": { 17 | "ASPNETCORE_ENVIRONMENT": "Development" 18 | } 19 | }, 20 | "CookieAuthSampleAPI": { 21 | "commandName": "Project", 22 | "launchBrowser": true, 23 | "launchUrl": "weatherforecast", 24 | "applicationUrl": "https://localhost:5001;http://localhost:5000", 25 | "environmentVariables": { 26 | "ASPNETCORE_ENVIRONMENT": "Development" 27 | } 28 | } 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /JwtAuthSample/JwtAuthSampleAPI/Startup.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Text; 3 | using JwtAuthSampleAPI.Configuration; 4 | using JwtAuthSampleAPI.Data; 5 | using Microsoft.AspNetCore.Authentication.JwtBearer; 6 | using Microsoft.AspNetCore.Builder; 7 | using Microsoft.AspNetCore.Hosting; 8 | using Microsoft.AspNetCore.Identity; 9 | using Microsoft.EntityFrameworkCore; 10 | using Microsoft.Extensions.Configuration; 11 | using Microsoft.Extensions.DependencyInjection; 12 | using Microsoft.Extensions.Hosting; 13 | using Microsoft.IdentityModel.Tokens; 14 | 15 | namespace JwtAuthSampleAPI 16 | { 17 | public class Startup 18 | { 19 | public Startup(IConfiguration configuration) 20 | { 21 | Configuration = configuration; 22 | } 23 | 24 | public IConfiguration Configuration { get; } 25 | 26 | // This method gets called by the runtime. Use this method to add services to the container. 27 | public void ConfigureServices(IServiceCollection services) 28 | { 29 | services.AddCors(); 30 | services.AddControllers(); 31 | 32 | services.AddDbContext(options => 33 | options.UseSqlServer(Configuration.GetConnectionString("SqlConnection"))); 34 | 35 | services.AddIdentity(options => options.SignIn.RequireConfirmedAccount = true) 36 | .AddEntityFrameworkStores(); 37 | 38 | // configure strongly typed settings objects 39 | var jwtSection = Configuration.GetSection("JwtBearerTokenSettings"); 40 | services.Configure(jwtSection); 41 | var jwtBearerTokenSettings = jwtSection.Get(); 42 | var key = Encoding.ASCII.GetBytes(jwtBearerTokenSettings.SecretKey); 43 | 44 | services.AddAuthentication(options => 45 | { 46 | options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; 47 | options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; 48 | }) 49 | .AddJwtBearer(options => 50 | { 51 | options.RequireHttpsMetadata = false; 52 | options.SaveToken = true; 53 | options.TokenValidationParameters = new TokenValidationParameters() 54 | { 55 | ValidIssuer = jwtBearerTokenSettings.Issuer, 56 | ValidAudience = jwtBearerTokenSettings.Audience, 57 | IssuerSigningKey = new SymmetricSecurityKey(key), 58 | }; 59 | }); 60 | } 61 | 62 | // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. 63 | public void Configure(IApplicationBuilder app, IWebHostEnvironment env) 64 | { 65 | app.UseCors(x => x 66 | .AllowAnyOrigin() 67 | .AllowAnyMethod() 68 | .AllowAnyHeader()); 69 | 70 | if (env.IsDevelopment()) 71 | { 72 | app.UseDeveloperExceptionPage(); 73 | } 74 | 75 | app.UseHttpsRedirection(); 76 | app.UseRouting(); 77 | app.UseAuthentication(); 78 | app.UseAuthorization(); 79 | 80 | app.UseEndpoints(endpoints => 81 | { 82 | endpoints.MapControllers(); 83 | }); 84 | } 85 | } 86 | } 87 | -------------------------------------------------------------------------------- /JwtAuthSample/JwtAuthSampleAPI/appsettings.Development.json: -------------------------------------------------------------------------------- 1 | { 2 | "Logging": { 3 | "LogLevel": { 4 | "Default": "Information", 5 | "Microsoft": "Warning", 6 | "Microsoft.Hosting.Lifetime": "Information" 7 | } 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /JwtAuthSample/JwtAuthSampleAPI/appsettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "JwtBearerTokenSettings": { 3 | "SecretKey": "ThisIsSomeSampleSymmetricEncryptionKey", 4 | "Audience": "https://localhost:44322/", 5 | "Issuer": "https://localhost:44322/", 6 | "ExpiryTimeInSeconds": 60 7 | 8 | }, 9 | "Logging": { 10 | "LogLevel": { 11 | "Default": "Information", 12 | "Microsoft": "Warning", 13 | "Microsoft.Hosting.Lifetime": "Information" 14 | } 15 | }, 16 | 17 | "ConnectionStrings": { 18 | "SqlConnection": "Server=(localdb)\\MSSQLLocalDB;Initial Catalog=MyAppDb; Integrated Security=true;" 19 | }, 20 | 21 | "AllowedHosts": "*" 22 | } 23 | -------------------------------------------------------------------------------- /JwtAuthSample/Postman-Collection/JwtAuthSample.postman_collection.json: -------------------------------------------------------------------------------- 1 | { 2 | "info": { 3 | "_postman_id": "60255ce2-ab95-426f-9bcc-6a75d849c95e", 4 | "name": "Jwt Auth Sample", 5 | "schema": "https://schema.getpostman.com/json/collection/v2.1.0/collection.json" 6 | }, 7 | "item": [ 8 | { 9 | "name": "User Registration", 10 | "request": { 11 | "method": "POST", 12 | "header": [ 13 | { 14 | "key": "Accept", 15 | "value": "application/json", 16 | "type": "text" 17 | }, 18 | { 19 | "key": "Content-Type", 20 | "value": "application/json", 21 | "type": "text" 22 | } 23 | ], 24 | "body": { 25 | "mode": "raw", 26 | "raw": "{\n\t\"username\": \"test\",\n\t\"password\": \"Test@12345\",\n\t\"email\": \"abc@abc.com\"\n}" 27 | }, 28 | "url": { 29 | "raw": "https://localhost:44322/api/auth/register", 30 | "protocol": "https", 31 | "host": [ 32 | "localhost" 33 | ], 34 | "port": "44322", 35 | "path": [ 36 | "api", 37 | "auth", 38 | "register" 39 | ], 40 | "query": [ 41 | { 42 | "key": "username", 43 | "value": "test", 44 | "disabled": true 45 | }, 46 | { 47 | "key": "password", 48 | "value": "testpassword", 49 | "disabled": true 50 | } 51 | ] 52 | } 53 | }, 54 | "response": [] 55 | }, 56 | { 57 | "name": "Login", 58 | "request": { 59 | "method": "POST", 60 | "header": [ 61 | { 62 | "key": "Accept", 63 | "value": "application/json", 64 | "type": "text" 65 | }, 66 | { 67 | "key": "Content-Type", 68 | "value": "application/json", 69 | "type": "text" 70 | } 71 | ], 72 | "body": { 73 | "mode": "raw", 74 | "raw": "{\n\t\"username\": \"test\",\n\t\"password\": \"Test@12345\"\n}" 75 | }, 76 | "url": { 77 | "raw": "https://localhost:44322/api/auth/login", 78 | "protocol": "https", 79 | "host": [ 80 | "localhost" 81 | ], 82 | "port": "44322", 83 | "path": [ 84 | "api", 85 | "auth", 86 | "login" 87 | ] 88 | }, 89 | "description": "Login to get the cookie" 90 | }, 91 | "response": [] 92 | }, 93 | { 94 | "name": "Weather Forecast", 95 | "request": { 96 | "method": "GET", 97 | "header": [], 98 | "url": { 99 | "raw": "https://localhost:44322/api/weatherforecast", 100 | "protocol": "https", 101 | "host": [ 102 | "localhost" 103 | ], 104 | "port": "44322", 105 | "path": [ 106 | "api", 107 | "weatherforecast" 108 | ] 109 | } 110 | }, 111 | "response": [] 112 | }, 113 | { 114 | "name": "Logout", 115 | "request": { 116 | "method": "POST", 117 | "header": [ 118 | { 119 | "key": "Accept", 120 | "value": "application/json", 121 | "type": "text" 122 | }, 123 | { 124 | "key": "Content-Type", 125 | "value": "application/json", 126 | "type": "text" 127 | } 128 | ], 129 | "body": { 130 | "mode": "raw", 131 | "raw": "{\n\t\"username\": \"test\",\n\t\"password\": \"Test@12345\"\n}" 132 | }, 133 | "url": { 134 | "raw": "https://localhost:44322/api/auth/login", 135 | "protocol": "https", 136 | "host": [ 137 | "localhost" 138 | ], 139 | "port": "44322", 140 | "path": [ 141 | "api", 142 | "auth", 143 | "login" 144 | ] 145 | }, 146 | "description": "Login to get the cookie" 147 | }, 148 | "response": [] 149 | } 150 | ], 151 | "protocolProfileBehavior": {} 152 | } -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2020 Manoj Choudhari 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # ASP .NET Core Identity 2 | This repository contains the samples which I have created for my blog https://manojchoudhari.wordpress.com (now https://thecodeblogger.com) 3 | 4 | There are 1 base sample in the repository with name IdentityConfigurationSample. 5 | This sample is further used as base for CookieAuthSample and JwtAuthSample. 6 | 7 | 8 | -------------------------------------------------------------------------------- /RefreshJwtAuthSample/JwtAuthSampleAPI/Configuration/JwtBearerTokenSettings.cs: -------------------------------------------------------------------------------- 1 | namespace JwtAuthRefreshTokenSampleAPI.Configuration 2 | { 3 | public class JwtBearerTokenSettings 4 | { 5 | public string SecretKey { get; set; } 6 | public string Audience { get; set; } 7 | public string Issuer { get; set; } 8 | public int ExpiryTimeInSeconds { get; set; } 9 | public int RefreshTokenExpiryInDays { get; set; } 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /RefreshJwtAuthSample/JwtAuthSampleAPI/Controllers/AuthController.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.IdentityModel.Tokens.Jwt; 4 | using System.Linq; 5 | using System.Security.Claims; 6 | using System.Security.Cryptography; 7 | using System.Text; 8 | using System.Threading.Tasks; 9 | 10 | using JwtAuthRefreshTokenSampleAPI.Configuration; 11 | using JwtAuthRefreshTokenSampleAPI.Data; 12 | using JwtAuthRefreshTokenSampleAPI.Models; 13 | 14 | using Microsoft.AspNetCore.Authorization; 15 | using Microsoft.AspNetCore.Http; 16 | using Microsoft.AspNetCore.Identity; 17 | using Microsoft.AspNetCore.Mvc; 18 | using Microsoft.AspNetCore.Mvc.ModelBinding; 19 | using Microsoft.EntityFrameworkCore; 20 | using Microsoft.Extensions.Options; 21 | using Microsoft.IdentityModel.Tokens; 22 | 23 | namespace JwtAuthRefreshTokenSampleAPI.Controllers 24 | { 25 | [Route("api/[controller]")] 26 | [ApiController] 27 | public class AuthController : ControllerBase 28 | { 29 | private readonly JwtBearerTokenSettings jwtBearerTokenSettings; 30 | private readonly UserManager userManager; 31 | private readonly ApplicationDbContext dbContext; 32 | 33 | public AuthController(IOptions jwtTokenOptions, UserManager userManager, ApplicationDbContext dbContext) 34 | { 35 | this.jwtBearerTokenSettings = jwtTokenOptions.Value; 36 | this.userManager = userManager; 37 | this.dbContext = dbContext; 38 | } 39 | 40 | [HttpPost] 41 | [Route("Register")] 42 | public async Task Register([FromBody] UserDetails userDetails) 43 | { 44 | if (!ModelState.IsValid || userDetails == null) 45 | { 46 | return new BadRequestObjectResult(new { Message = "User Registration Failed" }); 47 | } 48 | 49 | var identityUser = new ApplicationUser() { UserName = userDetails.UserName, Email = userDetails.Email }; 50 | var result = await userManager.CreateAsync(identityUser, userDetails.Password); 51 | if (!result.Succeeded) 52 | { 53 | var dictionary = new ModelStateDictionary(); 54 | foreach (IdentityError error in result.Errors) 55 | { 56 | dictionary.AddModelError(error.Code, error.Description); 57 | } 58 | 59 | return new BadRequestObjectResult(new { Message = "User Registration Failed", Errors = dictionary }); 60 | } 61 | 62 | return Ok(new { Message = "User Reigstration Successful" }); 63 | } 64 | 65 | [HttpPost] 66 | [Route("Login")] 67 | public async Task Login([FromBody] LoginCredentials credentials) 68 | { 69 | ApplicationUser identityUser; 70 | 71 | if (!ModelState.IsValid 72 | || credentials == null 73 | || (identityUser = await ValidateUser(credentials)) == null) 74 | { 75 | return new BadRequestObjectResult(new { Message = "Login failed" }); 76 | } 77 | 78 | var token = GenerateTokens(identityUser); 79 | return Ok(new { Token = token, Message = "Success" }); 80 | } 81 | 82 | [AllowAnonymous] 83 | [HttpPost] 84 | [Route("RefreshToken")] 85 | public IActionResult RefreshToken() 86 | { 87 | var token = HttpContext.Request.Cookies["refreshToken"]; 88 | var identityUser = dbContext.Users.Include(x => x.RefreshTokens) 89 | .FirstOrDefault(x => x.RefreshTokens.Any(y => y.Token == token && y.UserId == x.Id)); 90 | 91 | // Get existing refresh token if it is valid and revoke it 92 | var existingRefreshToken = GetValidRefreshToken(token, identityUser); 93 | if(existingRefreshToken == null) 94 | { 95 | return new BadRequestObjectResult(new { Message = "Failed" }); 96 | } 97 | 98 | existingRefreshToken.RevokedByIp = HttpContext.Connection.RemoteIpAddress.ToString(); 99 | existingRefreshToken.RevokedOn = DateTime.UtcNow; 100 | 101 | // Generate new tokens 102 | var newToken = GenerateTokens(identityUser); 103 | return Ok(new { Token = newToken, Message = "Success" }); 104 | } 105 | 106 | [HttpPost] 107 | [Route("RevokeToken")] 108 | public IActionResult RevokeToken(string token) 109 | { 110 | // If user found, then revoke 111 | if (RevokeRefreshToken(token)) 112 | { 113 | return Ok(new { Message = "Success" }); 114 | } 115 | 116 | // Otherwise, return error 117 | return new BadRequestObjectResult(new { Message = "Failed" }); 118 | } 119 | 120 | [HttpPost] 121 | [Route("Logout")] 122 | public async Task Logout() 123 | { 124 | // Revoke Refresh Token 125 | RevokeRefreshToken(); 126 | return Ok(new { Token = "", Message = "Logged Out" }); 127 | } 128 | 129 | private RefreshToken GetValidRefreshToken(string token, ApplicationUser identityUser) 130 | { 131 | if (identityUser == null) 132 | { 133 | return null; 134 | } 135 | 136 | var existingToken = identityUser.RefreshTokens.FirstOrDefault(x => x.Token == token); 137 | return IsRefreshTokenValid(existingToken) ? existingToken : null; 138 | } 139 | 140 | private bool RevokeRefreshToken(string token = null) 141 | { 142 | token = token == null ? HttpContext.Request.Cookies["refreshToken"] : token; 143 | var identityUser = dbContext.Users.Include(x => x.RefreshTokens) 144 | .FirstOrDefault(x => x.RefreshTokens.Any(y => y.Token == token && y.UserId == x.Id)); 145 | if (identityUser == null) 146 | { 147 | return false; 148 | } 149 | 150 | // Revoke Refresh token 151 | var existingToken = identityUser.RefreshTokens.FirstOrDefault(x => x.Token == token); 152 | existingToken.RevokedByIp = HttpContext.Connection.RemoteIpAddress.ToString(); 153 | existingToken.RevokedOn = DateTime.UtcNow; 154 | dbContext.Update(identityUser); 155 | dbContext.SaveChanges(); 156 | return true; 157 | } 158 | 159 | private async Task ValidateUser(LoginCredentials credentials) 160 | { 161 | var identityUser = await userManager.FindByNameAsync(credentials.Username); 162 | if (identityUser != null) 163 | { 164 | var result = userManager.PasswordHasher.VerifyHashedPassword(identityUser, identityUser.PasswordHash, credentials.Password); 165 | return result == PasswordVerificationResult.Failed ? null : identityUser; 166 | } 167 | 168 | return null; 169 | } 170 | 171 | private string GenerateTokens(ApplicationUser identityUser) 172 | { 173 | // Generate access token 174 | string accessToken = GenerateAccessToken(identityUser); 175 | 176 | // Generate refresh token and set it to cookie 177 | var ipAddress = HttpContext.Connection.RemoteIpAddress.ToString(); 178 | var refreshToken = GenerateRefreshToken(ipAddress, identityUser.Id); 179 | 180 | // Set Refresh Token Cookie 181 | var cookieOptions = new CookieOptions 182 | { 183 | HttpOnly = true, 184 | Expires = DateTime.UtcNow.AddDays(7) 185 | }; 186 | HttpContext.Response.Cookies.Append("refreshToken", refreshToken.Token, cookieOptions); 187 | 188 | // Save refresh token to database 189 | if (identityUser.RefreshTokens == null) 190 | { 191 | identityUser.RefreshTokens = new List(); 192 | } 193 | 194 | identityUser.RefreshTokens.Add(refreshToken); 195 | dbContext.Update(identityUser); 196 | dbContext.SaveChanges(); 197 | return accessToken; 198 | } 199 | 200 | private string GenerateAccessToken(ApplicationUser identityUser) 201 | { 202 | var tokenHandler = new JwtSecurityTokenHandler(); 203 | var key = Encoding.ASCII.GetBytes(jwtBearerTokenSettings.SecretKey); 204 | 205 | var tokenDescriptor = new SecurityTokenDescriptor 206 | { 207 | Subject = new ClaimsIdentity(new Claim[] 208 | { 209 | new Claim(ClaimTypes.Name, identityUser.UserName.ToString()), 210 | new Claim(ClaimTypes.Email, identityUser.Email) 211 | }), 212 | 213 | Expires = DateTime.Now.AddSeconds(jwtBearerTokenSettings.ExpiryTimeInSeconds), 214 | SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature), 215 | Audience = jwtBearerTokenSettings.Audience, 216 | Issuer = jwtBearerTokenSettings.Issuer 217 | }; 218 | 219 | var token = tokenHandler.CreateToken(tokenDescriptor); 220 | return tokenHandler.WriteToken(token); 221 | } 222 | 223 | private RefreshToken GenerateRefreshToken(string ipAddress, string userId) 224 | { 225 | using (var rngCryptoServiceProvider = new RNGCryptoServiceProvider()) 226 | { 227 | var randomBytes = new byte[64]; 228 | rngCryptoServiceProvider.GetBytes(randomBytes); 229 | return new RefreshToken 230 | { 231 | Token = Convert.ToBase64String(randomBytes), 232 | ExpiryOn = DateTime.UtcNow.AddDays(jwtBearerTokenSettings.RefreshTokenExpiryInDays), 233 | CreatedOn = DateTime.UtcNow, 234 | CreatedByIp = ipAddress, 235 | UserId = userId 236 | }; 237 | } 238 | } 239 | 240 | private bool IsRefreshTokenValid(RefreshToken existingToken) 241 | { 242 | // Is token already revoked, then return false 243 | if (existingToken.RevokedByIp != null && existingToken.RevokedOn != DateTime.MinValue) 244 | { 245 | return false; 246 | } 247 | 248 | // Token already expired, then return false 249 | if (existingToken.ExpiryOn <= DateTime.UtcNow) 250 | { 251 | return false; 252 | } 253 | 254 | return true; 255 | } 256 | } 257 | } -------------------------------------------------------------------------------- /RefreshJwtAuthSample/JwtAuthSampleAPI/Controllers/WeatherForecastController.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | 5 | using JwtAuthRefreshTokenSampleAPI.Models; 6 | using Microsoft.AspNetCore.Authorization; 7 | using Microsoft.AspNetCore.Mvc; 8 | using Microsoft.Extensions.Logging; 9 | 10 | 11 | namespace JwtAuthRefreshTokenSampleAPI.Controllers 12 | { 13 | [Authorize] 14 | [ApiController] 15 | [Route("api/[controller]")] 16 | public class WeatherForecastController : ControllerBase 17 | { 18 | private static readonly string[] Summaries = new[] 19 | { 20 | "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching" 21 | }; 22 | 23 | private readonly ILogger _logger; 24 | 25 | public WeatherForecastController(ILogger logger) 26 | { 27 | _logger = logger; 28 | } 29 | 30 | [HttpGet] 31 | [Route("")] 32 | public IEnumerable Get() 33 | { 34 | var rng = new Random(); 35 | return Enumerable.Range(1, 5).Select(index => new WeatherForecast 36 | { 37 | Date = DateTime.Now.AddDays(index), 38 | TemperatureC = rng.Next(-20, 55), 39 | Summary = Summaries[rng.Next(Summaries.Length)] 40 | }) 41 | .ToArray(); 42 | } 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /RefreshJwtAuthSample/JwtAuthSampleAPI/Data/ApplicationDbContext.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Identity.EntityFrameworkCore; 2 | using Microsoft.EntityFrameworkCore; 3 | 4 | namespace JwtAuthRefreshTokenSampleAPI.Data 5 | { 6 | public class ApplicationDbContext : IdentityDbContext 7 | { 8 | public ApplicationDbContext(DbContextOptions options) : base(options) 9 | { 10 | 11 | } 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /RefreshJwtAuthSample/JwtAuthSampleAPI/Data/ApplicationUser.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Identity; 2 | using System.Collections.Generic; 3 | 4 | namespace JwtAuthRefreshTokenSampleAPI.Data 5 | { 6 | public class ApplicationUser: IdentityUser 7 | { 8 | public List RefreshTokens { get; set; } 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /RefreshJwtAuthSample/JwtAuthSampleAPI/Data/RefreshToken.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.ComponentModel.DataAnnotations; 3 | 4 | namespace JwtAuthRefreshTokenSampleAPI.Data 5 | { 6 | public class RefreshToken 7 | { 8 | [Key] 9 | public int Id { get; set; } 10 | 11 | public string Token { get; set; } 12 | 13 | public string UserId { get; set; } 14 | 15 | public DateTime ExpiryOn { get; set; } 16 | 17 | public DateTime CreatedOn { get; set; } 18 | 19 | public string CreatedByIp { get; set; } 20 | 21 | public DateTime RevokedOn { get; set; } 22 | 23 | public string RevokedByIp { get; set; } 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /RefreshJwtAuthSample/JwtAuthSampleAPI/JwtAuthRefreshTokenSampleAPI.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | net5.0 5 | JwtAuthRefreshTokenSampleAPI 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | all 14 | runtime; build; native; contentfiles; analyzers; buildtransitive 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | -------------------------------------------------------------------------------- /RefreshJwtAuthSample/JwtAuthSampleAPI/Migrations/20200123192549_First.Designer.cs: -------------------------------------------------------------------------------- 1 | // 2 | using System; 3 | using JwtAuthRefreshTokenSampleAPI.Data; 4 | using Microsoft.EntityFrameworkCore; 5 | using Microsoft.EntityFrameworkCore.Infrastructure; 6 | using Microsoft.EntityFrameworkCore.Metadata; 7 | using Microsoft.EntityFrameworkCore.Migrations; 8 | using Microsoft.EntityFrameworkCore.Storage.ValueConversion; 9 | 10 | namespace JwtAuthRefreshTokenSampleAPI.Migrations 11 | { 12 | [DbContext(typeof(ApplicationDbContext))] 13 | [Migration("20200123192549_First")] 14 | partial class First 15 | { 16 | protected override void BuildTargetModel(ModelBuilder modelBuilder) 17 | { 18 | #pragma warning disable 612, 618 19 | modelBuilder 20 | .HasAnnotation("ProductVersion", "3.1.1") 21 | .HasAnnotation("Relational:MaxIdentifierLength", 128) 22 | .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); 23 | 24 | modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRole", b => 25 | { 26 | b.Property("Id") 27 | .HasColumnType("nvarchar(450)"); 28 | 29 | b.Property("ConcurrencyStamp") 30 | .IsConcurrencyToken() 31 | .HasColumnType("nvarchar(max)"); 32 | 33 | b.Property("Name") 34 | .HasColumnType("nvarchar(256)") 35 | .HasMaxLength(256); 36 | 37 | b.Property("NormalizedName") 38 | .HasColumnType("nvarchar(256)") 39 | .HasMaxLength(256); 40 | 41 | b.HasKey("Id"); 42 | 43 | b.HasIndex("NormalizedName") 44 | .IsUnique() 45 | .HasName("RoleNameIndex") 46 | .HasFilter("[NormalizedName] IS NOT NULL"); 47 | 48 | b.ToTable("AspNetRoles"); 49 | }); 50 | 51 | modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => 52 | { 53 | b.Property("Id") 54 | .ValueGeneratedOnAdd() 55 | .HasColumnType("int") 56 | .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); 57 | 58 | b.Property("ClaimType") 59 | .HasColumnType("nvarchar(max)"); 60 | 61 | b.Property("ClaimValue") 62 | .HasColumnType("nvarchar(max)"); 63 | 64 | b.Property("RoleId") 65 | .IsRequired() 66 | .HasColumnType("nvarchar(450)"); 67 | 68 | b.HasKey("Id"); 69 | 70 | b.HasIndex("RoleId"); 71 | 72 | b.ToTable("AspNetRoleClaims"); 73 | }); 74 | 75 | modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUser", b => 76 | { 77 | b.Property("Id") 78 | .HasColumnType("nvarchar(450)"); 79 | 80 | b.Property("AccessFailedCount") 81 | .HasColumnType("int"); 82 | 83 | b.Property("ConcurrencyStamp") 84 | .IsConcurrencyToken() 85 | .HasColumnType("nvarchar(max)"); 86 | 87 | b.Property("Email") 88 | .HasColumnType("nvarchar(256)") 89 | .HasMaxLength(256); 90 | 91 | b.Property("EmailConfirmed") 92 | .HasColumnType("bit"); 93 | 94 | b.Property("LockoutEnabled") 95 | .HasColumnType("bit"); 96 | 97 | b.Property("LockoutEnd") 98 | .HasColumnType("datetimeoffset"); 99 | 100 | b.Property("NormalizedEmail") 101 | .HasColumnType("nvarchar(256)") 102 | .HasMaxLength(256); 103 | 104 | b.Property("NormalizedUserName") 105 | .HasColumnType("nvarchar(256)") 106 | .HasMaxLength(256); 107 | 108 | b.Property("PasswordHash") 109 | .HasColumnType("nvarchar(max)"); 110 | 111 | b.Property("PhoneNumber") 112 | .HasColumnType("nvarchar(max)"); 113 | 114 | b.Property("PhoneNumberConfirmed") 115 | .HasColumnType("bit"); 116 | 117 | b.Property("SecurityStamp") 118 | .HasColumnType("nvarchar(max)"); 119 | 120 | b.Property("TwoFactorEnabled") 121 | .HasColumnType("bit"); 122 | 123 | b.Property("UserName") 124 | .HasColumnType("nvarchar(256)") 125 | .HasMaxLength(256); 126 | 127 | b.HasKey("Id"); 128 | 129 | b.HasIndex("NormalizedEmail") 130 | .HasName("EmailIndex"); 131 | 132 | b.HasIndex("NormalizedUserName") 133 | .IsUnique() 134 | .HasName("UserNameIndex") 135 | .HasFilter("[NormalizedUserName] IS NOT NULL"); 136 | 137 | b.ToTable("AspNetUsers"); 138 | }); 139 | 140 | modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => 141 | { 142 | b.Property("Id") 143 | .ValueGeneratedOnAdd() 144 | .HasColumnType("int") 145 | .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); 146 | 147 | b.Property("ClaimType") 148 | .HasColumnType("nvarchar(max)"); 149 | 150 | b.Property("ClaimValue") 151 | .HasColumnType("nvarchar(max)"); 152 | 153 | b.Property("UserId") 154 | .IsRequired() 155 | .HasColumnType("nvarchar(450)"); 156 | 157 | b.HasKey("Id"); 158 | 159 | b.HasIndex("UserId"); 160 | 161 | b.ToTable("AspNetUserClaims"); 162 | }); 163 | 164 | modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => 165 | { 166 | b.Property("LoginProvider") 167 | .HasColumnType("nvarchar(450)"); 168 | 169 | b.Property("ProviderKey") 170 | .HasColumnType("nvarchar(450)"); 171 | 172 | b.Property("ProviderDisplayName") 173 | .HasColumnType("nvarchar(max)"); 174 | 175 | b.Property("UserId") 176 | .IsRequired() 177 | .HasColumnType("nvarchar(450)"); 178 | 179 | b.HasKey("LoginProvider", "ProviderKey"); 180 | 181 | b.HasIndex("UserId"); 182 | 183 | b.ToTable("AspNetUserLogins"); 184 | }); 185 | 186 | modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => 187 | { 188 | b.Property("UserId") 189 | .HasColumnType("nvarchar(450)"); 190 | 191 | b.Property("RoleId") 192 | .HasColumnType("nvarchar(450)"); 193 | 194 | b.HasKey("UserId", "RoleId"); 195 | 196 | b.HasIndex("RoleId"); 197 | 198 | b.ToTable("AspNetUserRoles"); 199 | }); 200 | 201 | modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => 202 | { 203 | b.Property("UserId") 204 | .HasColumnType("nvarchar(450)"); 205 | 206 | b.Property("LoginProvider") 207 | .HasColumnType("nvarchar(450)"); 208 | 209 | b.Property("Name") 210 | .HasColumnType("nvarchar(450)"); 211 | 212 | b.Property("Value") 213 | .HasColumnType("nvarchar(max)"); 214 | 215 | b.HasKey("UserId", "LoginProvider", "Name"); 216 | 217 | b.ToTable("AspNetUserTokens"); 218 | }); 219 | 220 | modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => 221 | { 222 | b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) 223 | .WithMany() 224 | .HasForeignKey("RoleId") 225 | .OnDelete(DeleteBehavior.Cascade) 226 | .IsRequired(); 227 | }); 228 | 229 | modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => 230 | { 231 | b.HasOne("Microsoft.AspNetCore.Identity.IdentityUser", null) 232 | .WithMany() 233 | .HasForeignKey("UserId") 234 | .OnDelete(DeleteBehavior.Cascade) 235 | .IsRequired(); 236 | }); 237 | 238 | modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => 239 | { 240 | b.HasOne("Microsoft.AspNetCore.Identity.IdentityUser", null) 241 | .WithMany() 242 | .HasForeignKey("UserId") 243 | .OnDelete(DeleteBehavior.Cascade) 244 | .IsRequired(); 245 | }); 246 | 247 | modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => 248 | { 249 | b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) 250 | .WithMany() 251 | .HasForeignKey("RoleId") 252 | .OnDelete(DeleteBehavior.Cascade) 253 | .IsRequired(); 254 | 255 | b.HasOne("Microsoft.AspNetCore.Identity.IdentityUser", null) 256 | .WithMany() 257 | .HasForeignKey("UserId") 258 | .OnDelete(DeleteBehavior.Cascade) 259 | .IsRequired(); 260 | }); 261 | 262 | modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => 263 | { 264 | b.HasOne("Microsoft.AspNetCore.Identity.IdentityUser", null) 265 | .WithMany() 266 | .HasForeignKey("UserId") 267 | .OnDelete(DeleteBehavior.Cascade) 268 | .IsRequired(); 269 | }); 270 | #pragma warning restore 612, 618 271 | } 272 | } 273 | } 274 | -------------------------------------------------------------------------------- /RefreshJwtAuthSample/JwtAuthSampleAPI/Migrations/20200123192549_First.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using Microsoft.EntityFrameworkCore.Migrations; 3 | 4 | namespace JwtAuthRefreshTokenSampleAPI.Migrations 5 | { 6 | public partial class First : Migration 7 | { 8 | protected override void Up(MigrationBuilder migrationBuilder) 9 | { 10 | migrationBuilder.CreateTable( 11 | name: "AspNetRoles", 12 | columns: table => new 13 | { 14 | Id = table.Column(nullable: false), 15 | Name = table.Column(maxLength: 256, nullable: true), 16 | NormalizedName = table.Column(maxLength: 256, nullable: true), 17 | ConcurrencyStamp = table.Column(nullable: true) 18 | }, 19 | constraints: table => 20 | { 21 | table.PrimaryKey("PK_AspNetRoles", x => x.Id); 22 | }); 23 | 24 | migrationBuilder.CreateTable( 25 | name: "AspNetUsers", 26 | columns: table => new 27 | { 28 | Id = table.Column(nullable: false), 29 | UserName = table.Column(maxLength: 256, nullable: true), 30 | NormalizedUserName = table.Column(maxLength: 256, nullable: true), 31 | Email = table.Column(maxLength: 256, nullable: true), 32 | NormalizedEmail = table.Column(maxLength: 256, nullable: true), 33 | EmailConfirmed = table.Column(nullable: false), 34 | PasswordHash = table.Column(nullable: true), 35 | SecurityStamp = table.Column(nullable: true), 36 | ConcurrencyStamp = table.Column(nullable: true), 37 | PhoneNumber = table.Column(nullable: true), 38 | PhoneNumberConfirmed = table.Column(nullable: false), 39 | TwoFactorEnabled = table.Column(nullable: false), 40 | LockoutEnd = table.Column(nullable: true), 41 | LockoutEnabled = table.Column(nullable: false), 42 | AccessFailedCount = table.Column(nullable: false) 43 | }, 44 | constraints: table => 45 | { 46 | table.PrimaryKey("PK_AspNetUsers", x => x.Id); 47 | }); 48 | 49 | migrationBuilder.CreateTable( 50 | name: "AspNetRoleClaims", 51 | columns: table => new 52 | { 53 | Id = table.Column(nullable: false) 54 | .Annotation("SqlServer:Identity", "1, 1"), 55 | RoleId = table.Column(nullable: false), 56 | ClaimType = table.Column(nullable: true), 57 | ClaimValue = table.Column(nullable: true) 58 | }, 59 | constraints: table => 60 | { 61 | table.PrimaryKey("PK_AspNetRoleClaims", x => x.Id); 62 | table.ForeignKey( 63 | name: "FK_AspNetRoleClaims_AspNetRoles_RoleId", 64 | column: x => x.RoleId, 65 | principalTable: "AspNetRoles", 66 | principalColumn: "Id", 67 | onDelete: ReferentialAction.Cascade); 68 | }); 69 | 70 | migrationBuilder.CreateTable( 71 | name: "AspNetUserClaims", 72 | columns: table => new 73 | { 74 | Id = table.Column(nullable: false) 75 | .Annotation("SqlServer:Identity", "1, 1"), 76 | UserId = table.Column(nullable: false), 77 | ClaimType = table.Column(nullable: true), 78 | ClaimValue = table.Column(nullable: true) 79 | }, 80 | constraints: table => 81 | { 82 | table.PrimaryKey("PK_AspNetUserClaims", x => x.Id); 83 | table.ForeignKey( 84 | name: "FK_AspNetUserClaims_AspNetUsers_UserId", 85 | column: x => x.UserId, 86 | principalTable: "AspNetUsers", 87 | principalColumn: "Id", 88 | onDelete: ReferentialAction.Cascade); 89 | }); 90 | 91 | migrationBuilder.CreateTable( 92 | name: "AspNetUserLogins", 93 | columns: table => new 94 | { 95 | LoginProvider = table.Column(nullable: false), 96 | ProviderKey = table.Column(nullable: false), 97 | ProviderDisplayName = table.Column(nullable: true), 98 | UserId = table.Column(nullable: false) 99 | }, 100 | constraints: table => 101 | { 102 | table.PrimaryKey("PK_AspNetUserLogins", x => new { x.LoginProvider, x.ProviderKey }); 103 | table.ForeignKey( 104 | name: "FK_AspNetUserLogins_AspNetUsers_UserId", 105 | column: x => x.UserId, 106 | principalTable: "AspNetUsers", 107 | principalColumn: "Id", 108 | onDelete: ReferentialAction.Cascade); 109 | }); 110 | 111 | migrationBuilder.CreateTable( 112 | name: "AspNetUserRoles", 113 | columns: table => new 114 | { 115 | UserId = table.Column(nullable: false), 116 | RoleId = table.Column(nullable: false) 117 | }, 118 | constraints: table => 119 | { 120 | table.PrimaryKey("PK_AspNetUserRoles", x => new { x.UserId, x.RoleId }); 121 | table.ForeignKey( 122 | name: "FK_AspNetUserRoles_AspNetRoles_RoleId", 123 | column: x => x.RoleId, 124 | principalTable: "AspNetRoles", 125 | principalColumn: "Id", 126 | onDelete: ReferentialAction.Cascade); 127 | table.ForeignKey( 128 | name: "FK_AspNetUserRoles_AspNetUsers_UserId", 129 | column: x => x.UserId, 130 | principalTable: "AspNetUsers", 131 | principalColumn: "Id", 132 | onDelete: ReferentialAction.Cascade); 133 | }); 134 | 135 | migrationBuilder.CreateTable( 136 | name: "AspNetUserTokens", 137 | columns: table => new 138 | { 139 | UserId = table.Column(nullable: false), 140 | LoginProvider = table.Column(nullable: false), 141 | Name = table.Column(nullable: false), 142 | Value = table.Column(nullable: true) 143 | }, 144 | constraints: table => 145 | { 146 | table.PrimaryKey("PK_AspNetUserTokens", x => new { x.UserId, x.LoginProvider, x.Name }); 147 | table.ForeignKey( 148 | name: "FK_AspNetUserTokens_AspNetUsers_UserId", 149 | column: x => x.UserId, 150 | principalTable: "AspNetUsers", 151 | principalColumn: "Id", 152 | onDelete: ReferentialAction.Cascade); 153 | }); 154 | 155 | migrationBuilder.CreateIndex( 156 | name: "IX_AspNetRoleClaims_RoleId", 157 | table: "AspNetRoleClaims", 158 | column: "RoleId"); 159 | 160 | migrationBuilder.CreateIndex( 161 | name: "RoleNameIndex", 162 | table: "AspNetRoles", 163 | column: "NormalizedName", 164 | unique: true, 165 | filter: "[NormalizedName] IS NOT NULL"); 166 | 167 | migrationBuilder.CreateIndex( 168 | name: "IX_AspNetUserClaims_UserId", 169 | table: "AspNetUserClaims", 170 | column: "UserId"); 171 | 172 | migrationBuilder.CreateIndex( 173 | name: "IX_AspNetUserLogins_UserId", 174 | table: "AspNetUserLogins", 175 | column: "UserId"); 176 | 177 | migrationBuilder.CreateIndex( 178 | name: "IX_AspNetUserRoles_RoleId", 179 | table: "AspNetUserRoles", 180 | column: "RoleId"); 181 | 182 | migrationBuilder.CreateIndex( 183 | name: "EmailIndex", 184 | table: "AspNetUsers", 185 | column: "NormalizedEmail"); 186 | 187 | migrationBuilder.CreateIndex( 188 | name: "UserNameIndex", 189 | table: "AspNetUsers", 190 | column: "NormalizedUserName", 191 | unique: true, 192 | filter: "[NormalizedUserName] IS NOT NULL"); 193 | } 194 | 195 | protected override void Down(MigrationBuilder migrationBuilder) 196 | { 197 | migrationBuilder.DropTable( 198 | name: "AspNetRoleClaims"); 199 | 200 | migrationBuilder.DropTable( 201 | name: "AspNetUserClaims"); 202 | 203 | migrationBuilder.DropTable( 204 | name: "AspNetUserLogins"); 205 | 206 | migrationBuilder.DropTable( 207 | name: "AspNetUserRoles"); 208 | 209 | migrationBuilder.DropTable( 210 | name: "AspNetUserTokens"); 211 | 212 | migrationBuilder.DropTable( 213 | name: "AspNetRoles"); 214 | 215 | migrationBuilder.DropTable( 216 | name: "AspNetUsers"); 217 | } 218 | } 219 | } 220 | -------------------------------------------------------------------------------- /RefreshJwtAuthSample/JwtAuthSampleAPI/Migrations/20201128135409_Second.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using Microsoft.EntityFrameworkCore.Migrations; 3 | 4 | namespace JwtAuthRefreshTokenSampleAPI.Migrations 5 | { 6 | public partial class Second : Migration 7 | { 8 | protected override void Up(MigrationBuilder migrationBuilder) 9 | { 10 | migrationBuilder.CreateTable( 11 | name: "RefreshToken", 12 | columns: table => new 13 | { 14 | Id = table.Column(nullable: false) 15 | .Annotation("SqlServer:Identity", "1, 1"), 16 | Token = table.Column(nullable: true), 17 | UserId = table.Column(nullable: true), 18 | ExpiryOn = table.Column(nullable: false), 19 | CreatedOn = table.Column(nullable: false), 20 | CreatedByIp = table.Column(nullable: true), 21 | RevokedOn = table.Column(nullable: false), 22 | RevokedByIp = table.Column(nullable: true), 23 | ApplicationUserId = table.Column(nullable: true) 24 | }, 25 | constraints: table => 26 | { 27 | table.PrimaryKey("PK_RefreshToken", x => x.Id); 28 | table.ForeignKey( 29 | name: "FK_RefreshToken_AspNetUsers_ApplicationUserId", 30 | column: x => x.ApplicationUserId, 31 | principalTable: "AspNetUsers", 32 | principalColumn: "Id", 33 | onDelete: ReferentialAction.Restrict); 34 | }); 35 | 36 | migrationBuilder.CreateIndex( 37 | name: "IX_RefreshToken_ApplicationUserId", 38 | table: "RefreshToken", 39 | column: "ApplicationUserId"); 40 | } 41 | 42 | protected override void Down(MigrationBuilder migrationBuilder) 43 | { 44 | migrationBuilder.DropTable( 45 | name: "RefreshToken"); 46 | } 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /RefreshJwtAuthSample/JwtAuthSampleAPI/Migrations/ApplicationDbContextModelSnapshot.cs: -------------------------------------------------------------------------------- 1 | // 2 | using System; 3 | using JwtAuthRefreshTokenSampleAPI.Data; 4 | using Microsoft.EntityFrameworkCore; 5 | using Microsoft.EntityFrameworkCore.Infrastructure; 6 | using Microsoft.EntityFrameworkCore.Metadata; 7 | using Microsoft.EntityFrameworkCore.Storage.ValueConversion; 8 | 9 | namespace JwtAuthRefreshTokenSampleAPI.Migrations 10 | { 11 | [DbContext(typeof(ApplicationDbContext))] 12 | partial class ApplicationDbContextModelSnapshot : ModelSnapshot 13 | { 14 | protected override void BuildModel(ModelBuilder modelBuilder) 15 | { 16 | #pragma warning disable 612, 618 17 | modelBuilder 18 | .HasAnnotation("ProductVersion", "3.1.1") 19 | .HasAnnotation("Relational:MaxIdentifierLength", 128) 20 | .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); 21 | 22 | modelBuilder.Entity("JwtAuthSampleAPI.Data.ApplicationUser", b => 23 | { 24 | b.Property("Id") 25 | .HasColumnType("nvarchar(450)"); 26 | 27 | b.Property("AccessFailedCount") 28 | .HasColumnType("int"); 29 | 30 | b.Property("ConcurrencyStamp") 31 | .IsConcurrencyToken() 32 | .HasColumnType("nvarchar(max)"); 33 | 34 | b.Property("Email") 35 | .HasColumnType("nvarchar(256)") 36 | .HasMaxLength(256); 37 | 38 | b.Property("EmailConfirmed") 39 | .HasColumnType("bit"); 40 | 41 | b.Property("LockoutEnabled") 42 | .HasColumnType("bit"); 43 | 44 | b.Property("LockoutEnd") 45 | .HasColumnType("datetimeoffset"); 46 | 47 | b.Property("NormalizedEmail") 48 | .HasColumnType("nvarchar(256)") 49 | .HasMaxLength(256); 50 | 51 | b.Property("NormalizedUserName") 52 | .HasColumnType("nvarchar(256)") 53 | .HasMaxLength(256); 54 | 55 | b.Property("PasswordHash") 56 | .HasColumnType("nvarchar(max)"); 57 | 58 | b.Property("PhoneNumber") 59 | .HasColumnType("nvarchar(max)"); 60 | 61 | b.Property("PhoneNumberConfirmed") 62 | .HasColumnType("bit"); 63 | 64 | b.Property("SecurityStamp") 65 | .HasColumnType("nvarchar(max)"); 66 | 67 | b.Property("TwoFactorEnabled") 68 | .HasColumnType("bit"); 69 | 70 | b.Property("UserName") 71 | .HasColumnType("nvarchar(256)") 72 | .HasMaxLength(256); 73 | 74 | b.HasKey("Id"); 75 | 76 | b.HasIndex("NormalizedEmail") 77 | .HasName("EmailIndex"); 78 | 79 | b.HasIndex("NormalizedUserName") 80 | .IsUnique() 81 | .HasName("UserNameIndex") 82 | .HasFilter("[NormalizedUserName] IS NOT NULL"); 83 | 84 | b.ToTable("AspNetUsers"); 85 | }); 86 | 87 | modelBuilder.Entity("JwtAuthSampleAPI.Data.RefreshToken", b => 88 | { 89 | b.Property("Id") 90 | .ValueGeneratedOnAdd() 91 | .HasColumnType("int") 92 | .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); 93 | 94 | b.Property("ApplicationUserId") 95 | .HasColumnType("nvarchar(450)"); 96 | 97 | b.Property("CreatedByIp") 98 | .HasColumnType("nvarchar(max)"); 99 | 100 | b.Property("CreatedOn") 101 | .HasColumnType("datetime2"); 102 | 103 | b.Property("ExpiryOn") 104 | .HasColumnType("datetime2"); 105 | 106 | b.Property("RevokedByIp") 107 | .HasColumnType("nvarchar(max)"); 108 | 109 | b.Property("RevokedOn") 110 | .HasColumnType("datetime2"); 111 | 112 | b.Property("Token") 113 | .HasColumnType("nvarchar(max)"); 114 | 115 | b.Property("UserId") 116 | .HasColumnType("nvarchar(max)"); 117 | 118 | b.HasKey("Id"); 119 | 120 | b.HasIndex("ApplicationUserId"); 121 | 122 | b.ToTable("RefreshToken"); 123 | }); 124 | 125 | modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRole", b => 126 | { 127 | b.Property("Id") 128 | .HasColumnType("nvarchar(450)"); 129 | 130 | b.Property("ConcurrencyStamp") 131 | .IsConcurrencyToken() 132 | .HasColumnType("nvarchar(max)"); 133 | 134 | b.Property("Name") 135 | .HasColumnType("nvarchar(256)") 136 | .HasMaxLength(256); 137 | 138 | b.Property("NormalizedName") 139 | .HasColumnType("nvarchar(256)") 140 | .HasMaxLength(256); 141 | 142 | b.HasKey("Id"); 143 | 144 | b.HasIndex("NormalizedName") 145 | .IsUnique() 146 | .HasName("RoleNameIndex") 147 | .HasFilter("[NormalizedName] IS NOT NULL"); 148 | 149 | b.ToTable("AspNetRoles"); 150 | }); 151 | 152 | modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => 153 | { 154 | b.Property("Id") 155 | .ValueGeneratedOnAdd() 156 | .HasColumnType("int") 157 | .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); 158 | 159 | b.Property("ClaimType") 160 | .HasColumnType("nvarchar(max)"); 161 | 162 | b.Property("ClaimValue") 163 | .HasColumnType("nvarchar(max)"); 164 | 165 | b.Property("RoleId") 166 | .IsRequired() 167 | .HasColumnType("nvarchar(450)"); 168 | 169 | b.HasKey("Id"); 170 | 171 | b.HasIndex("RoleId"); 172 | 173 | b.ToTable("AspNetRoleClaims"); 174 | }); 175 | 176 | modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => 177 | { 178 | b.Property("Id") 179 | .ValueGeneratedOnAdd() 180 | .HasColumnType("int") 181 | .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); 182 | 183 | b.Property("ClaimType") 184 | .HasColumnType("nvarchar(max)"); 185 | 186 | b.Property("ClaimValue") 187 | .HasColumnType("nvarchar(max)"); 188 | 189 | b.Property("UserId") 190 | .IsRequired() 191 | .HasColumnType("nvarchar(450)"); 192 | 193 | b.HasKey("Id"); 194 | 195 | b.HasIndex("UserId"); 196 | 197 | b.ToTable("AspNetUserClaims"); 198 | }); 199 | 200 | modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => 201 | { 202 | b.Property("LoginProvider") 203 | .HasColumnType("nvarchar(450)"); 204 | 205 | b.Property("ProviderKey") 206 | .HasColumnType("nvarchar(450)"); 207 | 208 | b.Property("ProviderDisplayName") 209 | .HasColumnType("nvarchar(max)"); 210 | 211 | b.Property("UserId") 212 | .IsRequired() 213 | .HasColumnType("nvarchar(450)"); 214 | 215 | b.HasKey("LoginProvider", "ProviderKey"); 216 | 217 | b.HasIndex("UserId"); 218 | 219 | b.ToTable("AspNetUserLogins"); 220 | }); 221 | 222 | modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => 223 | { 224 | b.Property("UserId") 225 | .HasColumnType("nvarchar(450)"); 226 | 227 | b.Property("RoleId") 228 | .HasColumnType("nvarchar(450)"); 229 | 230 | b.HasKey("UserId", "RoleId"); 231 | 232 | b.HasIndex("RoleId"); 233 | 234 | b.ToTable("AspNetUserRoles"); 235 | }); 236 | 237 | modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => 238 | { 239 | b.Property("UserId") 240 | .HasColumnType("nvarchar(450)"); 241 | 242 | b.Property("LoginProvider") 243 | .HasColumnType("nvarchar(450)"); 244 | 245 | b.Property("Name") 246 | .HasColumnType("nvarchar(450)"); 247 | 248 | b.Property("Value") 249 | .HasColumnType("nvarchar(max)"); 250 | 251 | b.HasKey("UserId", "LoginProvider", "Name"); 252 | 253 | b.ToTable("AspNetUserTokens"); 254 | }); 255 | 256 | modelBuilder.Entity("JwtAuthSampleAPI.Data.RefreshToken", b => 257 | { 258 | b.HasOne("JwtAuthSampleAPI.Data.ApplicationUser", null) 259 | .WithMany("RefreshTokens") 260 | .HasForeignKey("ApplicationUserId"); 261 | }); 262 | 263 | modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => 264 | { 265 | b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) 266 | .WithMany() 267 | .HasForeignKey("RoleId") 268 | .OnDelete(DeleteBehavior.Cascade) 269 | .IsRequired(); 270 | }); 271 | 272 | modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => 273 | { 274 | b.HasOne("JwtAuthSampleAPI.Data.ApplicationUser", null) 275 | .WithMany() 276 | .HasForeignKey("UserId") 277 | .OnDelete(DeleteBehavior.Cascade) 278 | .IsRequired(); 279 | }); 280 | 281 | modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => 282 | { 283 | b.HasOne("JwtAuthSampleAPI.Data.ApplicationUser", null) 284 | .WithMany() 285 | .HasForeignKey("UserId") 286 | .OnDelete(DeleteBehavior.Cascade) 287 | .IsRequired(); 288 | }); 289 | 290 | modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => 291 | { 292 | b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) 293 | .WithMany() 294 | .HasForeignKey("RoleId") 295 | .OnDelete(DeleteBehavior.Cascade) 296 | .IsRequired(); 297 | 298 | b.HasOne("JwtAuthSampleAPI.Data.ApplicationUser", null) 299 | .WithMany() 300 | .HasForeignKey("UserId") 301 | .OnDelete(DeleteBehavior.Cascade) 302 | .IsRequired(); 303 | }); 304 | 305 | modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => 306 | { 307 | b.HasOne("JwtAuthSampleAPI.Data.ApplicationUser", null) 308 | .WithMany() 309 | .HasForeignKey("UserId") 310 | .OnDelete(DeleteBehavior.Cascade) 311 | .IsRequired(); 312 | }); 313 | #pragma warning restore 612, 618 314 | } 315 | } 316 | } 317 | -------------------------------------------------------------------------------- /RefreshJwtAuthSample/JwtAuthSampleAPI/Models/LoginCredentials.cs: -------------------------------------------------------------------------------- 1 | namespace JwtAuthRefreshTokenSampleAPI.Models 2 | { 3 | public class LoginCredentials 4 | { 5 | public string Username { get; set; } 6 | 7 | public string Password { get; set; } 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /RefreshJwtAuthSample/JwtAuthSampleAPI/Models/UserDetails.cs: -------------------------------------------------------------------------------- 1 | using System.ComponentModel.DataAnnotations; 2 | 3 | namespace JwtAuthRefreshTokenSampleAPI.Models 4 | { 5 | public class UserDetails 6 | { 7 | [Required] 8 | public string UserName { get; set; } 9 | 10 | [Required] 11 | public string Password { get; set; } 12 | 13 | [Required] 14 | public string Email { get; set; } 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /RefreshJwtAuthSample/JwtAuthSampleAPI/Models/WeatherForecast.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace JwtAuthRefreshTokenSampleAPI.Models 4 | { 5 | public class WeatherForecast 6 | { 7 | public DateTime Date { get; set; } 8 | 9 | public int TemperatureC { get; set; } 10 | 11 | public int TemperatureF => 32 + (int)(TemperatureC / 0.5556); 12 | 13 | public string Summary { get; set; } 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /RefreshJwtAuthSample/JwtAuthSampleAPI/Program.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Hosting; 2 | using Microsoft.Extensions.Hosting; 3 | 4 | namespace JwtAuthRefreshTokenSampleAPI 5 | { 6 | public class Program 7 | { 8 | public static void Main(string[] args) 9 | { 10 | CreateHostBuilder(args).Build().Run(); 11 | } 12 | 13 | public static IHostBuilder CreateHostBuilder(string[] args) => 14 | Host.CreateDefaultBuilder(args) 15 | .ConfigureWebHostDefaults(webBuilder => 16 | { 17 | webBuilder.UseStartup(); 18 | }); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /RefreshJwtAuthSample/JwtAuthSampleAPI/Properties/launchSettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "http://json.schemastore.org/launchsettings.json", 3 | "iisSettings": { 4 | "windowsAuthentication": false, 5 | "anonymousAuthentication": true, 6 | "iisExpress": { 7 | "applicationUrl": "http://localhost:61610", 8 | "sslPort": 44322 9 | } 10 | }, 11 | "profiles": { 12 | "IIS Express": { 13 | "commandName": "IISExpress", 14 | "launchBrowser": true, 15 | "launchUrl": "weatherforecast", 16 | "environmentVariables": { 17 | "ASPNETCORE_ENVIRONMENT": "Development" 18 | } 19 | }, 20 | "CookieAuthSampleAPI": { 21 | "commandName": "Project", 22 | "launchBrowser": true, 23 | "launchUrl": "weatherforecast", 24 | "applicationUrl": "https://localhost:5001;http://localhost:5000", 25 | "environmentVariables": { 26 | "ASPNETCORE_ENVIRONMENT": "Development" 27 | } 28 | } 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /RefreshJwtAuthSample/JwtAuthSampleAPI/Startup.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Text; 3 | using JwtAuthRefreshTokenSampleAPI.Configuration; 4 | using JwtAuthRefreshTokenSampleAPI.Data; 5 | using Microsoft.AspNetCore.Authentication.JwtBearer; 6 | using Microsoft.AspNetCore.Builder; 7 | using Microsoft.AspNetCore.Hosting; 8 | using Microsoft.AspNetCore.Identity; 9 | using Microsoft.EntityFrameworkCore; 10 | using Microsoft.Extensions.Configuration; 11 | using Microsoft.Extensions.DependencyInjection; 12 | using Microsoft.Extensions.Hosting; 13 | using Microsoft.IdentityModel.Tokens; 14 | 15 | namespace JwtAuthRefreshTokenSampleAPI 16 | { 17 | public class Startup 18 | { 19 | public Startup(IConfiguration configuration) 20 | { 21 | Configuration = configuration; 22 | } 23 | 24 | public IConfiguration Configuration { get; } 25 | 26 | // This method gets called by the runtime. Use this method to add services to the container. 27 | public void ConfigureServices(IServiceCollection services) 28 | { 29 | services.AddCors(); 30 | services.AddControllers(); 31 | 32 | services.AddDbContext(options => 33 | options.UseSqlServer(Configuration.GetConnectionString("SqlConnection"))); 34 | 35 | services.AddIdentity(options => options.SignIn.RequireConfirmedAccount = true) 36 | .AddEntityFrameworkStores(); 37 | 38 | // configure strongly typed settings objects 39 | var jwtSection = Configuration.GetSection("JwtBearerTokenSettings"); 40 | services.Configure(jwtSection); 41 | var jwtBearerTokenSettings = jwtSection.Get(); 42 | var key = Encoding.ASCII.GetBytes(jwtBearerTokenSettings.SecretKey); 43 | 44 | services.AddAuthentication(options => 45 | { 46 | options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; 47 | options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; 48 | }) 49 | .AddJwtBearer(options => 50 | { 51 | options.RequireHttpsMetadata = false; 52 | options.SaveToken = true; 53 | options.TokenValidationParameters = new TokenValidationParameters() 54 | { 55 | ValidateIssuer = true, 56 | ValidIssuer = jwtBearerTokenSettings.Issuer, 57 | ValidateAudience = true, 58 | ValidAudience = jwtBearerTokenSettings.Audience, 59 | ValidateIssuerSigningKey = true, 60 | IssuerSigningKey = new SymmetricSecurityKey(key), 61 | ValidateLifetime = true, 62 | ClockSkew = TimeSpan.Zero // To immediately reject the access token 63 | }; 64 | }); 65 | } 66 | 67 | // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. 68 | public void Configure(IApplicationBuilder app, IWebHostEnvironment env) 69 | { 70 | app.UseCors(x => x 71 | .AllowAnyOrigin() 72 | .AllowAnyMethod() 73 | .AllowAnyHeader()); 74 | 75 | if (env.IsDevelopment()) 76 | { 77 | app.UseDeveloperExceptionPage(); 78 | } 79 | 80 | app.UseHttpsRedirection(); 81 | app.UseRouting(); 82 | app.UseAuthentication(); 83 | app.UseAuthorization(); 84 | 85 | app.UseEndpoints(endpoints => 86 | { 87 | endpoints.MapControllers(); 88 | }); 89 | } 90 | } 91 | } 92 | -------------------------------------------------------------------------------- /RefreshJwtAuthSample/JwtAuthSampleAPI/appsettings.Development.json: -------------------------------------------------------------------------------- 1 | { 2 | "Logging": { 3 | "LogLevel": { 4 | "Default": "Information", 5 | "Microsoft": "Warning", 6 | "Microsoft.Hosting.Lifetime": "Information" 7 | } 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /RefreshJwtAuthSample/JwtAuthSampleAPI/appsettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "JwtBearerTokenSettings": { 3 | "SecretKey": "ThisIsSomeSampleSymmetricEncryptionKey", 4 | "Audience": "https://localhost:44322/", 5 | "Issuer": "https://localhost:44322/", 6 | "ExpiryTimeInSeconds": 60, 7 | "RefreshTokenSecret": "ThisIsRefreshTokenKey", 8 | "RefreshTokenExpiryInDays": 7 9 | }, 10 | "Logging": { 11 | "LogLevel": { 12 | "Default": "Information", 13 | "Microsoft": "Warning", 14 | "Microsoft.Hosting.Lifetime": "Information" 15 | } 16 | }, 17 | 18 | "ConnectionStrings": { 19 | "SqlConnection": "Server=(localdb)\\MSSQLLocalDB;Initial Catalog=MyAppDb; Integrated Security=true;" 20 | }, 21 | 22 | "AllowedHosts": "*" 23 | } 24 | -------------------------------------------------------------------------------- /RefreshJwtAuthSample/Postman-Collection/refresh-token-aspnetcore-sample-postman-setup.json: -------------------------------------------------------------------------------- 1 | { 2 | "info": { 3 | "_postman_id": "60255ce2-ab95-426f-9bcc-6a75d849c95e", 4 | "name": "Jwt Auth Sample", 5 | "schema": "https://schema.getpostman.com/json/collection/v2.1.0/collection.json" 6 | }, 7 | "item": [ 8 | { 9 | "name": "User Registration", 10 | "request": { 11 | "method": "POST", 12 | "header": [ 13 | { 14 | "key": "Accept", 15 | "value": "application/json", 16 | "type": "text" 17 | }, 18 | { 19 | "key": "Content-Type", 20 | "value": "application/json", 21 | "type": "text" 22 | } 23 | ], 24 | "body": { 25 | "mode": "raw", 26 | "raw": "{\n\t\"username\": \"test\",\n\t\"password\": \"Test@12345\",\n\t\"email\": \"abc@abc.com\"\n}" 27 | }, 28 | "url": { 29 | "raw": "https://localhost:44322/api/auth/register", 30 | "protocol": "https", 31 | "host": [ 32 | "localhost" 33 | ], 34 | "port": "44322", 35 | "path": [ 36 | "api", 37 | "auth", 38 | "register" 39 | ], 40 | "query": [ 41 | { 42 | "key": "username", 43 | "value": "test", 44 | "disabled": true 45 | }, 46 | { 47 | "key": "password", 48 | "value": "testpassword", 49 | "disabled": true 50 | } 51 | ] 52 | } 53 | }, 54 | "response": [] 55 | }, 56 | { 57 | "name": "Login", 58 | "request": { 59 | "method": "POST", 60 | "header": [ 61 | { 62 | "key": "Accept", 63 | "value": "application/json", 64 | "type": "text" 65 | }, 66 | { 67 | "key": "Content-Type", 68 | "value": "application/json", 69 | "type": "text" 70 | } 71 | ], 72 | "body": { 73 | "mode": "raw", 74 | "raw": "{\n\t\"username\": \"test\",\n\t\"password\": \"Test@12345\"\n}" 75 | }, 76 | "url": { 77 | "raw": "https://localhost:44322/api/auth/login", 78 | "protocol": "https", 79 | "host": [ 80 | "localhost" 81 | ], 82 | "port": "44322", 83 | "path": [ 84 | "api", 85 | "auth", 86 | "login" 87 | ] 88 | }, 89 | "description": "Login to get the cookie" 90 | }, 91 | "response": [] 92 | }, 93 | { 94 | "name": "Weather Forecast", 95 | "protocolProfileBehavior": { 96 | "disableBodyPruning": true 97 | }, 98 | "request": { 99 | "auth": { 100 | "type": "noauth" 101 | }, 102 | "method": "GET", 103 | "header": [ 104 | { 105 | "key": "Accept", 106 | "value": "application/json", 107 | "description": "\n", 108 | "type": "text" 109 | }, 110 | { 111 | "key": "Content-Type", 112 | "value": "application/json", 113 | "type": "text" 114 | }, 115 | { 116 | "key": "Authorization", 117 | "value": "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1bmlxdWVfbmFtZSI6InRlc3R1c2VyIiwiZW1haWwiOiJ0ZXN0QHRlc3QuY29tIiwibmJmIjoxNjA3MTgxMjI5LCJleHAiOjE2MDcxODEyODksImlhdCI6MTYwNzE4MTIyOSwiaXNzIjoiaHR0cHM6Ly9sb2NhbGhvc3Q6NDQzMjIvIiwiYXVkIjoiaHR0cHM6Ly9sb2NhbGhvc3Q6NDQzMjIvIn0.VlcfZXE1RHzZkStXjL_2htNea0GhFd-wHAVwavt_CLY", 118 | "type": "text" 119 | } 120 | ], 121 | "body": { 122 | "mode": "raw", 123 | "raw": "" 124 | }, 125 | "url": { 126 | "raw": "https://localhost:44322/api/weatherforecast?key=value", 127 | "protocol": "https", 128 | "host": [ 129 | "localhost" 130 | ], 131 | "port": "44322", 132 | "path": [ 133 | "api", 134 | "weatherforecast" 135 | ], 136 | "query": [ 137 | { 138 | "key": "key", 139 | "value": "value" 140 | } 141 | ] 142 | } 143 | }, 144 | "response": [] 145 | }, 146 | { 147 | "name": "Logout", 148 | "request": { 149 | "method": "POST", 150 | "header": [ 151 | { 152 | "key": "Accept", 153 | "value": "application/json", 154 | "type": "text" 155 | }, 156 | { 157 | "key": "Content-Type", 158 | "value": "application/json", 159 | "type": "text" 160 | } 161 | ], 162 | "body": { 163 | "mode": "raw", 164 | "raw": "{\n\t\"username\": \"test\",\n\t\"password\": \"Test@12345\"\n}" 165 | }, 166 | "url": { 167 | "raw": "https://localhost:44322/api/auth/login", 168 | "protocol": "https", 169 | "host": [ 170 | "localhost" 171 | ], 172 | "port": "44322", 173 | "path": [ 174 | "api", 175 | "auth", 176 | "login" 177 | ] 178 | }, 179 | "description": "Login to get the cookie" 180 | }, 181 | "response": [] 182 | }, 183 | { 184 | "name": "RefreshToken", 185 | "request": { 186 | "method": "POST", 187 | "header": [], 188 | "url": { 189 | "raw": "https://localhost:44322/api/auth/refreshtoken", 190 | "protocol": "https", 191 | "host": [ 192 | "localhost" 193 | ], 194 | "port": "44322", 195 | "path": [ 196 | "api", 197 | "auth", 198 | "refreshtoken" 199 | ] 200 | } 201 | }, 202 | "response": [] 203 | }, 204 | { 205 | "name": "RevokeToken", 206 | "request": { 207 | "method": "POST", 208 | "header": [], 209 | "url": { 210 | "raw": "https://localhost:44322/api/auth/revoketoken", 211 | "protocol": "https", 212 | "host": [ 213 | "localhost" 214 | ], 215 | "port": "44322", 216 | "path": [ 217 | "api", 218 | "auth", 219 | "revoketoken" 220 | ] 221 | } 222 | }, 223 | "response": [] 224 | } 225 | ], 226 | "protocolProfileBehavior": {} 227 | } -------------------------------------------------------------------------------- /RefreshJwtAuthSample/RefreshJwtAuthSampleAPI.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio Version 16 4 | VisualStudioVersion = 16.0.29613.14 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Postman-Collection", "Postman-Collection", "{288B75D6-78DF-4F8A-821B-FE250A445997}" 7 | ProjectSection(SolutionItems) = preProject 8 | Postman-Collection\refresh-token-aspnetcore-sample-postman-setup.json = Postman-Collection\refresh-token-aspnetcore-sample-postman-setup.json 9 | EndProjectSection 10 | EndProject 11 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "JwtAuthRefreshTokenSampleAPI", "JwtAuthSampleAPI\JwtAuthRefreshTokenSampleAPI.csproj", "{57E8F9AB-42FF-448B-8673-3888EC00934D}" 12 | EndProject 13 | Global 14 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 15 | Debug|Any CPU = Debug|Any CPU 16 | Release|Any CPU = Release|Any CPU 17 | EndGlobalSection 18 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 19 | {57E8F9AB-42FF-448B-8673-3888EC00934D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 20 | {57E8F9AB-42FF-448B-8673-3888EC00934D}.Debug|Any CPU.Build.0 = Debug|Any CPU 21 | {57E8F9AB-42FF-448B-8673-3888EC00934D}.Release|Any CPU.ActiveCfg = Release|Any CPU 22 | {57E8F9AB-42FF-448B-8673-3888EC00934D}.Release|Any CPU.Build.0 = Release|Any CPU 23 | EndGlobalSection 24 | GlobalSection(SolutionProperties) = preSolution 25 | HideSolutionNode = FALSE 26 | EndGlobalSection 27 | GlobalSection(ExtensibilityGlobals) = postSolution 28 | SolutionGuid = {D3545E52-87EF-46B9-A4C5-7BABF1053564} 29 | EndGlobalSection 30 | EndGlobal 31 | --------------------------------------------------------------------------------