├── .editorconfig ├── .gitignore ├── ApiProjectTemplates.sln ├── Directory.Build.props ├── Directory.Packages.props ├── LICENSE ├── README.md ├── api_templates ├── APIProjectTests │ ├── APIEndpointsProjectTests.csproj │ ├── ControllerUnitTests.cs │ ├── Endpoints │ │ ├── Delete_Endpoint.cs │ │ ├── GetById_Endpoint.cs │ │ ├── GetById_EndpointAllInOne.cs │ │ ├── JsonOptionConstants.cs │ │ ├── List_Endpoint.cs │ │ └── Routes.cs │ ├── Swagger.cs │ ├── WebApiApplication.cs │ ├── XUnitLogger.cs │ ├── XUnitLoggerProvider.cs │ ├── appsettings.Development.json │ └── appsettings.json ├── ApiBestPractices.Endpoints │ ├── ApiBestPractices.Endpoints.csproj │ ├── ApiBestPractices.Endpoints.xml │ ├── AuthExtensions.cs │ ├── AutoMapping.cs │ ├── DataConsistencyWorker.cs │ ├── Endpoints │ │ ├── Account │ │ │ ├── Login.LoginUserCommand.cs │ │ │ ├── Login.TokenResponse.cs │ │ │ ├── Login.cs │ │ │ ├── Register.RegisterUserCommand.cs │ │ │ └── Register.cs │ │ └── Authors │ │ │ ├── Create.CreateAuthorCommand.cs │ │ │ ├── Create.CreatedAuthorResult.cs │ │ │ ├── Create.cs │ │ │ ├── Delete.cs │ │ │ ├── Get.AuthorDto.cs │ │ │ ├── Get.cs │ │ │ ├── List.AuthorListResult.cs │ │ │ ├── List.cs │ │ │ ├── Patch.PatchAuthorCommand.cs │ │ │ ├── Patch.PatchedAuthorResult.cs │ │ │ ├── Patch.cs │ │ │ ├── Update.UpdateAuthorCommand.cs │ │ │ ├── Update.UpdatedAuthorResult.cs │ │ │ └── Update.cs │ ├── Program.cs │ ├── Properties │ │ └── launchSettings.json │ ├── appsettings.Development.json │ ├── appsettings.Testing.json │ └── appsettings.json ├── BackendData │ ├── BackendData.csproj │ ├── DataAccess │ │ ├── AppDbContext.cs │ │ ├── Config │ │ │ ├── AuthorConfig.cs │ │ │ ├── ConfigConstants.cs │ │ │ └── UserConfig.cs │ │ ├── EfRepository.cs │ │ └── SeedData.cs │ ├── DomainModel │ │ ├── Author.cs │ │ ├── BaseEntity.cs │ │ ├── IAsyncRepository.cs │ │ ├── TwitterHelpers.cs │ │ └── User.cs │ ├── Migrations │ │ ├── 20220717191514_AddUsers.Designer.cs │ │ ├── 20220717191514_AddUsers.cs │ │ └── AppDbContextModelSnapshot.cs │ ├── Security │ │ ├── AccessToken.cs │ │ ├── IPasswordHasher.cs │ │ ├── ITokenFactory.cs │ │ ├── JsonWebToken.cs │ │ ├── PasswordHasher.cs │ │ ├── SigningConfigurations.cs │ │ ├── TokenFactory.cs │ │ └── TokenOptions.cs │ ├── Services │ │ ├── AuthenticationService.cs │ │ └── IAuthenticationService.cs │ └── database.sqlite ├── controllers │ ├── ApiModels │ │ ├── AuthorDto.cs │ │ └── BookDto.cs │ ├── Controllers │ │ ├── AuthorsController.cs │ │ ├── AuthorsUsingMediatrController.cs │ │ ├── AuthorsUsingMediatrFromBaseController.cs │ │ ├── AuthorsUsingServiceController.cs │ │ ├── DemoController.cs │ │ └── HomeController.cs │ ├── Handlers │ │ └── CreateAuthorHandler.cs │ ├── Interfaces │ │ └── IAuthorService.cs │ ├── Program.cs │ ├── Properties │ │ └── launchSettings.json │ ├── Services │ │ └── AuthorService.cs │ ├── appsettings.Development.json │ ├── appsettings.json │ ├── controllers.csproj │ ├── database.sqlite-shm │ └── database.sqlite-wal ├── fastendpoints │ ├── Authors │ │ └── Create.cs │ ├── FastEndpointsAPI.csproj │ ├── Program.cs │ ├── Properties │ │ └── launchSettings.json │ ├── appsettings.Development.json │ └── appsettings.json └── minimal │ ├── .vscode │ ├── launch.json │ └── tasks.json │ ├── AuthorDto.cs │ ├── Authors │ ├── Create.cs │ └── UpdateAuthorExtension.cs │ ├── Program.cs │ ├── Properties │ └── launchSettings.json │ ├── appsettings.Development.json │ ├── appsettings.json │ └── minimal.csproj ├── demos.zip ├── demos2022.zip └── securing_apis ├── Imperative ├── Imperative.sln └── OwnerPermissions │ ├── Controllers │ └── DocumentController.cs │ ├── Data │ ├── DocumentRepository.cs │ └── IDocumentRepository.cs │ ├── Models │ └── Document.cs │ ├── OwnerPermissions.csproj │ ├── Program.cs │ ├── Properties │ └── launchSettings.json │ ├── Services │ ├── DocumentAuthorizationCrudHandler.cs │ ├── DocumentAuthorizationHandler.cs │ ├── Operations.cs │ └── SameAuthorRequirement.cs │ ├── appsettings.Development.json │ └── appsettings.json ├── JsBffSample ├── BackendApiHost │ ├── BackendApiHost.csproj │ ├── Program.cs │ ├── Properties │ │ └── launchSettings.json │ ├── Startup.cs │ └── ToDoController.cs ├── FrontendHost │ ├── FrontendHost.csproj │ ├── Program.cs │ ├── Properties │ │ └── launchSettings.json │ ├── Startup.cs │ ├── ToDoController.cs │ └── wwwroot │ │ ├── StyleSheet.css │ │ ├── favicon.ico │ │ ├── index.html │ │ ├── libs │ │ ├── bootstrap.bundle.min.js │ │ ├── bootstrap.bundle.min.js.map │ │ ├── bootstrap.min.css │ │ ├── bootstrap.min.css.map │ │ └── jquery-3.6.0.min.js │ │ ├── session.js │ │ └── todo.js └── JsBffSample.sln └── jwtapi ├── AuthExtensions.cs ├── Controllers ├── LoginController.cs ├── ProtectedController.cs ├── Resources │ ├── RefreshTokenResource.cs │ ├── RevokeTokenResource.cs │ ├── TokenResource.cs │ ├── UserCredentialsResource.cs │ └── UserResource.cs └── UsersController.cs ├── Core ├── Models │ ├── ApplicationRole.cs │ ├── Role.cs │ ├── User.cs │ └── UserRole.cs ├── Repositories │ ├── IUnitOfWork.cs │ └── IUserRepository.cs ├── Security │ ├── Hashing │ │ └── IPasswordHasher.cs │ └── Tokens │ │ ├── AccessToken.cs │ │ ├── ITokenHandler.cs │ │ ├── JsonWebToken.cs │ │ └── RefreshToken.cs └── Services │ ├── Communication │ ├── BaseResponse.cs │ ├── CreateUserResponse.cs │ └── TokenResponse.cs │ ├── IAuthenticationService.cs │ └── IUserService.cs ├── Extensions └── MiddlewareExtensions.cs ├── JWTAPI.csproj ├── JWTAPI.sln ├── Mapping ├── ModelToResourceProfile.cs └── ResourceToModelProfile.cs ├── Persistence ├── AppDbContext.cs ├── DatabaseSeed.cs ├── UnitOfWork.cs └── UserRepository.cs ├── Program.cs ├── Properties └── launchSettings.json ├── Security ├── Hashing │ └── PasswordHasher.cs └── Tokens │ ├── SigningConfigurations.cs │ ├── TokenHandler.cs │ └── TokenOptions.cs ├── Services ├── AuthenticationService.cs └── UserService.cs ├── Startup.cs ├── appsettings.Development.json └── appsettings.json /.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 | # TeamCity is a build add-in 131 | _TeamCity* 132 | 133 | # DotCover is a Code Coverage Tool 134 | *.dotCover 135 | 136 | # AxoCover is a Code Coverage Tool 137 | .axoCover/* 138 | !.axoCover/settings.json 139 | 140 | # Visual Studio code coverage results 141 | *.coverage 142 | *.coveragexml 143 | 144 | # NCrunch 145 | _NCrunch_* 146 | .*crunch*.local.xml 147 | nCrunchTemp_* 148 | 149 | # MightyMoose 150 | *.mm.* 151 | AutoTest.Net/ 152 | 153 | # Web workbench (sass) 154 | .sass-cache/ 155 | 156 | # Installshield output folder 157 | [Ee]xpress/ 158 | 159 | # DocProject is a documentation generator add-in 160 | DocProject/buildhelp/ 161 | DocProject/Help/*.HxT 162 | DocProject/Help/*.HxC 163 | DocProject/Help/*.hhc 164 | DocProject/Help/*.hhk 165 | DocProject/Help/*.hhp 166 | DocProject/Help/Html2 167 | DocProject/Help/html 168 | 169 | # Click-Once directory 170 | publish/ 171 | 172 | # Publish Web Output 173 | *.[Pp]ublish.xml 174 | *.azurePubxml 175 | # Note: Comment the next line if you want to checkin your web deploy settings, 176 | # but database connection strings (with potential passwords) will be unencrypted 177 | *.pubxml 178 | *.publishproj 179 | 180 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 181 | # checkin your Azure Web App publish settings, but sensitive information contained 182 | # in these scripts will be unencrypted 183 | PublishScripts/ 184 | 185 | # NuGet Packages 186 | *.nupkg 187 | # NuGet Symbol Packages 188 | *.snupkg 189 | # The packages folder can be ignored because of Package Restore 190 | **/[Pp]ackages/* 191 | # except build/, which is used as an MSBuild target. 192 | !**/[Pp]ackages/build/ 193 | # Uncomment if necessary however generally it will be regenerated when needed 194 | #!**/[Pp]ackages/repositories.config 195 | # NuGet v3's project.json files produces more ignorable files 196 | *.nuget.props 197 | *.nuget.targets 198 | 199 | # Microsoft Azure Build Output 200 | csx/ 201 | *.build.csdef 202 | 203 | # Microsoft Azure Emulator 204 | ecf/ 205 | rcf/ 206 | 207 | # Windows Store app package directories and files 208 | AppPackages/ 209 | BundleArtifacts/ 210 | Package.StoreAssociation.xml 211 | _pkginfo.txt 212 | *.appx 213 | *.appxbundle 214 | *.appxupload 215 | 216 | # Visual Studio cache files 217 | # files ending in .cache can be ignored 218 | *.[Cc]ache 219 | # but keep track of directories ending in .cache 220 | !?*.[Cc]ache/ 221 | 222 | # Others 223 | ClientBin/ 224 | ~$* 225 | *~ 226 | *.dbmdl 227 | *.dbproj.schemaview 228 | *.jfm 229 | *.pfx 230 | *.publishsettings 231 | orleans.codegen.cs 232 | 233 | # Including strong name files can present a security risk 234 | # (https://github.com/github/gitignore/pull/2483#issue-259490424) 235 | #*.snk 236 | 237 | # Since there are multiple workflows, uncomment next line to ignore bower_components 238 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 239 | #bower_components/ 240 | 241 | # RIA/Silverlight projects 242 | Generated_Code/ 243 | 244 | # Backup & report files from converting an old project file 245 | # to a newer Visual Studio version. Backup files are not needed, 246 | # because we have git ;-) 247 | _UpgradeReport_Files/ 248 | Backup*/ 249 | UpgradeLog*.XML 250 | UpgradeLog*.htm 251 | ServiceFabricBackup/ 252 | *.rptproj.bak 253 | 254 | # SQL Server files 255 | *.mdf 256 | *.ldf 257 | *.ndf 258 | 259 | # Business Intelligence projects 260 | *.rdl.data 261 | *.bim.layout 262 | *.bim_*.settings 263 | *.rptproj.rsuser 264 | *- [Bb]ackup.rdl 265 | *- [Bb]ackup ([0-9]).rdl 266 | *- [Bb]ackup ([0-9][0-9]).rdl 267 | 268 | # Microsoft Fakes 269 | FakesAssemblies/ 270 | 271 | # GhostDoc plugin setting file 272 | *.GhostDoc.xml 273 | 274 | # Node.js Tools for Visual Studio 275 | .ntvs_analysis.dat 276 | node_modules/ 277 | 278 | # Visual Studio 6 build log 279 | *.plg 280 | 281 | # Visual Studio 6 workspace options file 282 | *.opt 283 | 284 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.) 285 | *.vbw 286 | 287 | # Visual Studio LightSwitch build output 288 | **/*.HTMLClient/GeneratedArtifacts 289 | **/*.DesktopClient/GeneratedArtifacts 290 | **/*.DesktopClient/ModelManifest.xml 291 | **/*.Server/GeneratedArtifacts 292 | **/*.Server/ModelManifest.xml 293 | _Pvt_Extensions 294 | 295 | # Paket dependency manager 296 | .paket/paket.exe 297 | paket-files/ 298 | 299 | # FAKE - F# Make 300 | .fake/ 301 | 302 | # CodeRush personal settings 303 | .cr/personal 304 | 305 | # Python Tools for Visual Studio (PTVS) 306 | __pycache__/ 307 | *.pyc 308 | 309 | # Cake - Uncomment if you are using it 310 | # tools/** 311 | # !tools/packages.config 312 | 313 | # Tabs Studio 314 | *.tss 315 | 316 | # Telerik's JustMock configuration file 317 | *.jmconfig 318 | 319 | # BizTalk build output 320 | *.btp.cs 321 | *.btm.cs 322 | *.odx.cs 323 | *.xsd.cs 324 | 325 | # OpenCover UI analysis results 326 | OpenCover/ 327 | 328 | # Azure Stream Analytics local run output 329 | ASALocalRun/ 330 | 331 | # MSBuild Binary and Structured Log 332 | *.binlog 333 | 334 | # NVidia Nsight GPU debugger configuration file 335 | *.nvuser 336 | 337 | # MFractors (Xamarin productivity tool) working folder 338 | .mfractor/ 339 | 340 | # Local History for Visual Studio 341 | .localhistory/ 342 | 343 | # BeatPulse healthcheck temp database 344 | healthchecksdb 345 | 346 | # Backup folder for Package Reference Convert tool in Visual Studio 2017 347 | MigrationBackup/ 348 | 349 | # Ionide (cross platform F# VS Code tools) working folder 350 | .ionide/ 351 | /api_templates/minimal/database.sqlite 352 | /api_templates/ApiBestPractices.Endpoints/database.sqlite 353 | /api_templates/controllers/database.sqlite 354 | -------------------------------------------------------------------------------- /ApiProjectTemplates.sln: -------------------------------------------------------------------------------- 1 | 2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio Version 17 4 | VisualStudioVersion = 17.1.32319.34 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Data", "Data", "{DE8D8BA4-19B1-4079-8847-BB05E31DAB0A}" 7 | EndProject 8 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "_Solution Items", "_Solution Items", "{3DCCFC81-5742-499C-BFBE-6CFA21DB20BF}" 9 | ProjectSection(SolutionItems) = preProject 10 | .editorconfig = .editorconfig 11 | Directory.Build.props = Directory.Build.props 12 | Directory.Packages.props = Directory.Packages.props 13 | EndProjectSection 14 | EndProject 15 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "API Projects", "API Projects", "{BF524179-7DDB-4E90-8E23-8D738F60347C}" 16 | EndProject 17 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Tests", "Tests", "{8F4D3419-3DD8-4847-BC2A-2A8DC17ED8D5}" 18 | EndProject 19 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "controllers", "api_templates\controllers\controllers.csproj", "{598E8089-2F57-4E6A-B2E1-F5E594ECF887}" 20 | EndProject 21 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "FastEndpointsAPI", "api_templates\fastendpoints\FastEndpointsAPI.csproj", "{9450CEC4-A630-4B51-A007-E7CF602E20C5}" 22 | EndProject 23 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "minimal", "api_templates\minimal\minimal.csproj", "{2DCDBB44-38A9-4537-BDB2-6CAFA3A0D3AD}" 24 | EndProject 25 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "BackendData", "api_templates\BackendData\BackendData.csproj", "{00DE605E-ACE3-46E6-B5B3-C2D283DA3DAB}" 26 | EndProject 27 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "APIEndpointsProjectTests", "api_templates\APIProjectTests\APIEndpointsProjectTests.csproj", "{55920625-28C8-4C64-A281-C57C0F9A9336}" 28 | EndProject 29 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ApiBestPractices.Endpoints", "api_templates\ApiBestPractices.Endpoints\ApiBestPractices.Endpoints.csproj", "{5586351A-B0F3-4577-AFDB-1FDE50B8E03D}" 30 | EndProject 31 | Global 32 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 33 | Debug|Any CPU = Debug|Any CPU 34 | Release|Any CPU = Release|Any CPU 35 | EndGlobalSection 36 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 37 | {598E8089-2F57-4E6A-B2E1-F5E594ECF887}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 38 | {598E8089-2F57-4E6A-B2E1-F5E594ECF887}.Debug|Any CPU.Build.0 = Debug|Any CPU 39 | {598E8089-2F57-4E6A-B2E1-F5E594ECF887}.Release|Any CPU.ActiveCfg = Release|Any CPU 40 | {598E8089-2F57-4E6A-B2E1-F5E594ECF887}.Release|Any CPU.Build.0 = Release|Any CPU 41 | {9450CEC4-A630-4B51-A007-E7CF602E20C5}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 42 | {9450CEC4-A630-4B51-A007-E7CF602E20C5}.Debug|Any CPU.Build.0 = Debug|Any CPU 43 | {9450CEC4-A630-4B51-A007-E7CF602E20C5}.Release|Any CPU.ActiveCfg = Release|Any CPU 44 | {9450CEC4-A630-4B51-A007-E7CF602E20C5}.Release|Any CPU.Build.0 = Release|Any CPU 45 | {2DCDBB44-38A9-4537-BDB2-6CAFA3A0D3AD}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 46 | {2DCDBB44-38A9-4537-BDB2-6CAFA3A0D3AD}.Debug|Any CPU.Build.0 = Debug|Any CPU 47 | {2DCDBB44-38A9-4537-BDB2-6CAFA3A0D3AD}.Release|Any CPU.ActiveCfg = Release|Any CPU 48 | {2DCDBB44-38A9-4537-BDB2-6CAFA3A0D3AD}.Release|Any CPU.Build.0 = Release|Any CPU 49 | {00DE605E-ACE3-46E6-B5B3-C2D283DA3DAB}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 50 | {00DE605E-ACE3-46E6-B5B3-C2D283DA3DAB}.Debug|Any CPU.Build.0 = Debug|Any CPU 51 | {00DE605E-ACE3-46E6-B5B3-C2D283DA3DAB}.Release|Any CPU.ActiveCfg = Release|Any CPU 52 | {00DE605E-ACE3-46E6-B5B3-C2D283DA3DAB}.Release|Any CPU.Build.0 = Release|Any CPU 53 | {55920625-28C8-4C64-A281-C57C0F9A9336}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 54 | {55920625-28C8-4C64-A281-C57C0F9A9336}.Debug|Any CPU.Build.0 = Debug|Any CPU 55 | {55920625-28C8-4C64-A281-C57C0F9A9336}.Release|Any CPU.ActiveCfg = Release|Any CPU 56 | {55920625-28C8-4C64-A281-C57C0F9A9336}.Release|Any CPU.Build.0 = Release|Any CPU 57 | {5586351A-B0F3-4577-AFDB-1FDE50B8E03D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 58 | {5586351A-B0F3-4577-AFDB-1FDE50B8E03D}.Debug|Any CPU.Build.0 = Debug|Any CPU 59 | {5586351A-B0F3-4577-AFDB-1FDE50B8E03D}.Release|Any CPU.ActiveCfg = Release|Any CPU 60 | {5586351A-B0F3-4577-AFDB-1FDE50B8E03D}.Release|Any CPU.Build.0 = Release|Any CPU 61 | EndGlobalSection 62 | GlobalSection(SolutionProperties) = preSolution 63 | HideSolutionNode = FALSE 64 | EndGlobalSection 65 | GlobalSection(NestedProjects) = preSolution 66 | {598E8089-2F57-4E6A-B2E1-F5E594ECF887} = {BF524179-7DDB-4E90-8E23-8D738F60347C} 67 | {9450CEC4-A630-4B51-A007-E7CF602E20C5} = {BF524179-7DDB-4E90-8E23-8D738F60347C} 68 | {2DCDBB44-38A9-4537-BDB2-6CAFA3A0D3AD} = {BF524179-7DDB-4E90-8E23-8D738F60347C} 69 | {00DE605E-ACE3-46E6-B5B3-C2D283DA3DAB} = {DE8D8BA4-19B1-4079-8847-BB05E31DAB0A} 70 | {55920625-28C8-4C64-A281-C57C0F9A9336} = {8F4D3419-3DD8-4847-BC2A-2A8DC17ED8D5} 71 | {5586351A-B0F3-4577-AFDB-1FDE50B8E03D} = {BF524179-7DDB-4E90-8E23-8D738F60347C} 72 | EndGlobalSection 73 | GlobalSection(ExtensibilityGlobals) = postSolution 74 | SolutionGuid = {F3DAE36F-B1E7-40B6-B6A0-CBA0C3920CB1} 75 | EndGlobalSection 76 | EndGlobal 77 | -------------------------------------------------------------------------------- /Directory.Build.props: -------------------------------------------------------------------------------- 1 | 2 | 3 | true 4 | 5 | net8.0 6 | 7 | enable 8 | 9 | 10 | 1591 11 | 12 | -------------------------------------------------------------------------------- /Directory.Packages.props: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2022 Steve Smith 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 | -------------------------------------------------------------------------------- /api_templates/APIProjectTests/APIEndpointsProjectTests.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | net8.0 5 | enable 6 | 7 | false 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | PreserveNewest 18 | true 19 | PreserveNewest 20 | 21 | 22 | PreserveNewest 23 | true 24 | PreserveNewest 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | runtime; build; native; contentfiles; analyzers; buildtransitive 39 | all 40 | 41 | 42 | runtime; build; native; contentfiles; analyzers; buildtransitive 43 | all 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | -------------------------------------------------------------------------------- /api_templates/APIProjectTests/ControllerUnitTests.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using System.Threading; 3 | using System.Threading.Tasks; 4 | using BackendData; 5 | using controllers.ApiModels; 6 | using controllers.Controllers; 7 | using Microsoft.AspNetCore.Mvc; 8 | using Microsoft.Extensions.Logging; 9 | using Moq; 10 | using Xunit; 11 | 12 | namespace APIProjectTests; 13 | 14 | /// 15 | /// Don't do this - it doesn't test filters, routing, etc. 16 | /// 17 | public class ControllerUnitTests 18 | { 19 | [Fact] 20 | public async Task TestControllerAction() 21 | { 22 | var mockLogger = new Mock>(); 23 | var mockRepo = new Mock>(); 24 | mockRepo 25 | .Setup(c => c.ListAllAsync(It.IsAny())) 26 | .ReturnsAsync(new List()); 27 | var controller = new AuthorsController(mockLogger.Object, mockRepo.Object); 28 | 29 | var result = await controller.Index(CancellationToken.None); 30 | 31 | Assert.NotNull(result); 32 | Assert.IsType>>(result); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /api_templates/APIProjectTests/Endpoints/Delete_Endpoint.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Net; 3 | using System.Net.Http; 4 | using System.Text; 5 | using System.Text.Json; 6 | using System.Threading.Tasks; 7 | using ApiBestPractices.Endpoints.Endpoints.Account; 8 | using Microsoft.Extensions.Logging; 9 | using Xunit; 10 | using Xunit.Abstractions; 11 | 12 | namespace APIProjectTests.Endpoints; 13 | 14 | public class Delete_Endpoint 15 | { 16 | private readonly ITestOutputHelper _testOutputHelper; 17 | private readonly ILogger _logger; 18 | private readonly HttpClient _client; 19 | private static JsonSerializerOptions _serializerOptions = new JsonSerializerOptions 20 | { 21 | PropertyNamingPolicy = JsonNamingPolicy.CamelCase 22 | }; 23 | 24 | public Delete_Endpoint(ITestOutputHelper testOutputHelper) 25 | { 26 | _testOutputHelper = testOutputHelper; 27 | _logger = XUnitLogger.CreateLogger(_testOutputHelper); 28 | _client = new WebApiApplication(_testOutputHelper) 29 | .CreateClient(); // (new() { BaseAddress = new Uri("https://localhost")} ); 30 | } 31 | 32 | [Fact] 33 | public async Task Returns401GivenNoToken() 34 | { 35 | var result = await _client.DeleteAsync(Routes.Authors.Delete(1)); 36 | 37 | Assert.Equal(HttpStatusCode.Unauthorized, result.StatusCode); 38 | } 39 | 40 | [Fact] 41 | public async Task Returns204NotContentGivenValidAuthToken() 42 | { 43 | // create a new user then login, get a token, then delete the user 44 | 45 | var token = await GetAuthToken(); 46 | 47 | _client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", token); 48 | var result = await _client.DeleteAsync(Routes.Authors.Delete(1)); 49 | 50 | Assert.Equal(HttpStatusCode.NoContent, result.StatusCode); 51 | } 52 | 53 | 54 | // Option 1: Get a real token using the real API 55 | // Option 2: Build a fake token: https://medium.com/asos-techblog/testing-authorization-scenarios-in-asp-net-core-web-api-484bc95d5f6f 56 | private async Task GetAuthToken() 57 | { 58 | string testUserEmail = "test@test.com" + Guid.NewGuid().ToString(); 59 | const string testUserPassword = "123456"; 60 | 61 | await Register(testUserEmail, testUserPassword); 62 | 63 | return await LoginGetToken(testUserEmail, testUserPassword); 64 | } 65 | 66 | private async Task Register(string email, string password) 67 | { 68 | var registerCommand = new RegisterUserCommand { Email = email, Password = password }; 69 | var registerContent = new StringContent(JsonSerializer.Serialize(registerCommand, _serializerOptions), Encoding.UTF8, "application/json"); 70 | var response = await _client.PostAsync(Routes.Account.Register(), registerContent); 71 | response.EnsureSuccessStatusCode(); 72 | } 73 | 74 | private async Task LoginGetToken(string email, string password) 75 | { 76 | var loginCommand = new LoginUserCommand { Email = email, Password = password }; 77 | var loginJsonContent = new StringContent(JsonSerializer.Serialize(loginCommand, _serializerOptions), Encoding.UTF8, "application/json"); 78 | var loginResponse = await _client.PostAsync(Routes.Account.Login(), loginJsonContent); 79 | loginResponse.EnsureSuccessStatusCode(); 80 | 81 | var loginStringResult = await loginResponse.Content.ReadAsStringAsync(); 82 | var tokenResult = JsonSerializer.Deserialize(loginStringResult, _serializerOptions); 83 | 84 | return tokenResult.AccessToken.TokenString; 85 | } 86 | } 87 | -------------------------------------------------------------------------------- /api_templates/APIProjectTests/Endpoints/GetById_Endpoint.cs: -------------------------------------------------------------------------------- 1 | using System.Text.Json; 2 | using ApiBestPractices.Endpoints.Endpoints.Authors; 3 | using BackendData; 4 | using BackendData.DataAccess; 5 | using Microsoft.Extensions.Logging; 6 | using Xunit; 7 | using Xunit.Abstractions; 8 | using Ardalis.HttpClientTestExtensions; 9 | 10 | namespace APIProjectTests.Endpoints; 11 | 12 | public class GetById_Endpoint 13 | { 14 | private readonly ITestOutputHelper _testOutputHelper; 15 | private readonly ILogger _logger; 16 | private readonly HttpClient _client; 17 | private List Authors { get; set; } = new(); 18 | 19 | public GetById_Endpoint(ITestOutputHelper testOutputHelper) 20 | { 21 | _testOutputHelper = testOutputHelper; 22 | _logger = XUnitLogger.CreateLogger(_testOutputHelper); 23 | _client = new WebApiApplication(_testOutputHelper).CreateClient(); 24 | Authors = SeedData.Authors(); 25 | } 26 | 27 | [Fact] 28 | public async Task ReturnsSeededAuthorWithId1() 29 | { 30 | // Arrange (done in WebApiApplication) 31 | 32 | // Act 33 | var result = await GetAndDeserialize(Routes.Authors.Get(Authors.FirstOrDefault().Id)); 34 | 35 | // Assert 36 | Assert.NotNull(result); 37 | 38 | string expectedAuthorName = Authors.FirstOrDefault().Name; 39 | Assert.Equal(expectedAuthorName, result.Name); 40 | } 41 | 42 | [Fact] 43 | public async Task ReturnsSeededAuthorWithId1WithArdalisTestExtensions() 44 | { 45 | // Arrange (done in WebApiApplication) 46 | 47 | // Act 48 | var result = await _client.GetAndDeserializeAsync(Routes.Authors.Get(Authors.FirstOrDefault().Id)); 49 | 50 | // Assert 51 | Assert.NotNull(result); 52 | 53 | string expectedAuthorName = Authors.FirstOrDefault().Name; 54 | Assert.Equal(expectedAuthorName, result.Name); 55 | } 56 | 57 | [Fact] 58 | public async Task ReturnsNotFoundGivenInvalidId() 59 | { 60 | // Arrange 61 | int invalidId = -1; 62 | 63 | // Act 64 | await GetAndAssertNotFound(Routes.Authors.Get(invalidId)); 65 | } 66 | 67 | [Fact] 68 | public async Task ReturnsNotFoundGivenInvalidIdWithArdalisTestExtensions() 69 | { 70 | // Arrange 71 | int invalidId = -1; 72 | 73 | // Act and Assert 74 | await _client.GetAndEnsureNotFoundAsync(Routes.Authors.Get(invalidId)); 75 | } 76 | 77 | private async Task GetAndAssertNotFound(string route) 78 | { 79 | var response = await _client.GetAsync(route); 80 | 81 | // Assert 82 | Assert.Equal(System.Net.HttpStatusCode.NotFound, response.StatusCode); 83 | } 84 | 85 | private async Task GetAndDeserialize(string route) 86 | { 87 | var response = await _client.GetAsync(route); 88 | response.EnsureSuccessStatusCode(); 89 | var stringResult = await response.Content.ReadAsStringAsync(); 90 | _logger.LogInformation(stringResult); 91 | var result = JsonSerializer.Deserialize(stringResult, 92 | JsonOptionConstants.SerializerOptions); 93 | return result; 94 | } 95 | } 96 | -------------------------------------------------------------------------------- /api_templates/APIProjectTests/Endpoints/GetById_EndpointAllInOne.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Linq; 3 | using System.Text.Json; 4 | using System.Threading.Tasks; 5 | using ApiBestPractices.Endpoints.Endpoints.Authors; 6 | using BackendData.DataAccess; 7 | using Microsoft.AspNetCore.Hosting; 8 | using Microsoft.AspNetCore.Mvc.Testing; 9 | using Microsoft.EntityFrameworkCore; 10 | using Microsoft.Extensions.DependencyInjection; 11 | using Microsoft.Extensions.Logging; 12 | using Xunit; 13 | using Xunit.Abstractions; 14 | 15 | namespace APIProjectTests.Endpoints; 16 | 17 | // Do everything in the test method 18 | // Works, but results in a lot of duplication when you have more than one test 19 | public class GetById_EndpointAllInOne 20 | { 21 | private readonly ITestOutputHelper _testOutputHelper; 22 | private readonly ILogger _logger; 23 | private readonly int _testAuthorId = 1; 24 | 25 | public GetById_EndpointAllInOne(ITestOutputHelper testOutputHelper) 26 | { 27 | _testOutputHelper = testOutputHelper; 28 | _logger = XUnitLogger.CreateLogger(_testOutputHelper); 29 | } 30 | 31 | [Fact] 32 | public async Task ReturnsSeededAuthorWithId1() 33 | { 34 | // Arrange 35 | var application = new WebApplicationFactory() 36 | .WithWebHostBuilder(builder => 37 | { 38 | builder.UseEnvironment("Testing"); 39 | 40 | builder.ConfigureLogging(loggingBuilder => 41 | { 42 | loggingBuilder.Services.AddSingleton(serviceProvider => new XUnitLoggerProvider(_testOutputHelper)); 43 | }); 44 | 45 | builder.ConfigureServices(services => 46 | { 47 | var descriptor = services.SingleOrDefault( 48 | d => d.ServiceType == 49 | typeof(DbContextOptions)); 50 | 51 | services.Remove(descriptor); 52 | 53 | string dbName = "InMemoryDbForTesting" + Guid.NewGuid().ToString(); 54 | 55 | services.AddDbContext(options => 56 | { 57 | options.UseInMemoryDatabase(dbName); 58 | }); 59 | 60 | var serviceProvider = services.BuildServiceProvider(); 61 | 62 | using (var scope = serviceProvider.CreateScope()) 63 | using (var appContext = scope.ServiceProvider.GetRequiredService()) 64 | { 65 | try 66 | { 67 | // this will call the Seed method defined in AuthorConfig.cs in BackendData project 68 | appContext.Database.EnsureCreated(); 69 | } 70 | catch (Exception ex) 71 | { 72 | //Log errors or do anything you think is needed 73 | throw; 74 | } 75 | } 76 | }); 77 | }); 78 | 79 | var client = application.CreateClient(); 80 | 81 | // Act 82 | var response = await client.GetAsync(Routes.Authors.Get(_testAuthorId)); 83 | response.EnsureSuccessStatusCode(); 84 | var stringResult = await response.Content.ReadAsStringAsync(); 85 | _logger.LogInformation(stringResult); 86 | var result = JsonSerializer.Deserialize(stringResult, JsonOptionConstants.SerializerOptions); 87 | 88 | // Assert 89 | Assert.NotNull(result); 90 | Assert.Equal("Steve Smith", result.Name); 91 | } 92 | } 93 | -------------------------------------------------------------------------------- /api_templates/APIProjectTests/Endpoints/JsonOptionConstants.cs: -------------------------------------------------------------------------------- 1 | using System.Text.Json; 2 | 3 | namespace APIProjectTests; 4 | 5 | public static class JsonOptionConstants 6 | { 7 | public static JsonSerializerOptions SerializerOptions = new JsonSerializerOptions 8 | { 9 | PropertyNamingPolicy = JsonNamingPolicy.CamelCase, 10 | WriteIndented = true 11 | }; 12 | } 13 | -------------------------------------------------------------------------------- /api_templates/APIProjectTests/Endpoints/List_Endpoint.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using System.Linq; 3 | using System.Net; 4 | using System.Net.Http; 5 | using System.Text.Json; 6 | using System.Threading.Tasks; 7 | using Ardalis.HttpClientTestExtensions; 8 | using BackendData.DataAccess; 9 | using Microsoft.Extensions.Logging; 10 | using Xunit; 11 | using Xunit.Abstractions; 12 | 13 | namespace APIProjectTests.Endpoints; 14 | 15 | internal record AuthorListResult(int Id, string Name, string TwitterAlias); 16 | public class List_Endpoint 17 | { 18 | private readonly ITestOutputHelper _testOutputHelper; 19 | private readonly ILogger _logger; 20 | private readonly HttpClient _client; 21 | 22 | public List_Endpoint(ITestOutputHelper testOutputHelper) 23 | { 24 | _testOutputHelper = testOutputHelper; 25 | _logger = XUnitLogger.CreateLogger(_testOutputHelper); 26 | _client = new WebApiApplication(_testOutputHelper).CreateClient(); 27 | } 28 | 29 | [Fact] 30 | public async Task ReturnsSeededAuthors() 31 | { 32 | // Arrange (done in WebApiApplication) 33 | 34 | // Act 35 | var response = await _client.GetAsync("/Authors"); 36 | response.EnsureSuccessStatusCode(); 37 | Assert.Equal(HttpStatusCode.OK, response.StatusCode); 38 | var stringResult = await response.Content.ReadAsStringAsync(); 39 | _logger.LogInformation(stringResult); 40 | var result = JsonSerializer.Deserialize>(stringResult); 41 | 42 | // Assert 43 | Assert.NotNull(result); 44 | Assert.Equal(SeedData.Authors().Count, result.Count()); 45 | } 46 | 47 | [Fact] 48 | public async Task ReturnsSeededAuthorsRefactored() 49 | { 50 | var result = await _client.GetAndDeserializeAsync>(Routes.Authors.List()); 51 | 52 | Assert.NotNull(result); 53 | Assert.Equal(SeedData.Authors().Count, result.Count()); 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /api_templates/APIProjectTests/Endpoints/Routes.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace APIProjectTests; 4 | 5 | public static class Routes 6 | { 7 | private const string BaseRoute = ""; 8 | 9 | public static class Authors 10 | { 11 | private const string BaseAuthorsRoute = Routes.BaseRoute + "/authors"; 12 | 13 | public const string Create = BaseAuthorsRoute; 14 | 15 | public const string Update = BaseAuthorsRoute; 16 | 17 | public static string List() => BaseAuthorsRoute; 18 | 19 | public static string List(int perPage, int page) => $"{BaseAuthorsRoute}?perPage={perPage}&page={page}"; 20 | 21 | public static string Get(int id) => $"{BaseAuthorsRoute}/{id}"; 22 | 23 | public static string Delete(int id) => $"{BaseAuthorsRoute}/{id}"; 24 | } 25 | 26 | public static class Account 27 | { 28 | private const string BaseAccountRoute = Routes.BaseRoute + "/account"; 29 | 30 | public static string Register() => BaseAccountRoute + "/register"; 31 | 32 | internal static string? Login() => BaseAccountRoute + "/login"; 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /api_templates/APIProjectTests/Swagger.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Net; 3 | using Xunit.Abstractions; 4 | 5 | namespace APIProjectTests; 6 | 7 | public class Swagger 8 | { 9 | private readonly ITestOutputHelper _testOutputHelper; 10 | 11 | public Swagger(ITestOutputHelper testOutputHelper) 12 | { 13 | _testOutputHelper = testOutputHelper; 14 | } 15 | 16 | // [Fact] 17 | // public async Task SwaggerUI_Responds_OK_In_Development() 18 | // { 19 | // var logger = XUnitLogger.CreateLogger(_testOutputHelper); 20 | 21 | // await using var application = new WebApiApplication(_testOutputHelper); 22 | 23 | // var client = application.CreateClient(new() { BaseAddress = new Uri("https://localhost") }); 24 | //// _client = new WebApiApplication(_testOutputHelper).CreateClient(new() { BaseAddress = new Uri("https://localhost") }); 25 | 26 | // var response = await client.GetAsync("/index.html"); 27 | 28 | // logger.LogInformation($"URL: {response.RequestMessage.RequestUri.AbsoluteUri}"); 29 | 30 | // response.EnsureSuccessStatusCode(); 31 | // } 32 | 33 | 34 | } 35 | -------------------------------------------------------------------------------- /api_templates/APIProjectTests/WebApiApplication.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Linq; 3 | using BackendData.DataAccess; 4 | using Microsoft.AspNetCore.Mvc.Testing; 5 | using Microsoft.EntityFrameworkCore; 6 | using Microsoft.Extensions.DependencyInjection; 7 | using Microsoft.Extensions.Hosting; 8 | using Microsoft.Extensions.Logging; 9 | using Xunit.Abstractions; 10 | 11 | namespace APIProjectTests; 12 | 13 | public class WebApiApplication : WebApplicationFactory 14 | { 15 | private readonly ITestOutputHelper _testOutputHelper; 16 | 17 | public WebApiApplication(ITestOutputHelper testOutputHelper) 18 | { 19 | _testOutputHelper = testOutputHelper; 20 | } 21 | 22 | protected override IHost CreateHost(IHostBuilder builder) 23 | { 24 | builder.UseEnvironment("Testing"); 25 | 26 | builder.ConfigureLogging(loggingBuilder => 27 | { 28 | loggingBuilder.Services.AddSingleton(serviceProvider => new XUnitLoggerProvider(_testOutputHelper)); 29 | }); 30 | 31 | builder.ConfigureServices(services => 32 | { 33 | var descriptor = services.SingleOrDefault( 34 | d => d.ServiceType == 35 | typeof(DbContextOptions)); 36 | 37 | services.Remove(descriptor); 38 | 39 | string dbName = "InMemoryDbForTesting" + Guid.NewGuid().ToString(); 40 | 41 | services.AddDbContext(options => 42 | { 43 | options.UseInMemoryDatabase(dbName); 44 | }); 45 | 46 | // Create a new service provider. 47 | var serviceProvider = services.BuildServiceProvider(); 48 | 49 | using (var scope = serviceProvider.CreateScope()) 50 | using (var appContext = scope.ServiceProvider.GetRequiredService()) 51 | { 52 | try 53 | { 54 | appContext.Database.EnsureCreated(); 55 | } 56 | catch (Exception ex) 57 | { 58 | //Log errors or do anything you think is needed 59 | throw; 60 | } 61 | } 62 | }); 63 | 64 | return base.CreateHost(builder); 65 | } 66 | } 67 | -------------------------------------------------------------------------------- /api_templates/APIProjectTests/XUnitLogger.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Text; 3 | using Microsoft.Extensions.Logging; 4 | using Xunit.Abstractions; 5 | 6 | namespace APIProjectTests; 7 | 8 | internal sealed class XUnitLogger : XUnitLogger, ILogger 9 | { 10 | public XUnitLogger(ITestOutputHelper testOutputHelper, LoggerExternalScopeProvider scopeProvider) 11 | : base(testOutputHelper, scopeProvider, typeof(T).FullName) 12 | { 13 | } 14 | } 15 | 16 | internal class XUnitLogger : ILogger 17 | { 18 | private readonly ITestOutputHelper _testOutputHelper; 19 | private readonly string _categoryName; 20 | private readonly LoggerExternalScopeProvider _scopeProvider; 21 | 22 | public static ILogger CreateLogger(ITestOutputHelper testOutputHelper) => new XUnitLogger(testOutputHelper, new LoggerExternalScopeProvider(), ""); 23 | public static ILogger CreateLogger(ITestOutputHelper testOutputHelper) => new XUnitLogger(testOutputHelper, new LoggerExternalScopeProvider()); 24 | 25 | public XUnitLogger(ITestOutputHelper testOutputHelper, LoggerExternalScopeProvider scopeProvider, string categoryName) 26 | { 27 | _testOutputHelper = testOutputHelper; 28 | _scopeProvider = scopeProvider; 29 | _categoryName = categoryName; 30 | } 31 | 32 | public bool IsEnabled(LogLevel logLevel) => logLevel != LogLevel.None; 33 | 34 | public IDisposable BeginScope(TState state) => _scopeProvider.Push(state); 35 | 36 | public void Log(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func formatter) 37 | { 38 | var sb = new StringBuilder(); 39 | sb.Append(GetLogLevelString(logLevel)) 40 | .Append(" [").Append(_categoryName).Append("] ") 41 | .Append(formatter(state, exception)); 42 | 43 | if (exception != null) 44 | { 45 | sb.Append('\n').Append(exception); 46 | } 47 | 48 | // Append scopes 49 | _scopeProvider.ForEachScope((scope, state) => 50 | { 51 | state.Append("\n => "); 52 | state.Append(scope); 53 | }, sb); 54 | 55 | _testOutputHelper.WriteLine(sb.ToString()); 56 | } 57 | 58 | private static string GetLogLevelString(LogLevel logLevel) 59 | { 60 | return logLevel switch 61 | { 62 | LogLevel.Trace => "trce", 63 | LogLevel.Debug => "dbug", 64 | LogLevel.Information => "info", 65 | LogLevel.Warning => "warn", 66 | LogLevel.Error => "fail", 67 | LogLevel.Critical => "crit", 68 | _ => throw new ArgumentOutOfRangeException(nameof(logLevel)) 69 | }; 70 | } 71 | } 72 | -------------------------------------------------------------------------------- /api_templates/APIProjectTests/XUnitLoggerProvider.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.Extensions.Logging; 2 | using Xunit.Abstractions; 3 | 4 | namespace APIProjectTests; 5 | 6 | internal sealed class XUnitLoggerProvider : ILoggerProvider 7 | { 8 | private readonly ITestOutputHelper _testOutputHelper; 9 | private readonly LoggerExternalScopeProvider _scopeProvider = new LoggerExternalScopeProvider(); 10 | 11 | public XUnitLoggerProvider(ITestOutputHelper testOutputHelper) 12 | { 13 | _testOutputHelper = testOutputHelper; 14 | } 15 | 16 | public ILogger CreateLogger(string categoryName) 17 | { 18 | return new XUnitLogger(_testOutputHelper, _scopeProvider, categoryName); 19 | } 20 | 21 | public void Dispose() 22 | { 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /api_templates/APIProjectTests/appsettings.Development.json: -------------------------------------------------------------------------------- 1 | { 2 | "Logging": { 3 | "LogLevel": { 4 | "Default": "Information", 5 | "Microsoft.AspNetCore": "Warning" 6 | } 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /api_templates/APIProjectTests/appsettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "Logging": { 3 | "LogLevel": { 4 | "Default": "Information", 5 | "Microsoft.AspNetCore": "Warning" 6 | } 7 | }, 8 | "ConnectionStrings": { 9 | "DefaultConnection": "Data Source=:memory:" 10 | }, 11 | "AllowedHosts": "*" 12 | } 13 | -------------------------------------------------------------------------------- /api_templates/ApiBestPractices.Endpoints/ApiBestPractices.Endpoints.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | net8.0 5 | enable 6 | enable 7 | 8 | 9 | 10 | .\ApiBestPractices.Endpoints.xml 11 | CS1591 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | all 24 | runtime; build; native; contentfiles; analyzers; buildtransitive 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | -------------------------------------------------------------------------------- /api_templates/ApiBestPractices.Endpoints/ApiBestPractices.Endpoints.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | ApiBestPractices.Endpoints 5 | 6 | 7 | 8 | 9 | Source: https://docs.microsoft.com/en-us/dotnet/core/extensions/scoped-service 10 | 11 | 12 | 13 | 14 | Authenticates a user and returns a JWT Token 15 | 16 | 17 | 18 | 19 | Creates a new User 20 | 21 | 22 | 23 | 24 | Creates a new Author 25 | 26 | 27 | 28 | 29 | Deletes an Author 30 | 31 | 32 | 33 | 34 | Get a specific Author 35 | 36 | 37 | 38 | 39 | List all Authors 40 | 41 | 42 | 43 | 44 | See: https://docs.microsoft.com/en-us/aspnet/core/web-api/jsonpatch?view=aspnetcore-6.0 45 | 46 | 47 | 48 | 49 | Patches an existing Author 50 | 51 | 52 | 53 | 54 | Updates an existing Author 55 | 56 | 57 | 58 | 59 | -------------------------------------------------------------------------------- /api_templates/ApiBestPractices.Endpoints/AuthExtensions.cs: -------------------------------------------------------------------------------- 1 | using BackendData.Security; 2 | using Microsoft.AspNetCore.Authentication.JwtBearer; 3 | using Microsoft.IdentityModel.Tokens; 4 | 5 | public static class AuthExtensions 6 | { 7 | public static void ConfigureJwtAuthentication(this IServiceCollection services, 8 | TokenOptions tokenOptions, 9 | SigningConfigurations signingConfigurations) 10 | { 11 | services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) 12 | .AddJwtBearer(jwtBearerOptions => 13 | { 14 | jwtBearerOptions.TokenValidationParameters = 15 | new TokenValidationParameters() 16 | { 17 | ValidateAudience = true, 18 | ValidateLifetime = true, 19 | ValidateIssuerSigningKey = true, 20 | ValidIssuer = tokenOptions.Issuer, 21 | ValidAudience = tokenOptions.Audience, 22 | IssuerSigningKey = signingConfigurations.SecurityKey, 23 | ClockSkew = TimeSpan.Zero 24 | }; 25 | }); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /api_templates/ApiBestPractices.Endpoints/AutoMapping.cs: -------------------------------------------------------------------------------- 1 | using ApiBestPractices.Endpoints.Endpoints.Authors; 2 | using AutoMapper; 3 | using BackendData; 4 | 5 | namespace ApiBestPractices.Endpoints; 6 | 7 | public class AutoMapping : Profile 8 | { 9 | public AutoMapping() 10 | { 11 | CreateMap(); 12 | CreateMap(); 13 | 14 | CreateMap().ReverseMap(); 15 | CreateMap(); 16 | 17 | CreateMap(); 18 | 19 | CreateMap().ReverseMap(); 20 | CreateMap(); 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /api_templates/ApiBestPractices.Endpoints/DataConsistencyWorker.cs: -------------------------------------------------------------------------------- 1 | using BackendData; 2 | 3 | namespace ApiBestPractices.Endpoints; 4 | 5 | // makes sure data in the database stays properly formatted 6 | public class DataConsistencyWorker : BackgroundService 7 | { 8 | public DataConsistencyWorker(IServiceProvider services) 9 | { 10 | Services = services; 11 | } 12 | 13 | public IServiceProvider Services { get; } 14 | 15 | protected override async Task ExecuteAsync(CancellationToken stoppingToken) 16 | { 17 | await DoWork(stoppingToken); 18 | } 19 | 20 | private async Task DoWork(CancellationToken stoppingToken) 21 | { 22 | using (var scope = Services.CreateScope()) 23 | { 24 | var scopedProcessingService = 25 | scope.ServiceProvider 26 | .GetRequiredService(); 27 | 28 | await scopedProcessingService.DoWork(stoppingToken); 29 | } 30 | } 31 | } 32 | 33 | internal interface IScopedProcessingService 34 | { 35 | Task DoWork(CancellationToken stoppingToken); 36 | } 37 | 38 | /// 39 | /// Source: https://docs.microsoft.com/en-us/dotnet/core/extensions/scoped-service 40 | /// 41 | internal class ScopedProcessingService : IScopedProcessingService 42 | { 43 | private readonly ILogger _logger; 44 | private readonly IAsyncRepository _authorRepository; 45 | 46 | public ScopedProcessingService(ILogger logger, 47 | IAsyncRepository authorRepository) 48 | { 49 | _logger = logger; 50 | _authorRepository = authorRepository; 51 | } 52 | 53 | public async Task DoWork(CancellationToken stoppingToken) 54 | { 55 | while (!stoppingToken.IsCancellationRequested) 56 | { 57 | _logger.LogInformation( 58 | "Checking database for issues..."); 59 | 60 | var authorsWithInvalidTwitterAlias = (await _authorRepository 61 | .ListAllAsync(stoppingToken)) 62 | .Where(author => author.TwitterAlias?.Length > 0 && 63 | !author.TwitterAlias.StartsWith('@')) 64 | .ToList(); 65 | 66 | _logger.LogInformation($"Found {authorsWithInvalidTwitterAlias.Count} records to fix."); 67 | 68 | foreach (var author in authorsWithInvalidTwitterAlias) 69 | { 70 | author.TwitterAlias = "@" + author.TwitterAlias; 71 | await _authorRepository.UpdateAsync(author, stoppingToken); 72 | } 73 | 74 | _logger.LogInformation($"Fixed {authorsWithInvalidTwitterAlias.Count} records."); 75 | 76 | await Task.Delay(30_000, stoppingToken); 77 | } 78 | } 79 | } 80 | -------------------------------------------------------------------------------- /api_templates/ApiBestPractices.Endpoints/Endpoints/Account/Login.LoginUserCommand.cs: -------------------------------------------------------------------------------- 1 | using System.ComponentModel.DataAnnotations; 2 | using BackendData.DataAccess.Config; 3 | 4 | namespace ApiBestPractices.Endpoints.Endpoints.Account; 5 | 6 | public class LoginUserCommand 7 | { 8 | [Required] 9 | [MaxLength(ConfigConstants.DEFAULT_NAME_LENGTH)] 10 | public string Email { get; set; } = string.Empty; 11 | 12 | [Required] 13 | [MaxLength(ConfigConstants.DEFAULT_NAME_LENGTH)] 14 | public string Password { get; set; } = string.Empty; 15 | } 16 | -------------------------------------------------------------------------------- /api_templates/ApiBestPractices.Endpoints/Endpoints/Account/Login.TokenResponse.cs: -------------------------------------------------------------------------------- 1 | using BackendData.Security; 2 | 3 | namespace ApiBestPractices.Endpoints.Endpoints.Account; 4 | 5 | public class TokenResponse 6 | { 7 | public AccessToken AccessToken { get; set; } = default!; 8 | } 9 | -------------------------------------------------------------------------------- /api_templates/ApiBestPractices.Endpoints/Endpoints/Account/Login.cs: -------------------------------------------------------------------------------- 1 | using Ardalis.ApiEndpoints; 2 | using BackendData; 3 | using BackendData.Security; 4 | using BackendData.Services; 5 | using Microsoft.AspNetCore.Mvc; 6 | 7 | namespace ApiBestPractices.Endpoints.Endpoints.Account; 8 | 9 | public class Login : EndpointBaseAsync 10 | .WithRequest 11 | .WithActionResult 12 | { 13 | private readonly IAsyncRepository _repository; 14 | private readonly IPasswordHasher _passwordHasher; 15 | private readonly IAuthenticationService _authenticationService; 16 | 17 | public Login(IAsyncRepository repository, 18 | IPasswordHasher passwordHasher, 19 | IAuthenticationService authenticationService) 20 | { 21 | _repository = repository; 22 | _passwordHasher = passwordHasher; 23 | _authenticationService = authenticationService; 24 | } 25 | 26 | /// 27 | /// Authenticates a user and returns a JWT Token 28 | /// 29 | [HttpPost("[namespace]/Login")] 30 | [ProducesResponseType(StatusCodes.Status200OK)] 31 | [ProducesResponseType(StatusCodes.Status400BadRequest)] 32 | public override async Task> HandleAsync(LoginUserCommand request, 33 | CancellationToken cancellationToken = default) 34 | { 35 | var tokenResult = await _authenticationService.CreateAccessTokenAsync(request.Email, 36 | request.Password, cancellationToken); 37 | 38 | if (!tokenResult.IsSuccess) 39 | { 40 | return BadRequest("Invalid credentials."); 41 | } 42 | 43 | var response = new TokenResponse() { AccessToken = tokenResult.Value }; 44 | 45 | return Ok(response); 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /api_templates/ApiBestPractices.Endpoints/Endpoints/Account/Register.RegisterUserCommand.cs: -------------------------------------------------------------------------------- 1 | using System.ComponentModel.DataAnnotations; 2 | using BackendData.DataAccess.Config; 3 | 4 | namespace ApiBestPractices.Endpoints.Endpoints.Account; 5 | 6 | public class RegisterUserCommand 7 | { 8 | [Required] 9 | [MaxLength(ConfigConstants.DEFAULT_NAME_LENGTH)] 10 | public string Email { get; set; } 11 | 12 | [Required] 13 | [MaxLength(ConfigConstants.DEFAULT_NAME_LENGTH)] 14 | public string Password { get; set; } 15 | } 16 | -------------------------------------------------------------------------------- /api_templates/ApiBestPractices.Endpoints/Endpoints/Account/Register.cs: -------------------------------------------------------------------------------- 1 | using Ardalis.ApiEndpoints; 2 | using BackendData; 3 | using BackendData.Security; 4 | using Microsoft.AspNetCore.Mvc; 5 | 6 | namespace ApiBestPractices.Endpoints.Endpoints.Account; 7 | 8 | public class Register : EndpointBaseAsync 9 | .WithRequest 10 | .WithActionResult 11 | { 12 | private readonly IAsyncRepository _repository; 13 | private readonly IPasswordHasher _passwordHasher; 14 | 15 | public Register(IAsyncRepository repository, 16 | IPasswordHasher passwordHasher) 17 | { 18 | _repository = repository; 19 | _passwordHasher = passwordHasher; 20 | } 21 | 22 | /// 23 | /// Creates a new User 24 | /// 25 | [HttpPost("[namespace]/Register")] 26 | [ProducesResponseType(StatusCodes.Status200OK)] 27 | [ProducesResponseType(StatusCodes.Status400BadRequest)] 28 | public override async Task HandleAsync([FromBody] RegisterUserCommand request, 29 | CancellationToken cancellationToken = default) 30 | { 31 | var existingUsers = await _repository.ListByExpressionAsync(u => u.Email == request.Email, cancellationToken); 32 | 33 | if (existingUsers.Any()) return BadRequest("User with email already exists"); 34 | 35 | var user = new User(request.Email, _passwordHasher.HashPassword(request.Password)); 36 | 37 | await _repository.AddAsync(user, cancellationToken); 38 | 39 | return Ok(user.Id); 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /api_templates/ApiBestPractices.Endpoints/Endpoints/Authors/Create.CreateAuthorCommand.cs: -------------------------------------------------------------------------------- 1 | using System.ComponentModel.DataAnnotations; 2 | using BackendData.DataAccess.Config; 3 | 4 | namespace ApiBestPractices.Endpoints.Endpoints.Authors; 5 | 6 | public class CreateAuthorCommand 7 | { 8 | [Required] 9 | [MaxLength(ConfigConstants.DEFAULT_NAME_LENGTH)] 10 | public string Name { get; set; } = null!; 11 | [MaxLength(ConfigConstants.DEFAULT_URI_LENGTH)] 12 | public string PluralsightUrl { get; set; } = null!; 13 | [MaxLength(ConfigConstants.DEFAULT_NAME_LENGTH)] 14 | [RegularExpression("^@(\\w){1,15}$")] 15 | public string? TwitterAlias { get; set; } 16 | } 17 | 18 | // You can use a record type, which still supports Data Annotations 19 | public record CreateAuthorRequest( 20 | [Required] 21 | [MaxLength(ConfigConstants.DEFAULT_NAME_LENGTH)] 22 | string Name, 23 | [MaxLength(ConfigConstants.DEFAULT_URI_LENGTH)] 24 | string PluralsightUrl, 25 | [MaxLength(ConfigConstants.DEFAULT_NAME_LENGTH)] 26 | string? TwitterAlias 27 | ); 28 | -------------------------------------------------------------------------------- /api_templates/ApiBestPractices.Endpoints/Endpoints/Authors/Create.CreatedAuthorResult.cs: -------------------------------------------------------------------------------- 1 | namespace ApiBestPractices.Endpoints.Endpoints.Authors; 2 | 3 | public class CreatedAuthorResult : CreateAuthorCommand 4 | { 5 | public int Id { get; set; } 6 | } 7 | -------------------------------------------------------------------------------- /api_templates/ApiBestPractices.Endpoints/Endpoints/Authors/Create.cs: -------------------------------------------------------------------------------- 1 | using Ardalis.ApiEndpoints; 2 | using AutoMapper; 3 | using BackendData; 4 | using Microsoft.AspNetCore.Mvc; 5 | 6 | namespace ApiBestPractices.Endpoints.Endpoints.Authors; 7 | 8 | public class Create : EndpointBaseAsync 9 | .WithRequest 10 | .WithActionResult 11 | { 12 | private readonly IAsyncRepository _repository; 13 | private readonly IMapper _mapper; 14 | 15 | public Create(IAsyncRepository repository, 16 | IMapper mapper) 17 | { 18 | _repository = repository; 19 | _mapper = mapper; 20 | } 21 | 22 | /// 23 | /// Creates a new Author 24 | /// 25 | [HttpPost("[namespace]")] 26 | [ProducesResponseType(StatusCodes.Status201Created, Type=typeof(CreatedAuthorResult))] 27 | [ProducesResponseType(StatusCodes.Status400BadRequest)] 28 | public override async Task HandleAsync([FromBody] CreateAuthorCommand request, 29 | CancellationToken cancellationToken) 30 | { 31 | var author = new Author(); 32 | _mapper.Map(request, author); 33 | await _repository.AddAsync(author, cancellationToken); 34 | 35 | var result = _mapper.Map(author); 36 | return CreatedAtRoute("Authors_Get", new { id = result.Id }, result); 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /api_templates/ApiBestPractices.Endpoints/Endpoints/Authors/Delete.cs: -------------------------------------------------------------------------------- 1 | using Ardalis.ApiEndpoints; 2 | using BackendData; 3 | using Microsoft.AspNetCore.Authorization; 4 | using Microsoft.AspNetCore.Mvc; 5 | 6 | namespace ApiBestPractices.Endpoints.Endpoints.Authors; 7 | 8 | [Authorize] 9 | public class Delete : EndpointBaseAsync 10 | .WithRequest 11 | .WithActionResult 12 | { 13 | private readonly IAsyncRepository _repository; 14 | 15 | public Delete(IAsyncRepository repository) 16 | { 17 | _repository = repository; 18 | } 19 | 20 | /// 21 | /// Deletes an Author 22 | /// 23 | [HttpDelete("[namespace]/{id}")] 24 | public override async Task HandleAsync(int id, CancellationToken cancellationToken) 25 | { 26 | var author = await _repository.GetByIdAsync(id, cancellationToken); 27 | 28 | if (author is null) 29 | { 30 | return NotFound(id); 31 | } 32 | 33 | await _repository.DeleteAsync(author, cancellationToken); 34 | 35 | // see https://restfulapi.net/http-methods/#delete 36 | return NoContent(); 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /api_templates/ApiBestPractices.Endpoints/Endpoints/Authors/Get.AuthorDto.cs: -------------------------------------------------------------------------------- 1 | namespace ApiBestPractices.Endpoints.Endpoints.Authors; 2 | 3 | public class AuthorDto 4 | { 5 | public string Id { get; set; } = null!; 6 | public string Name { get; set; } = null!; 7 | public string PluralsightUrl { get; set; } = null!; 8 | public string? TwitterAlias { get; set; } 9 | } 10 | -------------------------------------------------------------------------------- /api_templates/ApiBestPractices.Endpoints/Endpoints/Authors/Get.cs: -------------------------------------------------------------------------------- 1 | using Ardalis.ApiEndpoints; 2 | using AutoMapper; 3 | using BackendData; 4 | using Microsoft.AspNetCore.Mvc; 5 | 6 | namespace ApiBestPractices.Endpoints.Endpoints.Authors; 7 | 8 | public class Get : EndpointBaseAsync 9 | .WithRequest 10 | .WithActionResult 11 | { 12 | private readonly IAsyncRepository _repository; 13 | private readonly IMapper _mapper; 14 | 15 | public Get(IAsyncRepository repository, 16 | IMapper mapper) 17 | { 18 | _repository = repository; 19 | _mapper = mapper; 20 | } 21 | 22 | /// 23 | /// Get a specific Author 24 | /// 25 | [HttpGet("[namespace]/{id}", Name = "[namespace]_[controller]")] 26 | public override async Task> HandleAsync(int id, CancellationToken cancellationToken) 27 | { 28 | var author = await _repository.GetByIdAsync(id, cancellationToken); 29 | 30 | if (author is null) return NotFound(); 31 | 32 | var result = _mapper.Map(author); 33 | 34 | return result; 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /api_templates/ApiBestPractices.Endpoints/Endpoints/Authors/List.AuthorListResult.cs: -------------------------------------------------------------------------------- 1 | namespace ApiBestPractices.Endpoints.Endpoints.Authors; 2 | 3 | public record AuthorListResult(int Id, string Name, string TwitterAlias); 4 | -------------------------------------------------------------------------------- /api_templates/ApiBestPractices.Endpoints/Endpoints/Authors/List.cs: -------------------------------------------------------------------------------- 1 | using Ardalis.ApiEndpoints; 2 | using AutoMapper; 3 | using BackendData; 4 | using Microsoft.AspNetCore.Mvc; 5 | 6 | namespace ApiBestPractices.Endpoints.Endpoints.Authors; 7 | 8 | public class List : EndpointBaseAsync 9 | .WithoutRequest 10 | .WithResult> 11 | { 12 | private readonly IAsyncRepository _repository; 13 | private readonly IMapper _mapper; 14 | 15 | public List( 16 | IAsyncRepository repository, 17 | IMapper mapper) 18 | { 19 | _repository = repository; 20 | _mapper = mapper; 21 | } 22 | 23 | /// 24 | /// List all Authors 25 | /// 26 | [HttpGet("[namespace]")] 27 | public override async Task> HandleAsync(CancellationToken cancellationToken = default) 28 | { 29 | var result = (await _repository.ListAllAsync(cancellationToken)) 30 | .Select(i => _mapper.Map(i)); 31 | 32 | return result; 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /api_templates/ApiBestPractices.Endpoints/Endpoints/Authors/Patch.PatchAuthorCommand.cs: -------------------------------------------------------------------------------- 1 | using System.ComponentModel.DataAnnotations; 2 | using Microsoft.AspNetCore.JsonPatch; 3 | 4 | namespace ApiBestPractices.Endpoints.Endpoints.Authors; 5 | 6 | public class PatchAuthorCommand 7 | { 8 | [Required] // From Route 9 | [System.Text.Json.Serialization.JsonIgnore] // so it doesn't appear in body example schema in Swagger 10 | public int Id { get; set; } 11 | 12 | [Required] 13 | public JsonPatchDocument PatchDocument { get; set; } 14 | } 15 | -------------------------------------------------------------------------------- /api_templates/ApiBestPractices.Endpoints/Endpoints/Authors/Patch.PatchedAuthorResult.cs: -------------------------------------------------------------------------------- 1 | namespace ApiBestPractices.Endpoints.Endpoints.Authors; 2 | 3 | public class PatchedAuthorResult 4 | { 5 | public string Id { get; set; } = null!; 6 | public string Name { get; set; } = null!; 7 | public string? PluralsightUrl { get; set; } 8 | public string? TwitterAlias { get; set; } 9 | } 10 | -------------------------------------------------------------------------------- /api_templates/ApiBestPractices.Endpoints/Endpoints/Authors/Patch.cs: -------------------------------------------------------------------------------- 1 | using Ardalis.ApiEndpoints; 2 | using Ardalis.RouteAndBodyModelBinding; 3 | using AutoMapper; 4 | using BackendData; 5 | using Microsoft.AspNetCore.Mvc; 6 | 7 | namespace ApiBestPractices.Endpoints.Endpoints.Authors; 8 | 9 | /// 10 | /// See: https://docs.microsoft.com/en-us/aspnet/core/web-api/jsonpatch?view=aspnetcore-6.0 11 | /// 12 | public class Patch : EndpointBaseAsync 13 | .WithRequest 14 | .WithActionResult 15 | { 16 | private readonly IAsyncRepository _repository; 17 | private readonly IMapper _mapper; 18 | 19 | public Patch(IAsyncRepository repository, 20 | IMapper mapper) 21 | { 22 | _repository = repository; 23 | _mapper = mapper; 24 | } 25 | 26 | /// 27 | /// Patches an existing Author 28 | /// 29 | [HttpPatch("[namespace]/{id}")] 30 | public override async Task> HandleAsync([FromRouteAndBody] PatchAuthorCommand request, 31 | CancellationToken cancellationToken) 32 | { 33 | var author = await _repository.GetByIdAsync(request.Id, cancellationToken); 34 | if (author is null) return NotFound(); 35 | 36 | var updatecommand = _mapper.Map(author); 37 | request.PatchDocument.ApplyTo(updatecommand); 38 | 39 | // perform model validation of the changes 40 | TryValidateModel(updatecommand); 41 | if (!ModelState.IsValid) return BadRequest(ModelState); 42 | 43 | _mapper.Map(updatecommand, author); 44 | await _repository.UpdateAsync(author, cancellationToken); 45 | 46 | var result = _mapper.Map(author); 47 | return result; 48 | // NOTE: Alternately you could return a 204 No Content with a Location Header pointing to /authors/{id} 49 | } 50 | 51 | /* Examples: 52 | { 53 | "patchDocument": [ 54 | { "op": "replace", "path": "/name", "value": "steve" }, 55 | ] 56 | } 57 | { 58 | "patchDocument": [ 59 | { 60 | "op": "replace", 61 | "value": "updated", 62 | "path":"/twitterAlias" 63 | } 64 | ] 65 | } 66 | */ 67 | } 68 | -------------------------------------------------------------------------------- /api_templates/ApiBestPractices.Endpoints/Endpoints/Authors/Update.UpdateAuthorCommand.cs: -------------------------------------------------------------------------------- 1 | using System.ComponentModel.DataAnnotations; 2 | using BackendData.DataAccess.Config; 3 | 4 | namespace ApiBestPractices.Endpoints.Endpoints.Authors; 5 | 6 | public class UpdateAuthorCommand 7 | { 8 | [Required] // From Route 9 | [System.Text.Json.Serialization.JsonIgnore] // so it doesn't appear in body example schema in Swagger 10 | // see: https://github.com/domaindrivendev/Swashbuckle.WebApi/issues/1230 11 | public int Id { get; set; } 12 | 13 | [Required] 14 | [MaxLength(ConfigConstants.DEFAULT_NAME_LENGTH)] 15 | public string Name { get; set; } = null!; 16 | [MaxLength(ConfigConstants.DEFAULT_URI_LENGTH)] 17 | public string? PluralsightUrl { get; set; } 18 | [MaxLength(ConfigConstants.DEFAULT_NAME_LENGTH)] 19 | public string? TwitterAlias { get; set; } 20 | } 21 | -------------------------------------------------------------------------------- /api_templates/ApiBestPractices.Endpoints/Endpoints/Authors/Update.UpdatedAuthorResult.cs: -------------------------------------------------------------------------------- 1 | namespace ApiBestPractices.Endpoints.Endpoints.Authors; 2 | 3 | public class UpdatedAuthorResult 4 | { 5 | public string Id { get; set; } = null!; 6 | public string Name { get; set; } = null!; 7 | public string? PluralsightUrl { get; set; } 8 | public string? TwitterAlias { get; set; } 9 | } 10 | -------------------------------------------------------------------------------- /api_templates/ApiBestPractices.Endpoints/Endpoints/Authors/Update.cs: -------------------------------------------------------------------------------- 1 | using Ardalis.ApiEndpoints; 2 | using Ardalis.RouteAndBodyModelBinding; 3 | using AutoMapper; 4 | using BackendData; 5 | using Microsoft.AspNetCore.Mvc; 6 | 7 | namespace ApiBestPractices.Endpoints.Endpoints.Authors; 8 | 9 | public class Update : EndpointBaseAsync 10 | .WithRequest 11 | .WithActionResult 12 | { 13 | private readonly IAsyncRepository _repository; 14 | private readonly IMapper _mapper; 15 | 16 | public Update(IAsyncRepository repository, 17 | IMapper mapper) 18 | { 19 | _repository = repository; 20 | _mapper = mapper; 21 | } 22 | 23 | /// 24 | /// Updates an existing Author 25 | /// 26 | [HttpPut("[namespace]/{id}")] 27 | public override async Task> HandleAsync( 28 | [FromRouteAndBody] UpdateAuthorCommand request, 29 | CancellationToken cancellationToken) 30 | { 31 | var author = await _repository.GetByIdAsync(request.Id, cancellationToken); 32 | 33 | if (author is null) return NotFound(); 34 | 35 | _mapper.Map(request, author); 36 | await _repository.UpdateAsync(author, cancellationToken); 37 | 38 | var result = _mapper.Map(author); 39 | return result; 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /api_templates/ApiBestPractices.Endpoints/Program.cs: -------------------------------------------------------------------------------- 1 | using ApiBestPractices.Endpoints; 2 | using ApiBestPractices.Endpoints.Endpoints.Authors; 3 | using Ardalis.RouteAndBodyModelBinding; 4 | using BackendData; 5 | using BackendData.DataAccess; 6 | using BackendData.Security; 7 | using BackendData.Services; 8 | using Microsoft.Data.Sqlite; 9 | using Microsoft.EntityFrameworkCore; 10 | using Microsoft.OpenApi.Models; 11 | 12 | var builder = WebApplication.CreateBuilder(args); 13 | var connectionString = builder.Configuration.GetConnectionString("DefaultConnection") ?? "Data Source=database.sqlite;Cache=Shared"; 14 | var connection = new SqliteConnection(connectionString); 15 | connection.Open(); 16 | 17 | //var connectionString = builder.Configuration.GetConnectionString("DefaultConnection") ?? "Data Source=database.sqlite;Cache=Shared"; 18 | //builder.Services.AddSqlite(connectionString); 19 | 20 | 21 | builder.Services.AddDbContext(options => 22 | options.UseSqlite(connection)); // will be created in web project root 23 | 24 | builder.Services.AddControllers(options => 25 | { 26 | options.UseNamespaceRouteToken(); 27 | options.ModelBinderProviders.InsertRouteAndBodyBinding(); 28 | }) 29 | .AddNewtonsoftJson(); // needed for JsonPatch support 30 | builder.Services.AddAutoMapper(typeof(List)); 31 | builder.Services.AddScoped(typeof(IAsyncRepository<>), typeof(EfRepository<>)); 32 | builder.Services.AddSingleton(); 33 | builder.Services.AddScoped(); 34 | builder.Services.AddScoped(); 35 | 36 | builder.Services.Configure(builder.Configuration.GetSection("TokenOptions")); 37 | var tokenOptions = builder.Configuration.GetSection("TokenOptions").Get(); 38 | var signingConfigurations = new SigningConfigurations(tokenOptions.Secret); 39 | builder.Services.AddSingleton(signingConfigurations); 40 | 41 | builder.Services.ConfigureJwtAuthentication(tokenOptions, signingConfigurations); 42 | 43 | 44 | builder.Services.AddSwaggerGen(c => 45 | { 46 | c.SwaggerDoc("v1", new OpenApiInfo { Title = "API Endpoints", Version = "v1" }); 47 | c.IncludeXmlComments(Path.Combine(AppContext.BaseDirectory, "ApiBestPractices.Endpoints.xml")); 48 | c.UseApiEndpoints(); 49 | c.OperationFilter(); 50 | //c.DocumentFilter(); 51 | c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme 52 | { 53 | In = ParameterLocation.Header, 54 | Description = "Please enter a valid token", 55 | Name = "Authorization", 56 | Type = SecuritySchemeType.Http, 57 | BearerFormat = "JWT", 58 | Scheme = "Bearer" 59 | }); 60 | c.AddSecurityRequirement(new OpenApiSecurityRequirement 61 | { 62 | { 63 | new OpenApiSecurityScheme 64 | { 65 | Reference = new OpenApiReference 66 | { 67 | Type=ReferenceType.SecurityScheme, 68 | Id="Bearer" 69 | } 70 | }, 71 | new string[]{} 72 | } 73 | }); 74 | }); 75 | 76 | builder.Services.AddHostedService(); 77 | builder.Services.AddScoped(); 78 | 79 | var app = builder.Build(); 80 | 81 | await EnsureDb(app.Services, app.Logger); 82 | 83 | // Configure the HTTP request pipeline. 84 | if (app.Environment.IsDevelopment()) 85 | { 86 | app.UseSwagger(); 87 | app.UseSwaggerUI(c => 88 | { 89 | c.SwaggerEndpoint("/swagger/v1/swagger.json", "API Endpoints"); 90 | c.RoutePrefix = ""; 91 | }); 92 | } 93 | 94 | // Configure the HTTP request pipeline. 95 | if (!app.Environment.IsDevelopment()) 96 | { 97 | app.UseExceptionHandler("/Home/Error"); 98 | // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts. 99 | //app.UseHsts(); 100 | } 101 | 102 | //app.UseHttpsRedirection(); 103 | app.UseStaticFiles(); 104 | 105 | app.UseRouting(); 106 | 107 | app.UseAuthentication(); 108 | app.UseAuthorization(); 109 | 110 | app.UseEndpoints(app => app.MapControllers()); 111 | 112 | await using var scope = app.Services.CreateAsyncScope(); 113 | using var db = scope.ServiceProvider.GetService(); 114 | 115 | await EnsureDb(app.Services, app.Logger); 116 | 117 | app.Run(); 118 | 119 | async Task EnsureDb(IServiceProvider services, ILogger logger) 120 | { 121 | using var db = services.CreateScope() 122 | .ServiceProvider.GetRequiredService(); 123 | if (db.Database.IsRelational()) 124 | { 125 | logger.LogInformation("Ensuring database exists and is up to date at connection string '{connectionString}'", connectionString); 126 | //await db.Database.EnsureCreatedAsync(); 127 | await db.Database.MigrateAsync(); 128 | } 129 | } 130 | 131 | // Make the implicit Program class public so test projects can access it 132 | public partial class Program { } 133 | -------------------------------------------------------------------------------- /api_templates/ApiBestPractices.Endpoints/Properties/launchSettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "iisSettings": { 3 | "windowsAuthentication": false, 4 | "anonymousAuthentication": true, 5 | "iisExpress": { 6 | "applicationUrl": "http://localhost:3153", 7 | "sslPort": 44336 8 | } 9 | }, 10 | "profiles": { 11 | "ApiBestPractices.Endpoints": { 12 | "commandName": "Project", 13 | "launchBrowser": true, 14 | "environmentVariables": { 15 | "ASPNETCORE_ENVIRONMENT": "Development" 16 | }, 17 | "hotReloadEnabled": false, 18 | "applicationUrl": "https://localhost:7094;http://localhost:5219", 19 | "dotnetRunMessages": true 20 | }, 21 | "IIS Express": { 22 | "commandName": "IISExpress", 23 | "launchBrowser": true, 24 | "environmentVariables": { 25 | "ASPNETCORE_ENVIRONMENT": "Development" 26 | } 27 | } 28 | } 29 | } -------------------------------------------------------------------------------- /api_templates/ApiBestPractices.Endpoints/appsettings.Development.json: -------------------------------------------------------------------------------- 1 | { 2 | "Logging": { 3 | "LogLevel": { 4 | "Default": "Information", 5 | "Microsoft.AspNetCore": "Warning" 6 | } 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /api_templates/ApiBestPractices.Endpoints/appsettings.Testing.json: -------------------------------------------------------------------------------- 1 | { 2 | "Logging": { 3 | "LogLevel": { 4 | "Default": "Information", 5 | "Microsoft.AspNetCore": "Warning" 6 | } 7 | }, 8 | "ConnectionStrings": { 9 | "DefaultConnection": "Data Source=:memory:" 10 | }, 11 | "AllowedHosts": "*" 12 | } 13 | -------------------------------------------------------------------------------- /api_templates/ApiBestPractices.Endpoints/appsettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "Logging": { 3 | "LogLevel": { 4 | "Default": "Information", 5 | "Microsoft.AspNetCore": "Warning" 6 | } 7 | }, 8 | "TokenOptions": { 9 | "Audience": "EndpointsClients", 10 | "Issuer": "PluralsightApiBestPractices", 11 | "AccessTokenExpiration": 300, 12 | "Secret": "very_long_but_insecure_token_here_be_sure_to_use_env_var" 13 | }, 14 | "ConnectionStrings": { 15 | "DefaultConnection": "Data Source=database.sqlite" 16 | }, 17 | "AllowedHosts": "*" 18 | } 19 | -------------------------------------------------------------------------------- /api_templates/BackendData/BackendData.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | net8.0 5 | enable 6 | enable 7 | 8 | 9 | 10 | 11 | 12 | all 13 | runtime; build; native; contentfiles; analyzers; buildtransitive 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | -------------------------------------------------------------------------------- /api_templates/BackendData/DataAccess/AppDbContext.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.EntityFrameworkCore; 2 | using System.Reflection; 3 | 4 | namespace BackendData.DataAccess; 5 | 6 | public class AppDbContext : DbContext 7 | { 8 | // Add Migration Script, from Web Project 9 | // dotnet ef migrations add AddUsers --context AppDbContext -p ../BackendData/BackendData.csproj -s .\ApiBestPractices.Endpoints.csproj -o Migrations 10 | public AppDbContext() 11 | { } 12 | 13 | public AppDbContext(DbContextOptions options) : base(options) 14 | { 15 | } 16 | 17 | public DbSet Authors { get; set; } = null!; 18 | public DbSet Users { get; set; } = null!; 19 | 20 | //protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) 21 | //{ 22 | // if (!optionsBuilder.IsConfigured) 23 | // { 24 | // optionsBuilder.UseSqlite(":memory"); 25 | // } 26 | //} 27 | 28 | protected override void OnModelCreating(ModelBuilder modelBuilder) 29 | { 30 | base.OnModelCreating(modelBuilder); 31 | 32 | modelBuilder.ApplyConfigurationsFromAssembly(Assembly.GetExecutingAssembly()); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /api_templates/BackendData/DataAccess/Config/AuthorConfig.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.EntityFrameworkCore; 2 | using Microsoft.EntityFrameworkCore.Metadata.Builders; 3 | 4 | namespace BackendData.DataAccess.Config; 5 | 6 | public class AuthorConfig : IEntityTypeConfiguration 7 | { 8 | public void Configure(EntityTypeBuilder builder) 9 | { 10 | builder.Property(a => a.Name) 11 | .IsRequired() 12 | .HasMaxLength(ConfigConstants.DEFAULT_NAME_LENGTH); 13 | 14 | builder.Property(a => a.PluralsightUrl) 15 | .HasMaxLength(ConfigConstants.DEFAULT_URI_LENGTH); 16 | 17 | builder.Property(a => a.TwitterAlias) 18 | .HasMaxLength(ConfigConstants.DEFAULT_NAME_LENGTH); 19 | 20 | builder.HasData(SeedData.Authors()); 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /api_templates/BackendData/DataAccess/Config/ConfigConstants.cs: -------------------------------------------------------------------------------- 1 | namespace BackendData.DataAccess.Config; 2 | 3 | public class ConfigConstants 4 | { 5 | public const int DEFAULT_NAME_LENGTH = 100; 6 | public const int DEFAULT_URI_LENGTH = 255; 7 | } 8 | -------------------------------------------------------------------------------- /api_templates/BackendData/DataAccess/Config/UserConfig.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.EntityFrameworkCore; 2 | using Microsoft.EntityFrameworkCore.Metadata.Builders; 3 | 4 | namespace BackendData.DataAccess.Config; 5 | 6 | public class UserConfig : IEntityTypeConfiguration 7 | { 8 | public void Configure(EntityTypeBuilder builder) 9 | { 10 | builder.Property(x => x.Email) 11 | .IsRequired() 12 | .HasMaxLength(ConfigConstants.DEFAULT_NAME_LENGTH); 13 | 14 | builder.Property(x => x.Password) 15 | .HasMaxLength(ConfigConstants.DEFAULT_NAME_LENGTH); 16 | 17 | builder.HasData(SeedData.Users()); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /api_templates/BackendData/DataAccess/EfRepository.cs: -------------------------------------------------------------------------------- 1 | using System.Linq.Expressions; 2 | using Microsoft.EntityFrameworkCore; 3 | 4 | namespace BackendData.DataAccess; 5 | 6 | /// 7 | /// Source: My reference app https://github.com/dotnet-architecture/eShopOnWeb 8 | /// Check it out if you need filtering/paging/etc. 9 | /// Also consider Ardalis.Specification and its built-in generic repository 10 | /// 11 | public class EfRepository : IAsyncRepository where T : BaseEntity 12 | { 13 | protected readonly AppDbContext _dbContext; 14 | 15 | public EfRepository(AppDbContext dbContext) 16 | { 17 | _dbContext = dbContext; 18 | } 19 | 20 | public virtual async Task GetByIdAsync(int id, CancellationToken cancellationToken) 21 | { 22 | return await _dbContext.Set().FirstOrDefaultAsync(a => a.Id == id, cancellationToken); 23 | } 24 | 25 | public async Task> ListAllAsync(CancellationToken cancellationToken) 26 | { 27 | return await _dbContext.Set().ToListAsync(cancellationToken); 28 | } 29 | 30 | public async Task> ListByExpressionAsync(Expression> filter, 31 | CancellationToken cancellationToken) 32 | { 33 | return await _dbContext.Set() 34 | .Where(filter) 35 | .ToListAsync(cancellationToken); 36 | } 37 | 38 | /// 39 | public async Task> ListAllAsync( 40 | int perPage, 41 | int page, 42 | CancellationToken cancellationToken) 43 | { 44 | return await _dbContext.Set().Skip(perPage * (page - 1)).Take(perPage).ToListAsync(cancellationToken); 45 | } 46 | 47 | public async Task AddAsync(T entity, CancellationToken cancellationToken) 48 | { 49 | await _dbContext.Set().AddAsync(entity, cancellationToken); 50 | await _dbContext.SaveChangesAsync(cancellationToken); 51 | 52 | return entity; 53 | } 54 | 55 | public async Task UpdateAsync(T entity, CancellationToken cancellationToken) 56 | { 57 | _dbContext.Entry(entity).State = EntityState.Modified; 58 | await _dbContext.SaveChangesAsync(cancellationToken); 59 | } 60 | 61 | public async Task DeleteAsync(T entity, CancellationToken cancellationToken) 62 | { 63 | _dbContext.Set().Remove(entity); 64 | await _dbContext.SaveChangesAsync(cancellationToken); 65 | } 66 | } 67 | -------------------------------------------------------------------------------- /api_templates/BackendData/DataAccess/SeedData.cs: -------------------------------------------------------------------------------- 1 | using BackendData.Security; 2 | 3 | namespace BackendData.DataAccess; 4 | 5 | public static class SeedData 6 | { 7 | public static List Authors() 8 | { 9 | int id = 1; 10 | 11 | var authors = new List() 12 | { 13 | new Author 14 | { 15 | Id = id++, 16 | Name="Steve Smith", 17 | PluralsightUrl="https://www.pluralsight.com/authors/steve-smith", 18 | TwitterAlias="ardalis" 19 | }, 20 | new Author 21 | { 22 | Id = id++, 23 | Name="Julie Lerman", 24 | PluralsightUrl="https://www.pluralsight.com/authors/julie-lerman", 25 | TwitterAlias="julialerman" 26 | } 27 | }; 28 | 29 | return authors; 30 | } 31 | 32 | public static List Users() 33 | { 34 | int id = 1; 35 | 36 | var hasher = new PasswordHasher(); 37 | 38 | var users = new List 39 | { 40 | new User("test@test.com", hasher.HashPassword("123456")) { Id = id++} 41 | }; 42 | 43 | return users; 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /api_templates/BackendData/DomainModel/Author.cs: -------------------------------------------------------------------------------- 1 | namespace BackendData; 2 | 3 | public class Author : BaseEntity 4 | { 5 | public string Name { get; set; } = "New Author"; 6 | public string? PluralsightUrl { get; set; } 7 | public string? TwitterAlias { get; set; } 8 | } 9 | -------------------------------------------------------------------------------- /api_templates/BackendData/DomainModel/BaseEntity.cs: -------------------------------------------------------------------------------- 1 | namespace BackendData; 2 | 3 | public abstract class BaseEntity 4 | { 5 | public int Id { get; internal set; } 6 | } 7 | -------------------------------------------------------------------------------- /api_templates/BackendData/DomainModel/IAsyncRepository.cs: -------------------------------------------------------------------------------- 1 | using System.Linq.Expressions; 2 | 3 | namespace BackendData; 4 | 5 | /// 6 | /// Source: My reference app https://github.com/dotnet-architecture/eShopOnWeb 7 | /// Consider adding Ardalis.Specification if you implement this 8 | /// 9 | /// 10 | public interface IAsyncRepository where T : BaseEntity 11 | { 12 | Task GetByIdAsync(int id, CancellationToken cancellationToken); 13 | 14 | Task> ListAllAsync(CancellationToken cancellationToken); 15 | 16 | Task> ListAllAsync(int perPage, int page, CancellationToken cancellationToken); 17 | 18 | Task> ListByExpressionAsync(Expression> filter, CancellationToken cancellationToken); 19 | 20 | Task AddAsync(T entity, CancellationToken cancellationToken); 21 | 22 | Task UpdateAsync(T entity, CancellationToken cancellationToken); 23 | 24 | Task DeleteAsync(T entity, CancellationToken cancellationToken); 25 | } 26 | -------------------------------------------------------------------------------- /api_templates/BackendData/DomainModel/TwitterHelpers.cs: -------------------------------------------------------------------------------- 1 | using System.Text.RegularExpressions; 2 | using Ardalis.Result; 3 | 4 | namespace BackendData; 5 | 6 | public static class TwitterHelpers 7 | { 8 | public static Result ToAtPrefixFormat(string twitterAlias) 9 | { 10 | if (Regex.IsMatch(twitterAlias, "^@(\\w){ 1,15}$")) return twitterAlias; 11 | if (Regex.IsMatch(twitterAlias, "^(\\w){ 1,15}$")) return "@" + twitterAlias; 12 | if (twitterAlias.StartsWith("http://twitter.com") || 13 | twitterAlias.StartsWith("https://twitter.com")) 14 | { 15 | // grab the last part of the URL 16 | string lastPart = twitterAlias.Split('/').Last(); 17 | return "@" + lastPart; 18 | } 19 | return Result.Error("Input was not in a recognized format."); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /api_templates/BackendData/DomainModel/User.cs: -------------------------------------------------------------------------------- 1 | namespace BackendData; 2 | 3 | public class User : BaseEntity 4 | { 5 | public string Email { get; set; } 6 | public string Password { get; set; } 7 | 8 | public User(string email, string password) 9 | { 10 | Email = email; 11 | Password = password; 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /api_templates/BackendData/Migrations/20220717191514_AddUsers.Designer.cs: -------------------------------------------------------------------------------- 1 | // 2 | using BackendData.DataAccess; 3 | using Microsoft.EntityFrameworkCore; 4 | using Microsoft.EntityFrameworkCore.Infrastructure; 5 | using Microsoft.EntityFrameworkCore.Migrations; 6 | using Microsoft.EntityFrameworkCore.Storage.ValueConversion; 7 | 8 | #nullable disable 9 | 10 | namespace BackendData.Migrations 11 | { 12 | [DbContext(typeof(AppDbContext))] 13 | [Migration("20220717191514_AddUsers")] 14 | partial class AddUsers 15 | { 16 | protected override void BuildTargetModel(ModelBuilder modelBuilder) 17 | { 18 | #pragma warning disable 612, 618 19 | modelBuilder.HasAnnotation("ProductVersion", "6.0.3"); 20 | 21 | modelBuilder.Entity("BackendData.Author", b => 22 | { 23 | b.Property("Id") 24 | .ValueGeneratedOnAdd() 25 | .HasColumnType("INTEGER"); 26 | 27 | b.Property("Name") 28 | .IsRequired() 29 | .HasMaxLength(100) 30 | .HasColumnType("TEXT"); 31 | 32 | b.Property("PluralsightUrl") 33 | .HasMaxLength(255) 34 | .HasColumnType("TEXT"); 35 | 36 | b.Property("TwitterAlias") 37 | .HasMaxLength(100) 38 | .HasColumnType("TEXT"); 39 | 40 | b.HasKey("Id"); 41 | 42 | b.ToTable("Authors"); 43 | 44 | b.HasData( 45 | new 46 | { 47 | Id = 1, 48 | Name = "Steve Smith", 49 | PluralsightUrl = "https://www.pluralsight.com/authors/steve-smith", 50 | TwitterAlias = "ardalis" 51 | }, 52 | new 53 | { 54 | Id = 2, 55 | Name = "Julie Lerman", 56 | PluralsightUrl = "https://www.pluralsight.com/authors/julie-lerman", 57 | TwitterAlias = "julialerman" 58 | }); 59 | }); 60 | 61 | modelBuilder.Entity("BackendData.User", b => 62 | { 63 | b.Property("Id") 64 | .ValueGeneratedOnAdd() 65 | .HasColumnType("INTEGER"); 66 | 67 | b.Property("Email") 68 | .IsRequired() 69 | .HasMaxLength(100) 70 | .HasColumnType("TEXT"); 71 | 72 | b.Property("Password") 73 | .IsRequired() 74 | .HasMaxLength(100) 75 | .HasColumnType("TEXT"); 76 | 77 | b.HasKey("Id"); 78 | 79 | b.ToTable("Users"); 80 | }); 81 | #pragma warning restore 612, 618 82 | } 83 | } 84 | } 85 | -------------------------------------------------------------------------------- /api_templates/BackendData/Migrations/20220717191514_AddUsers.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.EntityFrameworkCore.Migrations; 2 | 3 | #nullable disable 4 | 5 | namespace BackendData.Migrations 6 | { 7 | public partial class AddUsers : Migration 8 | { 9 | protected override void Up(MigrationBuilder migrationBuilder) 10 | { 11 | migrationBuilder.CreateTable( 12 | name: "Authors", 13 | columns: table => new 14 | { 15 | Id = table.Column(type: "INTEGER", nullable: false) 16 | .Annotation("Sqlite:Autoincrement", true), 17 | Name = table.Column(type: "TEXT", maxLength: 100, nullable: false), 18 | PluralsightUrl = table.Column(type: "TEXT", maxLength: 255, nullable: true), 19 | TwitterAlias = table.Column(type: "TEXT", maxLength: 100, nullable: true) 20 | }, 21 | constraints: table => 22 | { 23 | table.PrimaryKey("PK_Authors", x => x.Id); 24 | }); 25 | 26 | migrationBuilder.CreateTable( 27 | name: "Users", 28 | columns: table => new 29 | { 30 | Id = table.Column(type: "INTEGER", nullable: false) 31 | .Annotation("Sqlite:Autoincrement", true), 32 | Email = table.Column(type: "TEXT", maxLength: 100, nullable: false), 33 | Password = table.Column(type: "TEXT", maxLength: 100, nullable: false) 34 | }, 35 | constraints: table => 36 | { 37 | table.PrimaryKey("PK_Users", x => x.Id); 38 | }); 39 | 40 | migrationBuilder.InsertData( 41 | table: "Authors", 42 | columns: new[] { "Id", "Name", "PluralsightUrl", "TwitterAlias" }, 43 | values: new object[] { 1, "Steve Smith", "https://www.pluralsight.com/authors/steve-smith", "ardalis" }); 44 | 45 | migrationBuilder.InsertData( 46 | table: "Authors", 47 | columns: new[] { "Id", "Name", "PluralsightUrl", "TwitterAlias" }, 48 | values: new object[] { 2, "Julie Lerman", "https://www.pluralsight.com/authors/julie-lerman", "julialerman" }); 49 | } 50 | 51 | protected override void Down(MigrationBuilder migrationBuilder) 52 | { 53 | migrationBuilder.DropTable( 54 | name: "Authors"); 55 | 56 | migrationBuilder.DropTable( 57 | name: "Users"); 58 | } 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /api_templates/BackendData/Migrations/AppDbContextModelSnapshot.cs: -------------------------------------------------------------------------------- 1 | // 2 | using BackendData.DataAccess; 3 | using Microsoft.EntityFrameworkCore; 4 | using Microsoft.EntityFrameworkCore.Infrastructure; 5 | using Microsoft.EntityFrameworkCore.Storage.ValueConversion; 6 | 7 | #nullable disable 8 | 9 | namespace BackendData.Migrations 10 | { 11 | [DbContext(typeof(AppDbContext))] 12 | partial class AppDbContextModelSnapshot : ModelSnapshot 13 | { 14 | protected override void BuildModel(ModelBuilder modelBuilder) 15 | { 16 | #pragma warning disable 612, 618 17 | modelBuilder.HasAnnotation("ProductVersion", "6.0.3"); 18 | 19 | modelBuilder.Entity("BackendData.Author", b => 20 | { 21 | b.Property("Id") 22 | .ValueGeneratedOnAdd() 23 | .HasColumnType("INTEGER"); 24 | 25 | b.Property("Name") 26 | .IsRequired() 27 | .HasMaxLength(100) 28 | .HasColumnType("TEXT"); 29 | 30 | b.Property("PluralsightUrl") 31 | .HasMaxLength(255) 32 | .HasColumnType("TEXT"); 33 | 34 | b.Property("TwitterAlias") 35 | .HasMaxLength(100) 36 | .HasColumnType("TEXT"); 37 | 38 | b.HasKey("Id"); 39 | 40 | b.ToTable("Authors"); 41 | 42 | b.HasData( 43 | new 44 | { 45 | Id = 1, 46 | Name = "Steve Smith", 47 | PluralsightUrl = "https://www.pluralsight.com/authors/steve-smith", 48 | TwitterAlias = "ardalis" 49 | }, 50 | new 51 | { 52 | Id = 2, 53 | Name = "Julie Lerman", 54 | PluralsightUrl = "https://www.pluralsight.com/authors/julie-lerman", 55 | TwitterAlias = "julialerman" 56 | }); 57 | }); 58 | 59 | modelBuilder.Entity("BackendData.User", b => 60 | { 61 | b.Property("Id") 62 | .ValueGeneratedOnAdd() 63 | .HasColumnType("INTEGER"); 64 | 65 | b.Property("Email") 66 | .IsRequired() 67 | .HasMaxLength(100) 68 | .HasColumnType("TEXT"); 69 | 70 | b.Property("Password") 71 | .IsRequired() 72 | .HasMaxLength(100) 73 | .HasColumnType("TEXT"); 74 | 75 | b.HasKey("Id"); 76 | 77 | b.ToTable("Users"); 78 | }); 79 | #pragma warning restore 612, 618 80 | } 81 | } 82 | } 83 | -------------------------------------------------------------------------------- /api_templates/BackendData/Security/AccessToken.cs: -------------------------------------------------------------------------------- 1 | namespace BackendData.Security; 2 | 3 | public class AccessToken : JsonWebToken 4 | { 5 | public AccessToken(string tokenString, long expiration) : 6 | base(tokenString, expiration) 7 | { 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /api_templates/BackendData/Security/IPasswordHasher.cs: -------------------------------------------------------------------------------- 1 | namespace BackendData.Security; 2 | 3 | public interface IPasswordHasher 4 | { 5 | string HashPassword(string password); 6 | bool PasswordMatches(string providedPassword, string passwordHash); 7 | } 8 | -------------------------------------------------------------------------------- /api_templates/BackendData/Security/ITokenFactory.cs: -------------------------------------------------------------------------------- 1 | namespace BackendData.Security; 2 | 3 | public interface ITokenFactory 4 | { 5 | AccessToken CreateAccessToken(User user); 6 | } 7 | -------------------------------------------------------------------------------- /api_templates/BackendData/Security/JsonWebToken.cs: -------------------------------------------------------------------------------- 1 | namespace BackendData.Security; 2 | 3 | public abstract class JsonWebToken 4 | { 5 | public string TokenString { get; protected set; } 6 | public long Expiration { get; protected set; } 7 | 8 | public JsonWebToken(string tokenString, long expiration) 9 | { 10 | if (string.IsNullOrWhiteSpace(tokenString)) 11 | throw new ArgumentException("Invalid token."); 12 | 13 | if (expiration <= 0) 14 | throw new ArgumentException("Invalid expiration."); 15 | 16 | TokenString = tokenString; 17 | Expiration = expiration; 18 | } 19 | 20 | public bool IsExpired() => DateTime.UtcNow.Ticks > Expiration; 21 | } 22 | -------------------------------------------------------------------------------- /api_templates/BackendData/Security/PasswordHasher.cs: -------------------------------------------------------------------------------- 1 | using System.Runtime.CompilerServices; 2 | using System.Security.Cryptography; 3 | 4 | namespace BackendData.Security; 5 | 6 | /// 7 | /// This password hasher is the same used by ASP.NET Identity. 8 | /// Explanation: https://stackoverflow.com/questions/20621950/asp-net-identity-default-password-hasher-how-does-it-work-and-is-it-secure 9 | /// Full implementation: https://gist.github.com/malkafly/e873228cb9515010bdbe 10 | /// 11 | public class PasswordHasher : IPasswordHasher 12 | { 13 | public string HashPassword(string password) 14 | { 15 | byte[] salt; 16 | byte[] buffer2; 17 | if (string.IsNullOrEmpty(password)) 18 | { 19 | throw new ArgumentNullException("password"); 20 | } 21 | using (var bytes = new Rfc2898DeriveBytes(password, 0x10, 0x3e8)) 22 | { 23 | salt = bytes.Salt; 24 | buffer2 = bytes.GetBytes(0x20); 25 | } 26 | var dst = new byte[0x31]; 27 | Buffer.BlockCopy(salt, 0, dst, 1, 0x10); 28 | Buffer.BlockCopy(buffer2, 0, dst, 0x11, 0x20); 29 | return Convert.ToBase64String(dst); 30 | } 31 | 32 | public bool PasswordMatches(string providedPassword, string passwordHash) 33 | { 34 | byte[] buffer4; 35 | if (passwordHash == null) 36 | { 37 | return false; 38 | } 39 | if (providedPassword == null) 40 | { 41 | throw new ArgumentNullException("providedPassword"); 42 | } 43 | var src = Convert.FromBase64String(passwordHash); 44 | if (src.Length != 0x31 || src[0] != 0) 45 | { 46 | return false; 47 | } 48 | var dst = new byte[0x10]; 49 | Buffer.BlockCopy(src, 1, dst, 0, 0x10); 50 | var buffer3 = new byte[0x20]; 51 | Buffer.BlockCopy(src, 0x11, buffer3, 0, 0x20); 52 | using (var bytes = new Rfc2898DeriveBytes(providedPassword, dst, 0x3e8)) 53 | { 54 | buffer4 = bytes.GetBytes(0x20); 55 | } 56 | return ByteArraysEqual(buffer3, buffer4); 57 | } 58 | 59 | [MethodImpl(MethodImplOptions.NoOptimization)] 60 | private bool ByteArraysEqual(byte[] a, byte[] b) 61 | { 62 | if (ReferenceEquals(a, b)) 63 | { 64 | return true; 65 | } 66 | 67 | if (a == null || b == null || a.Length != b.Length) 68 | { 69 | return false; 70 | } 71 | 72 | var areSame = true; 73 | for (var i = 0; i < a.Length; i++) 74 | { 75 | areSame &= a[i] == b[i]; 76 | } 77 | return areSame; 78 | } 79 | } 80 | -------------------------------------------------------------------------------- /api_templates/BackendData/Security/SigningConfigurations.cs: -------------------------------------------------------------------------------- 1 | using System.Text; 2 | using Microsoft.IdentityModel.Tokens; 3 | 4 | namespace BackendData.Security; 5 | 6 | public class SigningConfigurations 7 | { 8 | public SecurityKey SecurityKey { get; } 9 | public SigningCredentials SigningCredentials { get; } 10 | 11 | public SigningConfigurations(string key) 12 | { 13 | var keyBytes = Encoding.ASCII.GetBytes(key); 14 | 15 | SecurityKey = new SymmetricSecurityKey(keyBytes); 16 | SigningCredentials = new SigningCredentials(SecurityKey, SecurityAlgorithms.HmacSha256Signature); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /api_templates/BackendData/Security/TokenFactory.cs: -------------------------------------------------------------------------------- 1 | using System.IdentityModel.Tokens.Jwt; 2 | using System.Security.Claims; 3 | using Microsoft.Extensions.Options; 4 | 5 | namespace BackendData.Security; 6 | 7 | 8 | public class TokenFactory : ITokenFactory 9 | { 10 | private readonly TokenOptions _tokenOptions; 11 | private readonly SigningConfigurations _signingConfigurations; 12 | 13 | public TokenFactory(IOptions tokenOptionsSnapshot, 14 | SigningConfigurations signingConfigurations) 15 | { 16 | _tokenOptions = tokenOptionsSnapshot.Value; 17 | _signingConfigurations = signingConfigurations; 18 | } 19 | public AccessToken CreateAccessToken(User user) 20 | { 21 | return BuildAccessToken(user); 22 | } 23 | 24 | private AccessToken BuildAccessToken(User user) 25 | { 26 | var tokenExpiration = DateTime.UtcNow.AddSeconds(_tokenOptions.AccessTokenExpiration); 27 | 28 | var securityToken = new JwtSecurityToken 29 | ( 30 | issuer: _tokenOptions.Issuer, 31 | audience: _tokenOptions.Audience, 32 | claims: GetClaims(user), 33 | expires: tokenExpiration, 34 | notBefore: DateTime.UtcNow, 35 | signingCredentials: _signingConfigurations.SigningCredentials 36 | ); 37 | 38 | var handler = new JwtSecurityTokenHandler(); 39 | var accessToken = handler.WriteToken(securityToken); 40 | 41 | return new AccessToken(accessToken, tokenExpiration.Ticks); 42 | } 43 | 44 | private IEnumerable GetClaims(User user) 45 | { 46 | var claims = new List 47 | { 48 | new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()), 49 | new Claim(JwtRegisteredClaimNames.Sub, user.Email) 50 | }; 51 | 52 | //foreach (var userRole in user.UserRoles) 53 | //{ 54 | // claims.Add(new Claim(ClaimTypes.Role, userRole.Role.Name)); 55 | //} 56 | 57 | return claims; 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /api_templates/BackendData/Security/TokenOptions.cs: -------------------------------------------------------------------------------- 1 | namespace BackendData.Security; 2 | 3 | public class TokenOptions 4 | { 5 | public string Audience { get; set; } = String.Empty; 6 | public string Issuer { get; set; } = String.Empty; 7 | public long AccessTokenExpiration { get; set; } 8 | public string Secret { get; set; } = String.Empty; 9 | } 10 | -------------------------------------------------------------------------------- /api_templates/BackendData/Services/AuthenticationService.cs: -------------------------------------------------------------------------------- 1 | using Ardalis.Result; 2 | using BackendData.Security; 3 | 4 | namespace BackendData.Services; 5 | public class AuthenticationService : IAuthenticationService 6 | { 7 | private readonly IAsyncRepository _repository; 8 | private readonly IPasswordHasher _passwordHasher; 9 | private readonly ITokenFactory _tokenFactory; 10 | 11 | public AuthenticationService(IAsyncRepository repository, 12 | IPasswordHasher passwordHasher, 13 | ITokenFactory tokenFactory) 14 | { 15 | _repository = repository; 16 | _passwordHasher = passwordHasher; 17 | _tokenFactory = tokenFactory; 18 | } 19 | 20 | public async Task> CreateAccessTokenAsync(string email, string password, 21 | CancellationToken cancellationToken) 22 | { 23 | var hashedPassword = _passwordHasher.HashPassword(password); 24 | 25 | var users = await _repository.ListAllAsync(cancellationToken); 26 | 27 | var user = (await _repository 28 | .ListByExpressionAsync(u => u.Email == email, cancellationToken)) 29 | .FirstOrDefault(); 30 | 31 | if (user == null || !_passwordHasher.PasswordMatches(password, user.Password)) return Result.NotFound(); 32 | 33 | return _tokenFactory.CreateAccessToken(user); 34 | } 35 | 36 | } 37 | 38 | -------------------------------------------------------------------------------- /api_templates/BackendData/Services/IAuthenticationService.cs: -------------------------------------------------------------------------------- 1 | using Ardalis.Result; 2 | using BackendData.Security; 3 | 4 | namespace BackendData.Services; 5 | 6 | public interface IAuthenticationService 7 | { 8 | Task> CreateAccessTokenAsync(string email, string password, CancellationToken cancellationToken); 9 | } 10 | 11 | -------------------------------------------------------------------------------- /api_templates/BackendData/database.sqlite: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ardalis/WebApiBestPractices/e072d99989c11e05eb07c7d6ac4e2778f7e0f63a/api_templates/BackendData/database.sqlite -------------------------------------------------------------------------------- /api_templates/controllers/ApiModels/AuthorDto.cs: -------------------------------------------------------------------------------- 1 | namespace controllers.ApiModels 2 | { 3 | // records don't work with XML serialization - requires parameterless constructor 4 | //public record AuthorDto(int Id, string Name, string TwitterAlias); 5 | 6 | [Serializable] 7 | public class AuthorDto 8 | { 9 | public int Id { get; set; } 10 | public string Name { get; set; } 11 | public string TwitterAlias { get; set; } 12 | 13 | public AuthorDto() 14 | { 15 | } 16 | 17 | public AuthorDto(int id, string name, string twitterAlias) 18 | { 19 | Id = id; 20 | Name = name; 21 | TwitterAlias = twitterAlias; 22 | } 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /api_templates/controllers/ApiModels/BookDto.cs: -------------------------------------------------------------------------------- 1 | namespace controllers.ApiModels; 2 | 3 | //public record BookDto(int id, string ISBN, string Title, string Author); 4 | 5 | public class BookDto 6 | { 7 | public int Id { get; set; } 8 | public string ISBN { get; set; } 9 | public string Title { get; set; } 10 | public string Author { get; set; } 11 | 12 | public BookDto() 13 | { 14 | } 15 | 16 | public BookDto(int id, string iSBN, string title, string author) 17 | { 18 | Id = id; 19 | ISBN = iSBN; 20 | Title = title; 21 | Author = author; 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /api_templates/controllers/Controllers/AuthorsController.cs: -------------------------------------------------------------------------------- 1 | using BackendData; 2 | using controllers.ApiModels; 3 | using Microsoft.AspNetCore.Mvc; 4 | 5 | namespace controllers.Controllers; 6 | 7 | [ApiController] 8 | [Route("Authors")] 9 | public class AuthorsController : ControllerBase 10 | { 11 | private readonly ILogger _logger; 12 | private readonly IAsyncRepository _authorRepository; 13 | 14 | public AuthorsController(ILogger logger, 15 | IAsyncRepository authorRepository) 16 | { 17 | _logger = logger; 18 | _authorRepository = authorRepository; 19 | } 20 | 21 | #region Other actions 22 | [HttpGet] 23 | [ResponseCache(Duration = 10, Location = ResponseCacheLocation.Any, VaryByQueryKeys = new[] { "*" })] 24 | // NOTE: VaryByQueryKeys requires adding Response Cache Middleware (and services) 25 | public async Task>> Index(CancellationToken cancellationToken) 26 | { 27 | _logger.LogInformation("Returning Author List from /Authors."); 28 | 29 | var authors = await _authorRepository.ListAllAsync(cancellationToken); 30 | 31 | var responseModel = authors 32 | .Select(a => new AuthorDto(a.Id, a.Name, a.TwitterAlias ?? "")) 33 | .ToList(); 34 | 35 | return Ok(responseModel); 36 | } 37 | #endregion 38 | 39 | [HttpPost] 40 | [ProducesResponseType(StatusCodes.Status201Created, Type = typeof(AuthorDto))] 41 | public async Task> Create(AuthorDto newAuthor, 42 | CancellationToken cancellationToken) 43 | { 44 | var author = new Author 45 | { 46 | Name = newAuthor.Name, 47 | TwitterAlias = newAuthor.TwitterAlias 48 | }; 49 | 50 | await _authorRepository.AddAsync(author, cancellationToken); 51 | 52 | var authorDto = new AuthorDto(author.Id, author.Name, author.TwitterAlias); 53 | return Created($"authors/{author.Id}", authorDto); 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /api_templates/controllers/Controllers/AuthorsUsingMediatrController.cs: -------------------------------------------------------------------------------- 1 | using controllers.ApiModels; 2 | using controllers.Handlers; 3 | using MediatR; 4 | using Microsoft.AspNetCore.Mvc; 5 | 6 | namespace controllers.Controllers; 7 | 8 | // SHOW USING MEDIATR INSTEAD OF A REPOSITORY OR SERVICE 9 | 10 | [ApiController] 11 | [Route("AuthorsUsingMediatr")] 12 | public class AuthorsUsingMediatrController : ControllerBase 13 | { 14 | public AuthorsUsingMediatrController(IMediator mediator) 15 | { 16 | Mediator = mediator; 17 | } 18 | 19 | public IMediator Mediator { get; } 20 | 21 | [HttpPost()] 22 | [ProducesResponseType(StatusCodes.Status201Created, Type = typeof(AuthorDto))] 23 | public async Task> Create(AuthorDto newAuthor, 24 | CancellationToken cancellationToken) 25 | { 26 | var createAuthorCommand = new CreateAuthorCommand(newAuthor.Name, newAuthor.TwitterAlias); 27 | var createdAuthorDto = await Mediator.Send(createAuthorCommand, cancellationToken); 28 | return Created($"authors/{createdAuthorDto.Id}", createdAuthorDto); 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /api_templates/controllers/Controllers/AuthorsUsingMediatrFromBaseController.cs: -------------------------------------------------------------------------------- 1 | using controllers.ApiModels; 2 | using controllers.Handlers; 3 | using MediatR; 4 | using Microsoft.AspNetCore.Mvc; 5 | 6 | namespace controllers.Controllers; 7 | 8 | // SHOW USING MEDIATR FROM BASE INSTEAD OF A REPOSITORY OR SERVICE 9 | 10 | [ApiController] 11 | public abstract class MyBaseApiController : ControllerBase 12 | { 13 | // this requires a third party DI tool like Autofac and adding .AddControllersAsServices in Program.cs 14 | public IMediator Mediator { get; set; } 15 | } 16 | 17 | [Route("AuthorsUsingMediatrFromBase")] 18 | public class AuthorsUsingMediatrFromBaseController : MyBaseApiController 19 | { 20 | [HttpPost()] 21 | [ProducesResponseType(StatusCodes.Status201Created, Type = typeof(AuthorDto))] 22 | public async Task> Create(CreateAuthorCommand newAuthorCommand, 23 | CancellationToken cancellationToken) 24 | { 25 | //var createAuthorCommand = new CreateAuthorCommand(newAuthor.Name, newAuthor.TwitterAlias); 26 | var createdAuthorDto = await Mediator.Send(newAuthorCommand, cancellationToken); 27 | return Created($"authors/{createdAuthorDto.Id}", createdAuthorDto); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /api_templates/controllers/Controllers/AuthorsUsingServiceController.cs: -------------------------------------------------------------------------------- 1 | using controllers.ApiModels; 2 | using controllers.Interfaces; 3 | using Microsoft.AspNetCore.Mvc; 4 | 5 | namespace controllers.Controllers; 6 | 7 | // SHOW USING A SERVICE INSTEAD OF A REPOSITORY IN ACTION METHOD 8 | 9 | [ApiController] 10 | [Route("AuthorsUsingService")] 11 | public class AuthorsUsingServiceController : ControllerBase 12 | { 13 | private readonly IAuthorService _authorService; 14 | 15 | public AuthorsUsingServiceController(IAuthorService authorService) 16 | { 17 | _authorService = authorService; 18 | } 19 | 20 | [HttpPost()] 21 | [ProducesResponseType(StatusCodes.Status201Created, Type = typeof(AuthorDto))] 22 | public async Task> Create(AuthorDto newAuthor, 23 | CancellationToken cancellationToken) 24 | { 25 | var createdAuthorDto = _authorService.CreateAndSave(newAuthor, cancellationToken); 26 | return Created($"authors/{createdAuthorDto.Id}", createdAuthorDto); 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /api_templates/controllers/Controllers/DemoController.cs: -------------------------------------------------------------------------------- 1 | using System.Text.Json; 2 | using controllers.ApiModels; 3 | using Microsoft.AspNetCore.Mvc; 4 | 5 | namespace controllers.Controllers; 6 | 7 | [ApiController] 8 | [Route("Demo")] 9 | public class DemoController : ControllerBase 10 | { 11 | // different methods that return an author 12 | 13 | [HttpGet("getobject")] 14 | public object GetObject() 15 | { 16 | return GetBook(); 17 | } 18 | 19 | // returns a 204 no content with no body 20 | // response type header is not set 21 | [HttpGet("getobjectnull")] 22 | public object GetObjectNull() 23 | { 24 | return null; 25 | } 26 | 27 | // will set response type to text/plain 28 | [HttpGet("getstring")] 29 | public string GetString() 30 | { 31 | return JsonSerializer.Serialize(GetBook()); 32 | } 33 | 34 | [HttpGet("getjson")] 35 | public JsonResult GetJson() 36 | { 37 | return new JsonResult(GetBook()); 38 | } 39 | 40 | [HttpGet("getiactionresult")] 41 | public IActionResult GetIActionResult() 42 | { 43 | return Ok(GetBook()); 44 | } 45 | 46 | [HttpGet("getiactionresult")] 47 | public ActionResult GetActionResultOfT() 48 | { 49 | return Ok(GetBook()); 50 | } 51 | 52 | private BookDto GetBook() 53 | { 54 | return new BookDto(1, "1234-5678", "Warren Piece", "Steve Smith"); 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /api_templates/controllers/Controllers/HomeController.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Diagnostics; 2 | using Microsoft.AspNetCore.Mvc; 3 | 4 | namespace controllers.Controllers; 5 | 6 | public class HomeController : ControllerBase 7 | { 8 | [ApiExplorerSettings(IgnoreApi = true)] 9 | [Route("/error")] 10 | public IActionResult HandleError() => 11 | Problem(); 12 | 13 | [ApiExplorerSettings(IgnoreApi = true)] 14 | [Route("/error-development")] 15 | public IActionResult HandleErrorDevelopment( 16 | [FromServices] IHostEnvironment hostEnvironment) 17 | { 18 | if (!hostEnvironment.IsDevelopment()) 19 | { 20 | return NotFound(); 21 | } 22 | 23 | var exceptionHandlerFeature = 24 | HttpContext.Features.Get()!; 25 | 26 | return Problem( 27 | detail: exceptionHandlerFeature.Error.StackTrace, 28 | title: exceptionHandlerFeature.Error.Message); 29 | } 30 | 31 | // sample endpoint that throws 32 | [HttpGet("/throw")] 33 | public IActionResult Throw() => 34 | throw new Exception("Sample exception."); 35 | } 36 | -------------------------------------------------------------------------------- /api_templates/controllers/Handlers/CreateAuthorHandler.cs: -------------------------------------------------------------------------------- 1 | using controllers.ApiModels; 2 | using controllers.Interfaces; 3 | using MediatR; 4 | 5 | namespace controllers.Handlers; 6 | 7 | public class CreateAuthorCommand : IRequest 8 | { 9 | public CreateAuthorCommand(string name, string twitterAlias) 10 | { 11 | Name = name; 12 | TwitterAlias = twitterAlias; 13 | } 14 | 15 | public string Name { get; } 16 | public string TwitterAlias { get; } 17 | } 18 | public class CreateAuthorHandler : IRequestHandler 19 | { 20 | private readonly IAuthorService _authorService; 21 | 22 | public CreateAuthorHandler(IAuthorService authorService) 23 | { 24 | _authorService = authorService; 25 | } 26 | 27 | public async Task Handle(CreateAuthorCommand request, CancellationToken cancellationToken) 28 | { 29 | var authorDto = new AuthorDto() { Name = request.Name, TwitterAlias = request.TwitterAlias }; 30 | return await _authorService.CreateAndSave(authorDto, cancellationToken); 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /api_templates/controllers/Interfaces/IAuthorService.cs: -------------------------------------------------------------------------------- 1 | using controllers.ApiModels; 2 | 3 | namespace controllers.Interfaces; 4 | 5 | public interface IAuthorService 6 | { 7 | Task CreateAndSave(AuthorDto newAuthor, CancellationToken cancellationToken); 8 | } 9 | -------------------------------------------------------------------------------- /api_templates/controllers/Program.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | using Autofac; 3 | using Autofac.Extensions.DependencyInjection; 4 | using BackendData; 5 | using BackendData.DataAccess; 6 | using controllers.Controllers; 7 | using controllers.Interfaces; 8 | using controllers.Services; 9 | using MediatR; 10 | using Microsoft.EntityFrameworkCore; 11 | using Microsoft.OpenApi.Models; 12 | 13 | var builder = WebApplication.CreateBuilder(args); 14 | 15 | // Add services to the container. 16 | var connectionString = builder.Configuration.GetConnectionString("DefaultConnection") ?? "Data Source=database.sqlite;Cache=Shared"; 17 | builder.Services.AddSqlite(connectionString); 18 | builder.Services.AddScoped(typeof(IAsyncRepository<>), typeof(EfRepository<>)); 19 | 20 | builder.Services.AddResponseCaching(); 21 | 22 | builder.Services.AddControllers(options => 23 | { 24 | options.RespectBrowserAcceptHeader = true; 25 | }).AddXmlSerializerFormatters() 26 | .AddControllersAsServices(); 27 | 28 | builder.Services.AddSwaggerGen(c => 29 | { 30 | c.SwaggerDoc("v1", new OpenApiInfo { Title = "Controller-based API Sample", Version = "v1" }); 31 | }); 32 | 33 | // add application services 34 | builder.Services.AddScoped(); 35 | builder.Services.AddMediatR(config => config.RegisterServicesFromAssembly(typeof(IAuthorService).Assembly)); 36 | 37 | // configure autofac - necessary for MediatR property on base controller class example 38 | builder.Host.UseServiceProviderFactory(new AutofacServiceProviderFactory()); 39 | builder.Host.ConfigureContainer(containerBuilder => 40 | { 41 | // configure all controllers that inherit from MyBaseApiController to have properties injected 42 | containerBuilder.RegisterAssemblyTypes(Assembly.GetExecutingAssembly()) 43 | .Where(t => t.IsSubclassOf(typeof(MyBaseApiController))) 44 | .PropertiesAutowired(); 45 | }); 46 | 47 | var app = builder.Build(); 48 | 49 | await EnsureDb(app.Services, app.Logger); 50 | 51 | // Configure the HTTP request pipeline. 52 | if (app.Environment.IsDevelopment()) 53 | { 54 | app.UseExceptionHandler("/error-development"); 55 | app.UseSwagger(); 56 | app.UseSwaggerUI(); 57 | } 58 | 59 | if (!app.Environment.IsDevelopment()) 60 | { 61 | app.UseExceptionHandler("/error"); 62 | app.UseHsts(); 63 | } 64 | 65 | app.UseHttpsRedirection(); 66 | app.UseStaticFiles(); 67 | 68 | app.UseRouting(); 69 | 70 | app.UseResponseCaching(); 71 | 72 | app.UseAuthorization(); 73 | 74 | app.UseEndpoints(endpoints => endpoints.MapControllers()); 75 | 76 | app.Run(); 77 | 78 | async Task EnsureDb(IServiceProvider services, ILogger logger) 79 | { 80 | using var db = services.CreateScope().ServiceProvider.GetRequiredService(); 81 | if (db.Database.IsRelational()) 82 | { 83 | logger.LogInformation("Ensuring database exists and is up to date at connection string '{connectionString}'", connectionString); 84 | await db.Database.MigrateAsync(); 85 | } 86 | } 87 | -------------------------------------------------------------------------------- /api_templates/controllers/Properties/launchSettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "iisSettings": { 3 | "windowsAuthentication": false, 4 | "anonymousAuthentication": true, 5 | "iisExpress": { 6 | "applicationUrl": "http://localhost:64494", 7 | "sslPort": 44382 8 | } 9 | }, 10 | "profiles": { 11 | "controllers - DEV": { 12 | "commandName": "Project", 13 | "dotnetRunMessages": true, 14 | "launchBrowser": true, 15 | "applicationUrl": "https://localhost:7218;http://localhost:5150", 16 | "environmentVariables": { 17 | "ASPNETCORE_ENVIRONMENT": "Development" 18 | } 19 | }, 20 | "controllers - PROD": { 21 | "commandName": "Project", 22 | "dotnetRunMessages": true, 23 | "launchBrowser": true, 24 | "applicationUrl": "https://localhost:7218;http://localhost:5150", 25 | "environmentVariables": { 26 | "ASPNETCORE_ENVIRONMENT": "Production" 27 | } 28 | }, 29 | "IIS Express": { 30 | "commandName": "IISExpress", 31 | "launchBrowser": true, 32 | "environmentVariables": { 33 | "ASPNETCORE_ENVIRONMENT": "Development" 34 | } 35 | } 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /api_templates/controllers/Services/AuthorService.cs: -------------------------------------------------------------------------------- 1 | using BackendData; 2 | using controllers.ApiModels; 3 | using controllers.Interfaces; 4 | 5 | namespace controllers.Services; 6 | 7 | public class AuthorService : IAuthorService 8 | { 9 | private readonly ILogger _logger; 10 | private readonly IAsyncRepository _authorRepository; 11 | 12 | public AuthorService(ILogger logger, 13 | IAsyncRepository authorRepository) 14 | { 15 | _logger = logger; 16 | _authorRepository = authorRepository; 17 | } 18 | 19 | public async Task CreateAndSave(AuthorDto newAuthor, CancellationToken cancellationToken) 20 | { 21 | var author = new Author 22 | { 23 | Name = newAuthor.Name, 24 | TwitterAlias = newAuthor.TwitterAlias 25 | }; 26 | 27 | await _authorRepository.AddAsync(author, cancellationToken); 28 | 29 | return new AuthorDto(author.Id, author.Name, author.TwitterAlias); 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /api_templates/controllers/appsettings.Development.json: -------------------------------------------------------------------------------- 1 | { 2 | "Logging": { 3 | "LogLevel": { 4 | "Default": "Information", 5 | "Microsoft.AspNetCore": "Warning" 6 | } 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /api_templates/controllers/appsettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "Logging": { 3 | "LogLevel": { 4 | "Default": "Information", 5 | "Microsoft.AspNetCore": "Warning" 6 | } 7 | }, 8 | "AllowedHosts": "*" 9 | } 10 | -------------------------------------------------------------------------------- /api_templates/controllers/controllers.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | net8.0 5 | enable 6 | enable 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | -------------------------------------------------------------------------------- /api_templates/controllers/database.sqlite-shm: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ardalis/WebApiBestPractices/e072d99989c11e05eb07c7d6ac4e2778f7e0f63a/api_templates/controllers/database.sqlite-shm -------------------------------------------------------------------------------- /api_templates/controllers/database.sqlite-wal: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ardalis/WebApiBestPractices/e072d99989c11e05eb07c7d6ac4e2778f7e0f63a/api_templates/controllers/database.sqlite-wal -------------------------------------------------------------------------------- /api_templates/fastendpoints/Authors/Create.cs: -------------------------------------------------------------------------------- 1 | using BackendData; 2 | using FastEndpoints; 3 | 4 | namespace FastEndpointsAPI.Authors; 5 | 6 | public class Create : Endpoint 7 | { 8 | private readonly IAsyncRepository _authorRepository; 9 | 10 | public Create(IAsyncRepository authorRepository) 11 | { 12 | _authorRepository = authorRepository; 13 | } 14 | 15 | public override void Configure() 16 | { 17 | Verbs(Http.POST); 18 | Routes("/authors"); 19 | AllowAnonymous(); 20 | } 21 | 22 | public override async Task HandleAsync(AuthorRequest req, CancellationToken cancellationToken) 23 | { 24 | var author = Map.ToEntity(req); 25 | 26 | await _authorRepository.AddAsync(author, cancellationToken); 27 | 28 | await SendAsync(new AuthorResponse() 29 | { 30 | Id = author.Id, 31 | Name = author.Name, 32 | TwitterAlias = author.TwitterAlias 33 | }); 34 | } 35 | 36 | public class AuthorRequest 37 | { 38 | public string Name { get; set; } 39 | public string TwitterAlias { get; set; } 40 | } 41 | public class AuthorResponse 42 | { 43 | public int Id { get; set; } 44 | public string Name { get; set; } 45 | public string TwitterAlias { get; set; } 46 | } 47 | 48 | public class AuthorMapper : Mapper 49 | { 50 | 51 | public override AuthorResponse FromEntity(Author e) 52 | { 53 | return new AuthorResponse() 54 | { 55 | Id = e.Id, 56 | Name = e.Name, 57 | TwitterAlias = e.TwitterAlias 58 | }; 59 | } 60 | 61 | public override Author ToEntity(AuthorRequest r) 62 | { 63 | return new Author 64 | { 65 | Name = r.Name, 66 | TwitterAlias = r.TwitterAlias 67 | }; 68 | 69 | } 70 | } 71 | } 72 | -------------------------------------------------------------------------------- /api_templates/fastendpoints/FastEndpointsAPI.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | net8.0 5 | enable 6 | enable 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | -------------------------------------------------------------------------------- /api_templates/fastendpoints/Program.cs: -------------------------------------------------------------------------------- 1 | using BackendData; 2 | using BackendData.DataAccess; 3 | using FastEndpoints; 4 | using Microsoft.Data.Sqlite; 5 | using Microsoft.EntityFrameworkCore; 6 | 7 | var builder = WebApplication.CreateBuilder(args); 8 | 9 | var connectionString = builder.Configuration.GetConnectionString("DefaultConnection") ?? "Data Source=database.sqlite;Cache=Shared"; 10 | var connection = new SqliteConnection(connectionString); 11 | connection.Open(); 12 | 13 | // Add services to the container. 14 | builder.Services.AddFastEndpoints(); 15 | builder.Services.AddDbContext(options => 16 | options.UseSqlite(connection)); // will be created in web project root 17 | builder.Services.AddScoped(typeof(IAsyncRepository<>), typeof(EfRepository<>)); 18 | 19 | builder.Services.AddEndpointsApiExplorer(); 20 | builder.Services.AddSwaggerGen(); 21 | 22 | var app = builder.Build(); 23 | 24 | await EnsureDb(app.Services, app.Logger); 25 | 26 | // Configure the HTTP request pipeline. 27 | if (app.Environment.IsDevelopment()) 28 | { 29 | app.UseSwagger(); 30 | app.UseSwaggerUI(); 31 | } 32 | 33 | app.UseHttpsRedirection(); 34 | 35 | app.UseAuthorization(); 36 | app.UseFastEndpoints(); 37 | 38 | app.Run(); 39 | 40 | async Task EnsureDb(IServiceProvider services, ILogger logger) 41 | { 42 | using var db = services.CreateScope().ServiceProvider.GetRequiredService(); 43 | if (db.Database.IsRelational()) 44 | { 45 | logger.LogInformation("Ensuring database exists and is up to date at connection string '{connectionString}'", connectionString); 46 | await db.Database.MigrateAsync(); 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /api_templates/fastendpoints/Properties/launchSettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "https://json.schemastore.org/launchsettings.json", 3 | "iisSettings": { 4 | "windowsAuthentication": false, 5 | "anonymousAuthentication": true, 6 | "iisExpress": { 7 | "applicationUrl": "http://localhost:63000", 8 | "sslPort": 44309 9 | } 10 | }, 11 | "profiles": { 12 | "fastendpoints": { 13 | "commandName": "Project", 14 | "dotnetRunMessages": true, 15 | "launchBrowser": true, 16 | "launchUrl": "swagger", 17 | "applicationUrl": "https://localhost:7037;http://localhost:5064", 18 | "environmentVariables": { 19 | "ASPNETCORE_ENVIRONMENT": "Development" 20 | } 21 | }, 22 | "IIS Express": { 23 | "commandName": "IISExpress", 24 | "launchBrowser": true, 25 | "launchUrl": "swagger", 26 | "environmentVariables": { 27 | "ASPNETCORE_ENVIRONMENT": "Development" 28 | } 29 | } 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /api_templates/fastendpoints/appsettings.Development.json: -------------------------------------------------------------------------------- 1 | { 2 | "Logging": { 3 | "LogLevel": { 4 | "Default": "Information", 5 | "Microsoft.AspNetCore": "Warning" 6 | } 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /api_templates/fastendpoints/appsettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "Logging": { 3 | "LogLevel": { 4 | "Default": "Information", 5 | "Microsoft.AspNetCore": "Warning" 6 | } 7 | }, 8 | "AllowedHosts": "*" 9 | } 10 | -------------------------------------------------------------------------------- /api_templates/minimal/.vscode/launch.json: -------------------------------------------------------------------------------- 1 | { 2 | "version": "0.2.0", 3 | "configurations": [ 4 | { 5 | // Use IntelliSense to find out which attributes exist for C# debugging 6 | // Use hover for the description of the existing attributes 7 | // For further information visit https://github.com/OmniSharp/omnisharp-vscode/blob/master/debugger-launchjson.md 8 | "name": ".NET Core Launch (web)", 9 | "type": "coreclr", 10 | "request": "launch", 11 | "preLaunchTask": "build", 12 | // If you have changed target frameworks, make sure to update the program path. 13 | "program": "${workspaceFolder}/bin/Debug/net6.0/minimal.dll", 14 | "args": [], 15 | "cwd": "${workspaceFolder}", 16 | "stopAtEntry": false, 17 | // Enable launching a web browser when ASP.NET Core starts. For more information: https://aka.ms/VSCode-CS-LaunchJson-WebBrowser 18 | "serverReadyAction": { 19 | "action": "openExternally", 20 | "pattern": "\\bNow listening on:\\s+(https?://\\S+)", 21 | "uriFormat": "%s/swagger" 22 | }, 23 | "env": { 24 | "ASPNETCORE_ENVIRONMENT": "Development" 25 | }, 26 | "sourceFileMap": { 27 | "/Views": "${workspaceFolder}/Views" 28 | } 29 | }, 30 | { 31 | "name": ".NET Core Attach", 32 | "type": "coreclr", 33 | "request": "attach", 34 | "processId": "${command:pickProcess}" 35 | } 36 | ] 37 | } -------------------------------------------------------------------------------- /api_templates/minimal/.vscode/tasks.json: -------------------------------------------------------------------------------- 1 | { 2 | "version": "2.0.0", 3 | "tasks": [ 4 | { 5 | "label": "build", 6 | "command": "dotnet", 7 | "type": "process", 8 | "args": [ 9 | "build", 10 | "${workspaceFolder}/minimal.csproj", 11 | "/property:GenerateFullPaths=true", 12 | "/consoleloggerparameters:NoSummary" 13 | ], 14 | "problemMatcher": "$msCompile" 15 | }, 16 | { 17 | "label": "publish", 18 | "command": "dotnet", 19 | "type": "process", 20 | "args": [ 21 | "publish", 22 | "${workspaceFolder}/minimal.csproj", 23 | "/property:GenerateFullPaths=true", 24 | "/consoleloggerparameters:NoSummary" 25 | ], 26 | "problemMatcher": "$msCompile" 27 | }, 28 | { 29 | "label": "watch", 30 | "command": "dotnet", 31 | "type": "process", 32 | "args": [ 33 | "watch", 34 | "run", 35 | "${workspaceFolder}/minimal.csproj", 36 | "/property:GenerateFullPaths=true", 37 | "/consoleloggerparameters:NoSummary" 38 | ], 39 | "problemMatcher": "$msCompile" 40 | } 41 | ] 42 | } -------------------------------------------------------------------------------- /api_templates/minimal/AuthorDto.cs: -------------------------------------------------------------------------------- 1 | public class AuthorDto 2 | { 3 | public int Id { get; set; } 4 | public string Name { get; set; } 5 | public string TwitterAlias { get; set; } 6 | } 7 | -------------------------------------------------------------------------------- /api_templates/minimal/Authors/Create.cs: -------------------------------------------------------------------------------- 1 | using System.ComponentModel.DataAnnotations; 2 | using BackendData; 3 | using MinimalApi.Endpoint; 4 | 5 | namespace minimal.Authors; 6 | public class Create : IEndpoint 7 | { 8 | private IAsyncRepository _authorRepository; 9 | public void AddRoute(IEndpointRouteBuilder app) 10 | { 11 | app.MapPost("/authors", async (CreateAuthorRequest request, IAsyncRepository authorRepository) => 12 | { 13 | _authorRepository = authorRepository; 14 | return await HandleAsync(request); 15 | }) 16 | .Produces() 17 | .WithTags("AuthorsApi"); 18 | } 19 | 20 | public async Task HandleAsync(CreateAuthorRequest request) 21 | { 22 | var author = new Author() 23 | { 24 | Name = request.Name, 25 | TwitterAlias = request.TwitterAlias 26 | }; 27 | await _authorRepository.AddAsync(author, new CancellationToken()); 28 | var response = new AuthorCreatedResponse(author.Id, author.Name, author.TwitterAlias, author.PluralsightUrl); 29 | return Results.Created($"/authors/{author.Id}", response); 30 | } 31 | } 32 | 33 | // NOTE: Minimal APIs don't support model validation in version 6 34 | public record CreateAuthorRequest([Required]string Name, string TwitterAlias); 35 | public record AuthorCreatedResponse(int Id, string Name, string TwitterAlias, string PluralsightUrl); 36 | 37 | -------------------------------------------------------------------------------- /api_templates/minimal/Authors/UpdateAuthorExtension.cs: -------------------------------------------------------------------------------- 1 | using BackendData; 2 | using Swashbuckle.AspNetCore.Annotations; 3 | 4 | namespace minimal.Authors; 5 | 6 | public static class UpdateAuthorExtension 7 | { 8 | // use a static extension method to register endpoints 9 | // reference: http://www.binaryintellect.net/articles/f3dcbb45-fa8b-4e12-b284-f0cd2e5b2dcf.aspx 10 | public static void RegisterAuthorUpdateEndpoint(this WebApplication app) 11 | { 12 | app.MapPut("/authors/{id}", 13 | [SwaggerOperation( 14 | Summary = "Updates an author.", 15 | Description = "Updates an author, which must exist, otherwise NotFound is returned.")] 16 | [SwaggerResponse(200, "Success")] 17 | [SwaggerResponse(404, "Not Found")] 18 | async (IAsyncRepository repo, int id, AuthorDto updatedAuthor) => 19 | { 20 | if (await repo.GetByIdAsync(id, cancellationToken: default) is Author author) 21 | { 22 | author.Name = updatedAuthor.Name; 23 | author.TwitterAlias = updatedAuthor.TwitterAlias; 24 | await repo.UpdateAsync(author, cancellationToken: default); 25 | return Results.Ok(); 26 | } 27 | else return Results.NotFound(); 28 | }) 29 | .WithName("UpdateAuthor") 30 | .WithTags("AuthorsApi"); 31 | } 32 | } 33 | 34 | -------------------------------------------------------------------------------- /api_templates/minimal/Program.cs: -------------------------------------------------------------------------------- 1 | using BackendData; 2 | using BackendData.DataAccess; 3 | using Microsoft.EntityFrameworkCore; 4 | using MinimalApi.Endpoint.Extensions; 5 | using Swashbuckle.AspNetCore.Annotations; 6 | using minimal.Authors; 7 | 8 | var builder = WebApplication.CreateBuilder(args); 9 | 10 | // MinimalApi.Endpoint registration 11 | builder.Services.AddEndpoints(); 12 | 13 | // Add services to the container. 14 | var connectionString = builder.Configuration.GetConnectionString("DefaultConnection") ?? "Data Source=database.sqlite;Cache=Shared"; 15 | builder.Services.AddSqlite(connectionString); 16 | builder.Services.AddScoped(typeof(IAsyncRepository<>), typeof(EfRepository<>)); 17 | 18 | builder.Services.AddMvcCore(); // pull in default model binders 19 | 20 | // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle 21 | builder.Services.AddEndpointsApiExplorer(); 22 | // builder.Services.AddEndpointsMetadataProviderApiExplorer(); only needed in NET6 23 | builder.Services.AddSwaggerGen(config => config.EnableAnnotations()); 24 | 25 | builder.Services.AddAuthentication(); 26 | builder.Services.AddAuthorization(); 27 | var app = builder.Build(); 28 | 29 | await EnsureDb(app.Services, app.Logger); 30 | 31 | // Configure the HTTP request pipeline. 32 | if (app.Environment.IsDevelopment()) 33 | { 34 | app.UseSwagger(); 35 | app.UseSwaggerUI(); 36 | } 37 | else 38 | { 39 | app.UseExceptionHandler(new ExceptionHandlerOptions { ExceptionHandlingPath = "/error", 40 | AllowStatusCode404Response = true }); 41 | } 42 | app.UseHttpsRedirection(); 43 | 44 | app.UseAuthorization(); 45 | 46 | // for minimal endpoints 47 | app.MapEndpoints(); 48 | 49 | // extension method 50 | app.RegisterAuthorUpdateEndpoint(); 51 | 52 | // Using simple minimal APIs List Authors 53 | app.MapGet("/authors", async (AppDbContext db) => await db.Authors.ToListAsync()) 54 | .WithName("ListAuthors") 55 | .WithTags("AuthorsApi"); 56 | 57 | // Using simple minimal APIs to Delete an Author 58 | app.MapDelete("/authors/{id}", 59 | [SwaggerOperation( 60 | Summary = "Deletes an author.", 61 | Description = "Deletes an author, which must exist, otherwise NotFound is returned.")] 62 | [SwaggerResponse(204, "Success")] 63 | [SwaggerResponse(404, "Not Found")] 64 | async (IAsyncRepository repo, int id) => 65 | { 66 | var author = await repo.GetByIdAsync(id, cancellationToken: default); 67 | if (author == null) return Results.NotFound(); 68 | await repo.DeleteAsync(author, cancellationToken: default); 69 | return Results.NoContent(); 70 | }) 71 | .WithName("DeleteAuthor") 72 | .WithTags("AuthorsApi"); 73 | 74 | app.Run(); 75 | 76 | async Task EnsureDb(IServiceProvider services, ILogger logger) 77 | { 78 | using var db = services.CreateScope().ServiceProvider.GetRequiredService(); 79 | if (db.Database.IsRelational()) 80 | { 81 | logger.LogInformation("Ensuring database exists and is up to date at connection string '{connectionString}'", connectionString); 82 | await db.Database.MigrateAsync(); 83 | } 84 | } 85 | -------------------------------------------------------------------------------- /api_templates/minimal/Properties/launchSettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "https://json.schemastore.org/launchsettings.json", 3 | "iisSettings": { 4 | "windowsAuthentication": false, 5 | "anonymousAuthentication": true, 6 | "iisExpress": { 7 | "applicationUrl": "http://localhost:40694", 8 | "sslPort": 44328 9 | } 10 | }, 11 | "profiles": { 12 | "minimal": { 13 | "commandName": "Project", 14 | "dotnetRunMessages": true, 15 | "launchBrowser": true, 16 | "launchUrl": "swagger", 17 | "applicationUrl": "https://localhost:7053;http://localhost:5066", 18 | "environmentVariables": { 19 | "ASPNETCORE_ENVIRONMENT": "Development" 20 | } 21 | }, 22 | "IIS Express": { 23 | "commandName": "IISExpress", 24 | "launchBrowser": true, 25 | "launchUrl": "swagger", 26 | "environmentVariables": { 27 | "ASPNETCORE_ENVIRONMENT": "Development" 28 | } 29 | } 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /api_templates/minimal/appsettings.Development.json: -------------------------------------------------------------------------------- 1 | { 2 | "Logging": { 3 | "LogLevel": { 4 | "Default": "Information", 5 | "Microsoft.AspNetCore": "Warning" 6 | } 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /api_templates/minimal/appsettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "Logging": { 3 | "LogLevel": { 4 | "Default": "Information", 5 | "Microsoft.AspNetCore": "Warning" 6 | } 7 | }, 8 | "AllowedHosts": "*" 9 | } 10 | -------------------------------------------------------------------------------- /api_templates/minimal/minimal.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | net8.0 5 | enable 6 | enable 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | -------------------------------------------------------------------------------- /demos.zip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ardalis/WebApiBestPractices/e072d99989c11e05eb07c7d6ac4e2778f7e0f63a/demos.zip -------------------------------------------------------------------------------- /demos2022.zip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ardalis/WebApiBestPractices/e072d99989c11e05eb07c7d6ac4e2778f7e0f63a/demos2022.zip -------------------------------------------------------------------------------- /securing_apis/Imperative/Imperative.sln: -------------------------------------------------------------------------------- 1 | 2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio Version 17 4 | VisualStudioVersion = 17.2.32602.215 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "OwnerPermissions", "OwnerPermissions\OwnerPermissions.csproj", "{69C3990F-22CC-4BBF-A184-EAE475F3F5D5}" 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 | {69C3990F-22CC-4BBF-A184-EAE475F3F5D5}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 15 | {69C3990F-22CC-4BBF-A184-EAE475F3F5D5}.Debug|Any CPU.Build.0 = Debug|Any CPU 16 | {69C3990F-22CC-4BBF-A184-EAE475F3F5D5}.Release|Any CPU.ActiveCfg = Release|Any CPU 17 | {69C3990F-22CC-4BBF-A184-EAE475F3F5D5}.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 = {54503CD2-DA76-4801-8495-EA512E088068} 24 | EndGlobalSection 25 | EndGlobal 26 | -------------------------------------------------------------------------------- /securing_apis/Imperative/OwnerPermissions/Controllers/DocumentController.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Authorization; 2 | using Microsoft.AspNetCore.Mvc; 3 | using OwnerPermissions.Data; 4 | using OwnerPermissions.Models; 5 | using OwnerPermissions.Services; 6 | 7 | namespace OwnerPermissions.Controllers; 8 | 9 | /// 10 | /// See: https://github.com/dotnet/AspNetCore.Docs/tree/main/aspnetcore/security/authorization/resourcebased/samples/3_0/ResourceBasedAuthApp2 11 | /// 12 | [Authorize] 13 | [ApiController] 14 | [Route("[controller]")] 15 | public class DocumentController : ControllerBase 16 | { 17 | private readonly IAuthorizationService _authorizationService; 18 | private readonly IDocumentRepository _documentRepository; 19 | private readonly ILogger _logger; 20 | 21 | public DocumentController(IAuthorizationService authorizationService, 22 | IDocumentRepository documentRepository, 23 | ILogger logger) 24 | { 25 | _authorizationService = authorizationService; 26 | _documentRepository = documentRepository; 27 | _logger = logger; 28 | } 29 | 30 | [HttpGet] 31 | public async Task GetById(int documentId) 32 | { 33 | _logger.LogInformation($"Attempting to view documentId {documentId} as {User.Identity!.Name}"); 34 | Document document = _documentRepository.Find(documentId); 35 | 36 | if (document == null) 37 | { 38 | return new NotFoundResult(); 39 | } 40 | 41 | var userIsAuthorized = (await _authorizationService 42 | .AuthorizeAsync(User, document, Operations.Read)).Succeeded; 43 | 44 | if (userIsAuthorized) 45 | { 46 | return Ok(document); 47 | } 48 | else 49 | { 50 | return Unauthorized(); 51 | } 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /securing_apis/Imperative/OwnerPermissions/Data/DocumentRepository.cs: -------------------------------------------------------------------------------- 1 | using OwnerPermissions.Models; 2 | 3 | namespace OwnerPermissions.Data; 4 | 5 | public class DocumentRepository : IDocumentRepository 6 | { 7 | public Document Find(int documentId) 8 | { 9 | return new Document 10 | { 11 | Author = "COMPUTERNAME\\UserName", // change this to your windows account name 12 | Content = "document content", 13 | Id = documentId, 14 | Title = "Test Document" 15 | }; 16 | } 17 | } 18 | 19 | -------------------------------------------------------------------------------- /securing_apis/Imperative/OwnerPermissions/Data/IDocumentRepository.cs: -------------------------------------------------------------------------------- 1 | using OwnerPermissions.Models; 2 | 3 | namespace OwnerPermissions.Data; 4 | 5 | public interface IDocumentRepository 6 | { 7 | Document Find(int documentId); 8 | } 9 | -------------------------------------------------------------------------------- /securing_apis/Imperative/OwnerPermissions/Models/Document.cs: -------------------------------------------------------------------------------- 1 | namespace OwnerPermissions.Models; 2 | 3 | public class Document 4 | { 5 | public int Id { get; set; } 6 | public string Author { get; set; } = ""; 7 | public string Title { get; set; } = ""; 8 | public string Content { get; set; } = ""; 9 | } 10 | -------------------------------------------------------------------------------- /securing_apis/Imperative/OwnerPermissions/OwnerPermissions.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | enable 5 | enable 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | -------------------------------------------------------------------------------- /securing_apis/Imperative/OwnerPermissions/Program.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Authentication.Negotiate; 2 | using Microsoft.AspNetCore.Authorization; 3 | using OwnerPermissions.Data; 4 | using OwnerPermissions.Services; 5 | 6 | namespace OwnerPermissions; 7 | 8 | public class Program 9 | { 10 | public static void Main(string[] args) 11 | { 12 | var builder = WebApplication.CreateBuilder(args); 13 | 14 | builder.Services.AddControllers(); 15 | // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle 16 | builder.Services.AddEndpointsApiExplorer(); 17 | builder.Services.AddSwaggerGen(); 18 | 19 | builder.Services.AddAuthentication(NegotiateDefaults.AuthenticationScheme) 20 | .AddNegotiate(); 21 | 22 | builder.Services.AddAuthorization(options => 23 | { 24 | options.AddPolicy("EditPolicy", policy => 25 | policy.Requirements.Add(new SameAuthorRequirement())); 26 | }); 27 | 28 | builder.Services.AddSingleton(); 29 | builder.Services.AddSingleton(); 30 | builder.Services.AddScoped(); 31 | var app = builder.Build(); 32 | 33 | // Configure the HTTP request pipeline. 34 | if (app.Environment.IsDevelopment()) 35 | { 36 | app.UseSwagger(); 37 | app.UseSwaggerUI(); 38 | } 39 | 40 | app.UseHttpsRedirection(); 41 | 42 | app.UseAuthentication(); 43 | app.UseAuthorization(); 44 | 45 | 46 | app.MapControllers(); 47 | 48 | app.Run(); 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /securing_apis/Imperative/OwnerPermissions/Properties/launchSettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "https://json.schemastore.org/launchsettings.json", 3 | "iisSettings": { 4 | "windowsAuthentication": true, 5 | "anonymousAuthentication": false, 6 | "iisExpress": { 7 | "applicationUrl": "http://localhost:54696", 8 | "sslPort": 44382 9 | } 10 | }, 11 | "profiles": { 12 | "OwnerPermissions": { 13 | "commandName": "Project", 14 | "dotnetRunMessages": true, 15 | "launchBrowser": true, 16 | "launchUrl": "swagger", 17 | "applicationUrl": "https://localhost:7249;http://localhost:5249", 18 | "environmentVariables": { 19 | "ASPNETCORE_ENVIRONMENT": "Development" 20 | } 21 | }, 22 | "IIS Express": { 23 | "commandName": "IISExpress", 24 | "launchBrowser": true, 25 | "launchUrl": "swagger", 26 | "environmentVariables": { 27 | "ASPNETCORE_ENVIRONMENT": "Development" 28 | } 29 | } 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /securing_apis/Imperative/OwnerPermissions/Services/DocumentAuthorizationCrudHandler.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Authorization; 2 | using Microsoft.AspNetCore.Authorization.Infrastructure; 3 | using OwnerPermissions.Models; 4 | 5 | namespace OwnerPermissions.Services; 6 | 7 | public class DocumentAuthorizationCrudHandler : 8 | AuthorizationHandler 9 | { 10 | protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, 11 | OperationAuthorizationRequirement requirement, 12 | Document resource) 13 | { 14 | if (context.User.Identity?.Name!.ToLower() == resource.Author && 15 | requirement.Name == Operations.Read.Name) 16 | { 17 | context.Succeed(requirement); 18 | } 19 | 20 | return Task.CompletedTask; 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /securing_apis/Imperative/OwnerPermissions/Services/DocumentAuthorizationHandler.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Authorization; 2 | using OwnerPermissions.Models; 3 | 4 | namespace OwnerPermissions.Services; 5 | 6 | public class DocumentAuthorizationHandler : 7 | AuthorizationHandler 8 | { 9 | protected override Task HandleRequirementAsync( 10 | AuthorizationHandlerContext context, 11 | SameAuthorRequirement requirement, 12 | Document resource) 13 | { 14 | if (context.User.Identity?.Name!.ToLower() == resource.Author) 15 | { 16 | context.Succeed(requirement); 17 | } 18 | 19 | return Task.CompletedTask; 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /securing_apis/Imperative/OwnerPermissions/Services/Operations.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Authorization.Infrastructure; 2 | 3 | namespace OwnerPermissions.Services; 4 | 5 | public static class Operations 6 | { 7 | public static OperationAuthorizationRequirement Create = 8 | new OperationAuthorizationRequirement { Name = nameof(Create) }; 9 | public static OperationAuthorizationRequirement Read = 10 | new OperationAuthorizationRequirement { Name = nameof(Read) }; 11 | public static OperationAuthorizationRequirement Update = 12 | new OperationAuthorizationRequirement { Name = nameof(Update) }; 13 | public static OperationAuthorizationRequirement Delete = 14 | new OperationAuthorizationRequirement { Name = nameof(Delete) }; 15 | } 16 | -------------------------------------------------------------------------------- /securing_apis/Imperative/OwnerPermissions/Services/SameAuthorRequirement.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Authorization; 2 | 3 | namespace OwnerPermissions.Services; 4 | 5 | public class SameAuthorRequirement : IAuthorizationRequirement { } 6 | -------------------------------------------------------------------------------- /securing_apis/Imperative/OwnerPermissions/appsettings.Development.json: -------------------------------------------------------------------------------- 1 | { 2 | "Logging": { 3 | "LogLevel": { 4 | "Default": "Information", 5 | "Microsoft.AspNetCore": "Warning" 6 | } 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /securing_apis/Imperative/OwnerPermissions/appsettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "Logging": { 3 | "LogLevel": { 4 | "Default": "Information", 5 | "Microsoft.AspNetCore": "Warning" 6 | } 7 | }, 8 | "AllowedHosts": "*" 9 | } 10 | -------------------------------------------------------------------------------- /securing_apis/JsBffSample/BackendApiHost/BackendApiHost.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | -------------------------------------------------------------------------------- /securing_apis/JsBffSample/BackendApiHost/Program.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Hosting; 2 | using Microsoft.Extensions.Hosting; 3 | 4 | namespace BackendApiHost; 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 | -------------------------------------------------------------------------------- /securing_apis/JsBffSample/BackendApiHost/Properties/launchSettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "iisSettings": { 3 | "windowsAuthentication": false, 4 | "anonymousAuthentication": true, 5 | "iisExpress": { 6 | "applicationUrl": "http://localhost:25721", 7 | "sslPort": 44337 8 | } 9 | }, 10 | "profiles": { 11 | "BackendApiHost": { 12 | "commandName": "Project", 13 | "environmentVariables": { 14 | "ASPNETCORE_ENVIRONMENT": "Development" 15 | }, 16 | "applicationUrl": "https://localhost:5020" 17 | } 18 | } 19 | } -------------------------------------------------------------------------------- /securing_apis/JsBffSample/BackendApiHost/Startup.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Builder; 2 | using Microsoft.AspNetCore.Hosting; 3 | using Microsoft.Extensions.DependencyInjection; 4 | 5 | namespace BackendApiHost; 6 | 7 | /// 8 | /// Source: https://github.com/DuendeSoftware/Samples/tree/main/IdentityServer/v6/BFF 9 | /// 10 | public class Startup 11 | { 12 | public void ConfigureServices(IServiceCollection services) 13 | { 14 | services.AddControllers(); 15 | 16 | services.AddAuthentication("token") 17 | .AddJwtBearer("token", options => 18 | { 19 | options.Authority = "https://demo.duendesoftware.com"; 20 | options.Audience = "api"; 21 | 22 | options.MapInboundClaims = false; 23 | }); 24 | 25 | services.AddAuthorization(options => 26 | { 27 | options.AddPolicy("ApiCaller", policy => 28 | { 29 | policy.RequireClaim("scope", "api"); 30 | }); 31 | 32 | options.AddPolicy("RequireInteractiveUser", policy => 33 | { 34 | policy.RequireClaim("sub"); 35 | }); 36 | }); 37 | } 38 | 39 | public void Configure(IApplicationBuilder app, IWebHostEnvironment env) 40 | { 41 | app.UseRouting(); 42 | 43 | app.UseAuthentication(); 44 | app.UseAuthorization(); 45 | 46 | app.UseEndpoints(endpoints => 47 | { 48 | endpoints.MapControllers() 49 | .RequireAuthorization("ApiCaller"); 50 | }); 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /securing_apis/JsBffSample/BackendApiHost/ToDoController.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Duende Software. All rights reserved. 2 | // See LICENSE in the project root for license information. 3 | 4 | using Microsoft.AspNetCore.Mvc; 5 | using System; 6 | using System.Collections.Generic; 7 | using System.Linq; 8 | using Microsoft.AspNetCore.Authorization; 9 | using Microsoft.Extensions.Logging; 10 | 11 | namespace BackendApiHost; 12 | 13 | [Authorize("RequireInteractiveUser")] 14 | public class ToDoController : ControllerBase 15 | { 16 | private readonly ILogger _logger; 17 | 18 | private static readonly List __data = new List() 19 | { 20 | new ToDo { Id = ToDo.NewId(), Date = DateTimeOffset.UtcNow, Name = "Demo ToDo API", User = "bob" }, 21 | new ToDo { Id = ToDo.NewId(), Date = DateTimeOffset.UtcNow.AddHours(1), Name = "Stop Demo", User = "bob" }, 22 | new ToDo { Id = ToDo.NewId(), Date = DateTimeOffset.UtcNow.AddHours(4), Name = "Have Dinner", User = "alice" }, 23 | }; 24 | 25 | public ToDoController(ILogger logger) 26 | { 27 | _logger = logger; 28 | } 29 | 30 | [HttpGet("todos")] 31 | public IActionResult GetAll() 32 | { 33 | _logger.LogInformation("GetAll"); 34 | 35 | return Ok(__data.AsEnumerable()); 36 | } 37 | 38 | [HttpGet("todos/{id}")] 39 | public IActionResult Get(int id) 40 | { 41 | var item = __data.FirstOrDefault(x => x.Id == id); 42 | if (item == null) return NotFound(); 43 | 44 | _logger.LogInformation("Get {id}", id); 45 | return Ok(item); 46 | } 47 | 48 | [HttpPost("todos")] 49 | public IActionResult Post([FromBody] ToDo model) 50 | { 51 | model.Id = ToDo.NewId(); 52 | model.User = $"{User.FindFirst("sub").Value} ({User.FindFirst("name").Value})"; 53 | 54 | __data.Add(model); 55 | _logger.LogInformation("Add {name}", model.Name); 56 | 57 | return Created(Url.Action(nameof(Get), new { id = model.Id }), model); 58 | } 59 | 60 | [HttpPut("todos/{id}")] 61 | public IActionResult Put(int id, [FromBody] ToDo model) 62 | { 63 | var item = __data.FirstOrDefault(x => x.Id == id); 64 | if (item == null) return NotFound(); 65 | 66 | item.Date = model.Date; 67 | item.Name = model.Name; 68 | 69 | _logger.LogInformation("Update {name}", model.Name); 70 | 71 | return NoContent(); 72 | } 73 | 74 | [HttpDelete("todos/{id}")] 75 | public IActionResult Delete(int id) 76 | { 77 | var item = __data.FirstOrDefault(x => x.Id == id); 78 | if (item == null) return NotFound(); 79 | 80 | __data.Remove(item); 81 | _logger.LogInformation("Delete {id}", id); 82 | 83 | return NoContent(); 84 | } 85 | } 86 | 87 | public class ToDo 88 | { 89 | static int _nextId = 1; 90 | public static int NewId() 91 | { 92 | return _nextId++; 93 | } 94 | 95 | public int Id { get; set; } 96 | public DateTimeOffset Date { get; set; } 97 | public string Name { get; set; } 98 | public string User { get; set; } 99 | } 100 | -------------------------------------------------------------------------------- /securing_apis/JsBffSample/FrontendHost/FrontendHost.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | -------------------------------------------------------------------------------- /securing_apis/JsBffSample/FrontendHost/Program.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Hosting; 2 | using Microsoft.Extensions.Hosting; 3 | 4 | namespace FrontendHost 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 | -------------------------------------------------------------------------------- /securing_apis/JsBffSample/FrontendHost/Properties/launchSettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "iisSettings": { 3 | "windowsAuthentication": false, 4 | "anonymousAuthentication": true, 5 | "iisExpress": { 6 | "applicationUrl": "http://localhost:32659", 7 | "sslPort": 44348 8 | } 9 | }, 10 | "profiles": { 11 | "JsBffSample": { 12 | "commandName": "Project", 13 | "launchBrowser": true, 14 | "environmentVariables": { 15 | "ASPNETCORE_ENVIRONMENT": "Development" 16 | }, 17 | "applicationUrl": "https://localhost:5010" 18 | } 19 | } 20 | } -------------------------------------------------------------------------------- /securing_apis/JsBffSample/FrontendHost/Startup.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Builder; 2 | using Microsoft.AspNetCore.Hosting; 3 | using Microsoft.AspNetCore.Http; 4 | using Microsoft.Extensions.DependencyInjection; 5 | using System; 6 | using Duende.Bff.Yarp; 7 | 8 | namespace FrontendHost 9 | { 10 | /// 11 | /// Source: https://github.com/DuendeSoftware/Samples/tree/main/IdentityServer/v6/BFF 12 | /// 13 | public class Startup 14 | { 15 | public void ConfigureServices(IServiceCollection services) 16 | { 17 | services.AddControllers(); 18 | 19 | services.AddBff() 20 | .AddRemoteApis(); 21 | 22 | // registers HTTP client that uses the managed user access token 23 | services.AddUserAccessTokenHttpClient("api_client", configureClient: client => 24 | { 25 | client.BaseAddress = new Uri("https://localhost:5002/"); 26 | }); 27 | 28 | services.AddAuthentication(options => 29 | { 30 | options.DefaultScheme = "cookie"; 31 | options.DefaultChallengeScheme = "oidc"; 32 | options.DefaultSignOutScheme = "oidc"; 33 | }) 34 | .AddCookie("cookie", options => 35 | { 36 | options.Cookie.Name = "__Host-bff"; 37 | options.Cookie.SameSite = SameSiteMode.Strict; 38 | }) 39 | .AddOpenIdConnect("oidc", options => 40 | { 41 | options.Authority = "https://demo.duendesoftware.com"; 42 | options.ClientId = "interactive.confidential"; 43 | options.ClientSecret = "secret"; 44 | options.ResponseType = "code"; 45 | options.ResponseMode = "query"; 46 | 47 | options.GetClaimsFromUserInfoEndpoint = true; 48 | options.MapInboundClaims = false; 49 | options.SaveTokens = true; 50 | 51 | options.Scope.Clear(); 52 | options.Scope.Add("openid"); 53 | options.Scope.Add("profile"); 54 | options.Scope.Add("api"); 55 | options.Scope.Add("offline_access"); 56 | 57 | options.TokenValidationParameters = new() 58 | { 59 | NameClaimType = "name", 60 | RoleClaimType = "role" 61 | }; 62 | }); 63 | } 64 | 65 | public void Configure(IApplicationBuilder app, IWebHostEnvironment env) 66 | { 67 | app.UseDefaultFiles(); 68 | app.UseStaticFiles(); 69 | 70 | app.UseRouting(); 71 | 72 | app.UseAuthentication(); 73 | app.UseBff(); 74 | app.UseAuthorization(); 75 | 76 | app.UseEndpoints(endpoints => 77 | { 78 | endpoints.MapBffManagementEndpoints(); 79 | 80 | // if you want the TODOs API local 81 | //endpoints.MapControllers() 82 | // .RequireAuthorization() 83 | // .AsBffApiEndpoint(); 84 | 85 | // if you want the TODOs API remote 86 | endpoints.MapRemoteBffApiEndpoint("/todos", "https://localhost:5020/todos") 87 | .RequireAccessToken(Duende.Bff.TokenType.User); 88 | }); 89 | } 90 | } 91 | } 92 | -------------------------------------------------------------------------------- /securing_apis/JsBffSample/FrontendHost/ToDoController.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Duende Software. All rights reserved. 2 | // See LICENSE in the project root for license information. 3 | 4 | using Microsoft.AspNetCore.Mvc; 5 | using System; 6 | using System.Collections.Generic; 7 | using System.Linq; 8 | using Microsoft.Extensions.Logging; 9 | 10 | namespace FrontendHost 11 | { 12 | public class ToDoController : ControllerBase 13 | { 14 | private readonly ILogger _logger; 15 | 16 | private static readonly List __data = new List() 17 | { 18 | new ToDo { Id = ToDo.NewId(), Date = DateTimeOffset.UtcNow, Name = "Demo ToDo API", User = "bob" }, 19 | new ToDo { Id = ToDo.NewId(), Date = DateTimeOffset.UtcNow.AddHours(1), Name = "Stop Demo", User = "bob" }, 20 | new ToDo { Id = ToDo.NewId(), Date = DateTimeOffset.UtcNow.AddHours(4), Name = "Have Dinner", User = "alice" }, 21 | }; 22 | 23 | public ToDoController(ILogger logger) 24 | { 25 | _logger = logger; 26 | } 27 | 28 | [HttpGet("todos")] 29 | public IActionResult GetAll() 30 | { 31 | _logger.LogInformation("GetAll"); 32 | 33 | return Ok(__data.AsEnumerable()); 34 | } 35 | 36 | [HttpGet("todos/{id}")] 37 | public IActionResult Get(int id) 38 | { 39 | var item = __data.FirstOrDefault(x => x.Id == id); 40 | if (item == null) return NotFound(); 41 | 42 | _logger.LogInformation("Get {id}", id); 43 | return Ok(item); 44 | } 45 | 46 | [HttpPost("todos")] 47 | public IActionResult Post([FromBody] ToDo model) 48 | { 49 | model.Id = ToDo.NewId(); 50 | model.User = $"{User.FindFirst("sub").Value} ({User.FindFirst("name").Value})"; 51 | 52 | __data.Add(model); 53 | _logger.LogInformation("Add {name}", model.Name); 54 | 55 | return Created(Url.Action(nameof(Get), new { id = model.Id }), model); 56 | } 57 | 58 | [HttpPut("todos/{id}")] 59 | public IActionResult Put(int id, [FromBody] ToDo model) 60 | { 61 | var item = __data.FirstOrDefault(x => x.Id == id); 62 | if (item == null) return NotFound(); 63 | 64 | item.Date = model.Date; 65 | item.Name = model.Name; 66 | 67 | _logger.LogInformation("Update {name}", model.Name); 68 | 69 | return NoContent(); 70 | } 71 | 72 | [HttpDelete("todos/{id}")] 73 | public IActionResult Delete(int id) 74 | { 75 | var item = __data.FirstOrDefault(x => x.Id == id); 76 | if (item == null) return NotFound(); 77 | 78 | __data.Remove(item); 79 | _logger.LogInformation("Delete {id}", id); 80 | 81 | return NoContent(); 82 | } 83 | } 84 | 85 | public class ToDo 86 | { 87 | static int _nextId = 1; 88 | public static int NewId() 89 | { 90 | return _nextId++; 91 | } 92 | 93 | public int Id { get; set; } 94 | public DateTimeOffset Date { get; set; } 95 | public string Name { get; set; } 96 | public string User { get; set; } 97 | } 98 | } 99 | -------------------------------------------------------------------------------- /securing_apis/JsBffSample/FrontendHost/wwwroot/StyleSheet.css: -------------------------------------------------------------------------------- 1 | header { 2 | margin-top:40px; 3 | margin-bottom:40px; 4 | border-bottom:1px solid #808080; 5 | padding:10px; 6 | } 7 | 8 | .hide { 9 | display:none !important; 10 | } 11 | pre:empty { 12 | display: none; 13 | } 14 | 15 | .form-inline { 16 | margin-bottom: 30px; 17 | } 18 | .form-control{ 19 | margin-right:10px; 20 | } 21 | 22 | #username { 23 | font-weight: bold; 24 | padding-top: 6px; 25 | margin-left:10px; 26 | } 27 | .buttons{ 28 | margin-top:20px; 29 | } 30 | .buttons > div { 31 | display:inline; 32 | } 33 | .form-inline label { 34 | font-weight:bold; 35 | margin-right:15px; 36 | } 37 | .banner{ 38 | float:left; 39 | } 40 | .buttons{ 41 | float:right; 42 | } -------------------------------------------------------------------------------- /securing_apis/JsBffSample/FrontendHost/wwwroot/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ardalis/WebApiBestPractices/e072d99989c11e05eb07c7d6ac4e2778f7e0f63a/securing_apis/JsBffSample/FrontendHost/wwwroot/favicon.ico -------------------------------------------------------------------------------- /securing_apis/JsBffSample/FrontendHost/wwwroot/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | Login 16 | 17 | 18 | Logout 19 | Show Session Information 20 | 21 | 22 | 23 | 24 | TODOs 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | Add New 33 | 34 | 35 | Todo Date 36 | 37 | Todo Name 38 | 39 | Create 40 | 41 | 42 | 43 | 44 | 45 | Error: 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | Id 55 | Date 56 | Note 57 | User 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | Session Claims 69 | 70 | 71 | 72 | 73 | 74 | Claim Type 75 | Claim Value 76 | 77 | 78 | 79 | 80 | 81 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | 93 | 94 | 95 | 96 | 97 | -------------------------------------------------------------------------------- /securing_apis/JsBffSample/FrontendHost/wwwroot/session.js: -------------------------------------------------------------------------------- 1 | const userUrl = "/bff/user"; 2 | 3 | window.addEventListener("load", async () => { 4 | 5 | var req = new Request(userUrl, { 6 | headers: new Headers({ 7 | 'X-CSRF': '1' 8 | }) 9 | }) 10 | 11 | var username = document.querySelector("#username"); 12 | 13 | try { 14 | var resp = await fetch(req); 15 | if (resp.ok) { 16 | document.querySelector(".logged-in").classList.remove("hide"); 17 | 18 | let claims = await resp.json(); 19 | console.log("user claims", claims); 20 | 21 | let logoutUrlClaim = claims.find(claim => claim.type === 'bff:logout_url'); 22 | if (logoutUrlClaim) { 23 | document.getElementById("logoutLink").href = logoutUrlClaim.value; 24 | } 25 | 26 | let name = claims.find(claim => claim.type === 'name') || claims.find(claim => claim.type === 'sub'); 27 | console.log(name); 28 | username.innerText = "logged in as: " + (name && name.value); 29 | 30 | } else if (resp.status === 401) { 31 | document.querySelector(".not-logged-in").classList.remove("hide"); 32 | username.innerText = "(not logged in)"; 33 | } 34 | } 35 | catch (e) { 36 | console.log("error checking user status"); 37 | } 38 | 39 | }); 40 | 41 | document.querySelector(".show_session").addEventListener("click", async () => { 42 | var req = new Request(userUrl, { 43 | headers: new Headers({ 44 | 'X-CSRF': '1' 45 | }) 46 | }) 47 | 48 | 49 | try { 50 | var resp = await fetch(req); 51 | if (resp.ok) { 52 | let claims = await resp.json(); 53 | 54 | let body = document.querySelector("#claims"); 55 | body.innerHTML = ""; 56 | 57 | claims.forEach(claim => { 58 | var c1 = document.createElement("td"); 59 | c1.innerText = claim.type; 60 | var c2 = document.createElement("td"); 61 | c2.innerText = claim.value; 62 | var r = document.createElement("tr"); 63 | r.appendChild(c1); 64 | r.appendChild(c2); 65 | body.appendChild(r); 66 | }); 67 | 68 | var modal = document.querySelector(".modal"); 69 | var myModal = new bootstrap.Modal(modal); 70 | myModal.toggle(); 71 | } 72 | else if (resp.status === 401) { 73 | } 74 | 75 | } 76 | catch (e) { 77 | console.log("error checking user session"); 78 | } 79 | 80 | }); 81 | -------------------------------------------------------------------------------- /securing_apis/JsBffSample/FrontendHost/wwwroot/todo.js: -------------------------------------------------------------------------------- 1 | const todoUrl = "/todos"; 2 | const todos = document.getElementById("todos"); 3 | 4 | document.getElementById("createNewButton").addEventListener("click", createTodo); 5 | const name = document.getElementById("name"); 6 | const date = document.getElementById("date"); 7 | 8 | window.addEventListener("load", showTodos); 9 | 10 | async function createTodo() { 11 | error(); 12 | 13 | let request = new Request(todoUrl, { 14 | method: "POST", 15 | headers: { 16 | "content-type": "application/json", 17 | 'x-csrf': '1' 18 | }, 19 | body: JSON.stringify({ 20 | name: name.value, 21 | date: date.value, 22 | }) 23 | }); 24 | 25 | let result = await fetch(request); 26 | if (result.ok) { 27 | var item = await result.json(); 28 | addRow(item); 29 | } 30 | else { 31 | error(result.status) 32 | } 33 | } 34 | 35 | async function showTodos() { 36 | let result = await fetch(new Request(todoUrl, { 37 | headers: { 38 | 'x-csrf': '1' 39 | }, 40 | })); 41 | 42 | if (result.ok) { 43 | let data = await result.json(); 44 | data.forEach(item => addRow(item)); 45 | } 46 | else if (result.status !== 401) { 47 | // 401 == not logged in 48 | error(result.status) 49 | } 50 | } 51 | 52 | async function deleteTodo(id) { 53 | error(); 54 | 55 | let request = new Request(todoUrl + "/" + id, { 56 | headers: { 57 | 'x-csrf': '1' 58 | }, 59 | method: "DELETE" 60 | }); 61 | 62 | let result = await fetch(request); 63 | if (result.ok) { 64 | deleteRow(id); 65 | } 66 | else { 67 | error(result.status) 68 | } 69 | } 70 | 71 | 72 | /////// UI helpers 73 | 74 | function error(msg) { 75 | let alert = document.querySelector(".alert"); 76 | let alertMsg = document.querySelector("#errText"); 77 | 78 | if (msg) { 79 | alert.classList.remove("hide"); 80 | alertMsg.innerText = msg; 81 | } 82 | else { 83 | alert.classList.add("hide"); 84 | alertMsg.innerText = ''; 85 | } 86 | } 87 | 88 | 89 | function addRow(item) { 90 | let row = document.createElement("tr"); 91 | row.dataset.id = item.id; 92 | todos.appendChild(row); 93 | 94 | function addCell(row, text) { 95 | let cell = document.createElement("td"); 96 | cell.innerText = text; 97 | row.appendChild(cell); 98 | } 99 | 100 | function addDeleteButton(row, id) { 101 | let cell = document.createElement("td"); 102 | row.appendChild(cell); 103 | let btn = document.createElement("button"); 104 | btn.classList.add("btn"); 105 | btn.classList.add("btn-danger"); 106 | cell.appendChild(btn); 107 | btn.textContent = "delete"; 108 | btn.addEventListener("click", async () => await deleteTodo(id)); 109 | } 110 | 111 | addDeleteButton(row, item.id); 112 | addCell(row, item.id); 113 | addCell(row, item.date); 114 | addCell(row, item.name); 115 | addCell(row, item.user); 116 | } 117 | 118 | 119 | async function deleteRow(id) { 120 | let row = todos.querySelector(`tr[data-id='${id}']`); 121 | if (row) { 122 | todos.removeChild(row); 123 | } 124 | } 125 | 126 | 127 | -------------------------------------------------------------------------------- /securing_apis/JsBffSample/JsBffSample.sln: -------------------------------------------------------------------------------- 1 | 2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio Version 16 4 | VisualStudioVersion = 16.0.31229.75 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "FrontendHost", "FrontendHost\FrontendHost.csproj", "{A62786A1-5D5E-4B37-A72C-98F2E19366BE}" 7 | EndProject 8 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "BackendApiHost", "BackendApiHost\BackendApiHost.csproj", "{A3E08ADB-A8AC-48A1-87D5-4A773BCF03DC}" 9 | EndProject 10 | Global 11 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 12 | Debug|Any CPU = Debug|Any CPU 13 | Release|Any CPU = Release|Any CPU 14 | EndGlobalSection 15 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 16 | {A62786A1-5D5E-4B37-A72C-98F2E19366BE}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 17 | {A62786A1-5D5E-4B37-A72C-98F2E19366BE}.Debug|Any CPU.Build.0 = Debug|Any CPU 18 | {A62786A1-5D5E-4B37-A72C-98F2E19366BE}.Release|Any CPU.ActiveCfg = Release|Any CPU 19 | {A62786A1-5D5E-4B37-A72C-98F2E19366BE}.Release|Any CPU.Build.0 = Release|Any CPU 20 | {A3E08ADB-A8AC-48A1-87D5-4A773BCF03DC}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 21 | {A3E08ADB-A8AC-48A1-87D5-4A773BCF03DC}.Debug|Any CPU.Build.0 = Debug|Any CPU 22 | {A3E08ADB-A8AC-48A1-87D5-4A773BCF03DC}.Release|Any CPU.ActiveCfg = Release|Any CPU 23 | {A3E08ADB-A8AC-48A1-87D5-4A773BCF03DC}.Release|Any CPU.Build.0 = Release|Any CPU 24 | EndGlobalSection 25 | GlobalSection(SolutionProperties) = preSolution 26 | HideSolutionNode = FALSE 27 | EndGlobalSection 28 | GlobalSection(ExtensibilityGlobals) = postSolution 29 | SolutionGuid = {6FCA70AE-F62B-4DD3-90F4-BE0330C5C51B} 30 | EndGlobalSection 31 | EndGlobal 32 | -------------------------------------------------------------------------------- /securing_apis/jwtapi/AuthExtensions.cs: -------------------------------------------------------------------------------- 1 | using JWTAPI.Security.Tokens; 2 | using Microsoft.AspNetCore.Authentication.JwtBearer; 3 | using Microsoft.IdentityModel.Tokens; 4 | 5 | namespace JWTAPI; 6 | 7 | public static class AuthExtensions 8 | { 9 | public static void ConfigureJwtAuthentication(this IServiceCollection services, 10 | TokenOptions tokenOptions, 11 | SigningConfigurations signingConfigurations) 12 | { 13 | services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) 14 | .AddJwtBearer(jwtBearerOptions => 15 | { 16 | jwtBearerOptions.TokenValidationParameters = 17 | new TokenValidationParameters() 18 | { 19 | ValidateAudience = true, 20 | ValidateLifetime = true, 21 | ValidateIssuerSigningKey = true, 22 | ValidIssuer = tokenOptions.Issuer, 23 | ValidAudience = tokenOptions.Audience, 24 | IssuerSigningKey = signingConfigurations.SecurityKey, 25 | ClockSkew = TimeSpan.Zero 26 | }; 27 | }); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /securing_apis/jwtapi/Controllers/LoginController.cs: -------------------------------------------------------------------------------- 1 | using AutoMapper; 2 | using JWTAPI.Controllers.Resources; 3 | using JWTAPI.Core.Security.Tokens; 4 | using JWTAPI.Core.Services; 5 | using Microsoft.AspNetCore.Mvc; 6 | 7 | namespace JWTAPI.Controllers; 8 | 9 | [ApiController] 10 | public class AuthController : Controller 11 | { 12 | private readonly IMapper _mapper; 13 | private readonly IAuthenticationService _authenticationService; 14 | 15 | public AuthController(IMapper mapper, IAuthenticationService authenticationService) 16 | { 17 | _authenticationService = authenticationService; 18 | _mapper = mapper; 19 | } 20 | 21 | [Route("/api/login")] 22 | [HttpPost] 23 | public async Task LoginAsync([FromBody] UserCredentialsResource userCredentials) 24 | { 25 | var response = await _authenticationService.CreateAccessTokenAsync(userCredentials.Email, 26 | userCredentials.Password); 27 | if (!response.Success) 28 | { 29 | return BadRequest(response.Message); 30 | } 31 | 32 | var accessTokenResource = _mapper.Map(response.Token); 33 | return Ok(accessTokenResource); 34 | } 35 | 36 | [Route("/api/token/refresh")] 37 | [HttpPost] 38 | public async Task RefreshTokenAsync([FromBody] RefreshTokenResource refreshTokenResource) 39 | { 40 | var response = await _authenticationService.RefreshTokenAsync(refreshTokenResource.Token, 41 | refreshTokenResource.UserEmail); 42 | if (!response.Success) 43 | { 44 | return BadRequest(response.Message); 45 | } 46 | 47 | var tokenResource = _mapper.Map(response.Token); 48 | return Ok(tokenResource); 49 | } 50 | 51 | [Route("/api/token/revoke")] 52 | [HttpPost] 53 | public IActionResult RevokeToken([FromBody] RevokeTokenResource revokeTokenResource) 54 | { 55 | _authenticationService.RevokeRefreshToken(revokeTokenResource.RefreshToken, revokeTokenResource.EmailAddress); 56 | return NoContent(); 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /securing_apis/jwtapi/Controllers/ProtectedController.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Authorization; 2 | using Microsoft.AspNetCore.Mvc; 3 | 4 | namespace JWTAPI.Controllers; 5 | 6 | [ApiController] 7 | public class ProtectedController : Controller 8 | { 9 | [HttpGet] 10 | [Authorize] 11 | [Route("/api/protectedforcommonusers")] 12 | public IActionResult GetProtectedData() 13 | { 14 | return Ok("Hello world from protected controller."); 15 | } 16 | 17 | [HttpGet] 18 | [Authorize(Roles = "Administrator")] 19 | [Route("/api/protectedforadministrators")] 20 | public IActionResult GetProtectedDataForAdmin() 21 | { 22 | return Ok("Hello admin!"); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /securing_apis/jwtapi/Controllers/Resources/RefreshTokenResource.cs: -------------------------------------------------------------------------------- 1 | using System.ComponentModel.DataAnnotations; 2 | 3 | namespace JWTAPI.Controllers.Resources; 4 | 5 | public class RefreshTokenResource 6 | { 7 | [Required] 8 | public string Token { get; set; } 9 | 10 | [Required] 11 | [DataType(DataType.EmailAddress)] 12 | [StringLength(255)] 13 | public string UserEmail { get; set; } 14 | } 15 | -------------------------------------------------------------------------------- /securing_apis/jwtapi/Controllers/Resources/RevokeTokenResource.cs: -------------------------------------------------------------------------------- 1 | using System.ComponentModel.DataAnnotations; 2 | 3 | namespace JWTAPI.Controllers.Resources; 4 | 5 | public class RevokeTokenResource 6 | { 7 | [Required] 8 | public string RefreshToken { get; set; } 9 | [Required] 10 | public string EmailAddress { get; set; } 11 | } 12 | -------------------------------------------------------------------------------- /securing_apis/jwtapi/Controllers/Resources/TokenResource.cs: -------------------------------------------------------------------------------- 1 | namespace JWTAPI.Controllers.Resources; 2 | 3 | public class AccessTokenResource 4 | { 5 | public string AccessToken { get; set; } 6 | public string RefreshToken { get; set; } 7 | public long Expiration { get; set; } 8 | } 9 | -------------------------------------------------------------------------------- /securing_apis/jwtapi/Controllers/Resources/UserCredentialsResource.cs: -------------------------------------------------------------------------------- 1 | using System.ComponentModel.DataAnnotations; 2 | 3 | namespace JWTAPI.Controllers.Resources; 4 | 5 | public class UserCredentialsResource 6 | { 7 | [Required] 8 | [DataType(DataType.EmailAddress)] 9 | [StringLength(255)] 10 | public string Email { get; set; } 11 | 12 | [Required] 13 | [StringLength(32)] 14 | public string Password { get; set; } 15 | } 16 | -------------------------------------------------------------------------------- /securing_apis/jwtapi/Controllers/Resources/UserResource.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | 3 | namespace JWTAPI.Controllers.Resources; 4 | 5 | public class UserResource 6 | { 7 | public int Id { get; set; } 8 | public string Email { get; set; } 9 | public IEnumerable Roles { get; set; } 10 | } 11 | -------------------------------------------------------------------------------- /securing_apis/jwtapi/Controllers/UsersController.cs: -------------------------------------------------------------------------------- 1 | using AutoMapper; 2 | using JWTAPI.Controllers.Resources; 3 | using JWTAPI.Core.Models; 4 | using JWTAPI.Core.Services; 5 | using Microsoft.AspNetCore.Mvc; 6 | 7 | namespace JWTAPI.Controllers; 8 | 9 | [ApiController] 10 | [Route("/api/[controller]")] 11 | public class UsersController : Controller 12 | { 13 | private readonly IMapper _mapper; 14 | private readonly IUserService _userService; 15 | 16 | public UsersController(IUserService userService, IMapper mapper) 17 | { 18 | _userService = userService; 19 | _mapper = mapper; 20 | } 21 | 22 | [HttpPost] 23 | public async Task CreateUserAsync([FromBody] UserCredentialsResource userCredentials) 24 | { 25 | var user = _mapper.Map(userCredentials); 26 | 27 | var response = await _userService.CreateUserAsync(user, ApplicationRole.Common); 28 | if (!response.Success) 29 | { 30 | return BadRequest(response.Message); 31 | } 32 | 33 | var userResource = _mapper.Map(response.User); 34 | return Ok(userResource); 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /securing_apis/jwtapi/Core/Models/ApplicationRole.cs: -------------------------------------------------------------------------------- 1 | namespace JWTAPI.Core.Models; 2 | 3 | public enum ApplicationRole 4 | { 5 | Common = 1, 6 | Administrator = 2 7 | } 8 | -------------------------------------------------------------------------------- /securing_apis/jwtapi/Core/Models/Role.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.ObjectModel; 2 | using System.ComponentModel.DataAnnotations; 3 | 4 | namespace JWTAPI.Core.Models; 5 | 6 | public class Role 7 | { 8 | public int Id { get; set; } 9 | 10 | [Required] 11 | [StringLength(50)] 12 | public string Name { get; set; } 13 | 14 | public ICollection UsersRole { get; set; } = new Collection(); 15 | } 16 | -------------------------------------------------------------------------------- /securing_apis/jwtapi/Core/Models/User.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.ObjectModel; 2 | using System.ComponentModel.DataAnnotations; 3 | 4 | namespace JWTAPI.Core.Models; 5 | 6 | public class User 7 | { 8 | public int Id { get; set; } 9 | 10 | [Required] 11 | [DataType(DataType.EmailAddress)] 12 | [StringLength(255)] 13 | public string Email { get; set; } 14 | 15 | [Required] 16 | public string Password { get; set; } 17 | 18 | public ICollection UserRoles { get; set; } = new Collection(); 19 | } 20 | -------------------------------------------------------------------------------- /securing_apis/jwtapi/Core/Models/UserRole.cs: -------------------------------------------------------------------------------- 1 | using System.ComponentModel.DataAnnotations.Schema; 2 | 3 | namespace JWTAPI.Core.Models; 4 | 5 | [Table("UserRoles")] 6 | public class UserRole 7 | { 8 | public int UserId { get; set; } 9 | public User User { get; set; } 10 | 11 | public int RoleId { get; set; } 12 | public Role Role { get; set; } 13 | } 14 | -------------------------------------------------------------------------------- /securing_apis/jwtapi/Core/Repositories/IUnitOfWork.cs: -------------------------------------------------------------------------------- 1 | namespace JWTAPI.Core.Repositories; 2 | 3 | public interface IUnitOfWork 4 | { 5 | Task CompleteAsync(); 6 | } 7 | -------------------------------------------------------------------------------- /securing_apis/jwtapi/Core/Repositories/IUserRepository.cs: -------------------------------------------------------------------------------- 1 | using JWTAPI.Core.Models; 2 | 3 | namespace JWTAPI.Core.Repositories; 4 | 5 | public interface IUserRepository 6 | { 7 | Task AddAsync(User user, ApplicationRole[] userRoles); 8 | Task FindByEmailAsync(string email); 9 | } 10 | -------------------------------------------------------------------------------- /securing_apis/jwtapi/Core/Security/Hashing/IPasswordHasher.cs: -------------------------------------------------------------------------------- 1 | namespace JWTAPI.Core.Security.Hashing; 2 | 3 | public interface IPasswordHasher 4 | { 5 | string HashPassword(string password); 6 | bool PasswordMatches(string providedPassword, string passwordHash); 7 | } 8 | -------------------------------------------------------------------------------- /securing_apis/jwtapi/Core/Security/Tokens/AccessToken.cs: -------------------------------------------------------------------------------- 1 | namespace JWTAPI.Core.Security.Tokens; 2 | 3 | public class AccessToken : JsonWebToken 4 | { 5 | public RefreshToken RefreshToken { get; private set; } 6 | 7 | public AccessToken(string token, long expiration, RefreshToken refreshToken) : base(token, expiration) 8 | { 9 | if (refreshToken == null) 10 | throw new ArgumentException("Specify a valid refresh token."); 11 | 12 | RefreshToken = refreshToken; 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /securing_apis/jwtapi/Core/Security/Tokens/ITokenHandler.cs: -------------------------------------------------------------------------------- 1 | using JWTAPI.Core.Models; 2 | 3 | namespace JWTAPI.Core.Security.Tokens; 4 | 5 | public interface ITokenHandler 6 | { 7 | AccessToken CreateAccessToken(User user); 8 | RefreshToken TakeRefreshToken(string token, string email); 9 | void RevokeRefreshToken(string token, string email); 10 | } 11 | -------------------------------------------------------------------------------- /securing_apis/jwtapi/Core/Security/Tokens/JsonWebToken.cs: -------------------------------------------------------------------------------- 1 | namespace JWTAPI.Core.Security.Tokens 2 | { 3 | public abstract class JsonWebToken 4 | { 5 | public string Token { get; protected set; } 6 | public long Expiration { get; protected set; } 7 | 8 | public JsonWebToken(string token, long expiration) 9 | { 10 | if(string.IsNullOrWhiteSpace(token)) 11 | throw new ArgumentException("Invalid token."); 12 | 13 | if(expiration <= 0) 14 | throw new ArgumentException("Invalid expiration."); 15 | 16 | Token = token; 17 | Expiration = expiration; 18 | } 19 | 20 | public bool IsExpired() => DateTime.UtcNow.Ticks > Expiration; 21 | } 22 | } -------------------------------------------------------------------------------- /securing_apis/jwtapi/Core/Security/Tokens/RefreshToken.cs: -------------------------------------------------------------------------------- 1 | namespace JWTAPI.Core.Security.Tokens 2 | { 3 | public class RefreshToken : JsonWebToken 4 | { 5 | public RefreshToken(string token, long expiration) : base(token, expiration) 6 | { 7 | } 8 | } 9 | } -------------------------------------------------------------------------------- /securing_apis/jwtapi/Core/Services/Communication/BaseResponse.cs: -------------------------------------------------------------------------------- 1 | namespace JWTAPI.Core.Services.Communication; 2 | 3 | public abstract class BaseResponse 4 | { 5 | public bool Success { get; protected set; } 6 | public string Message { get; protected set; } 7 | 8 | public BaseResponse(bool success, string message) 9 | { 10 | Success = success; 11 | Message = message; 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /securing_apis/jwtapi/Core/Services/Communication/CreateUserResponse.cs: -------------------------------------------------------------------------------- 1 | using JWTAPI.Core.Models; 2 | 3 | namespace JWTAPI.Core.Services.Communication; 4 | 5 | public class CreateUserResponse : BaseResponse 6 | { 7 | public User User { get; private set; } 8 | 9 | public CreateUserResponse(bool success, string message, User user) : base(success, message) 10 | { 11 | User = user; 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /securing_apis/jwtapi/Core/Services/Communication/TokenResponse.cs: -------------------------------------------------------------------------------- 1 | using JWTAPI.Core.Security.Tokens; 2 | 3 | namespace JWTAPI.Core.Services.Communication; 4 | 5 | public class TokenResponse : BaseResponse 6 | { 7 | public AccessToken Token { get; set; } 8 | 9 | public TokenResponse(bool success, string message, AccessToken token) : base(success, message) 10 | { 11 | Token = token; 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /securing_apis/jwtapi/Core/Services/IAuthenticationService.cs: -------------------------------------------------------------------------------- 1 | using JWTAPI.Core.Services.Communication; 2 | 3 | namespace JWTAPI.Core.Services; 4 | 5 | public interface IAuthenticationService 6 | { 7 | Task CreateAccessTokenAsync(string email, string password); 8 | Task RefreshTokenAsync(string refreshToken, string userEmail); 9 | void RevokeRefreshToken(string refreshToken, string userEmail); 10 | } 11 | -------------------------------------------------------------------------------- /securing_apis/jwtapi/Core/Services/IUserService.cs: -------------------------------------------------------------------------------- 1 | using JWTAPI.Core.Models; 2 | using JWTAPI.Core.Services.Communication; 3 | 4 | namespace JWTAPI.Core.Services; 5 | 6 | public interface IUserService 7 | { 8 | Task CreateUserAsync(User user, params ApplicationRole[] userRoles); 9 | Task FindByEmailAsync(string email); 10 | } 11 | -------------------------------------------------------------------------------- /securing_apis/jwtapi/Extensions/MiddlewareExtensions.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.OpenApi.Models; 2 | 3 | namespace JWTAPI.Extensions; 4 | 5 | public static class MiddlewareExtensions 6 | { 7 | public static IServiceCollection AddCustomSwagger(this IServiceCollection services) 8 | { 9 | services.AddSwaggerGen(cfg => 10 | { 11 | cfg.SwaggerDoc("v1", new OpenApiInfo 12 | { 13 | Title = "JWT API", 14 | Version = "v4", 15 | Description = "Example API that shows how to implement JSON Web Token authentication and authorization with ASP.NET 6, built from scratch.", 16 | Contact = new OpenApiContact 17 | { 18 | Name = "Originally by Evandro Gayer Gomes; Updated by Steve Smith @ardalis", 19 | Url = new Uri("https://www.linkedin.com/in/evandro-gayer-gomes/?locale=en_US") 20 | }, 21 | License = new OpenApiLicense 22 | { 23 | Name = "MIT", 24 | }, 25 | }); 26 | 27 | cfg.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme 28 | { 29 | In = ParameterLocation.Header, 30 | Description = "JSON Web Token to access resources. Example: Bearer {token}", 31 | Name = "Authorization", 32 | Type = SecuritySchemeType.ApiKey 33 | }); 34 | 35 | cfg.AddSecurityRequirement(new OpenApiSecurityRequirement 36 | { 37 | { 38 | new OpenApiSecurityScheme 39 | { 40 | Reference = new OpenApiReference { Type = ReferenceType.SecurityScheme, Id = "Bearer" } 41 | }, 42 | new [] { string.Empty } 43 | } 44 | }); 45 | }); 46 | 47 | return services; 48 | } 49 | 50 | public static IApplicationBuilder UseCustomSwagger(this IApplicationBuilder app) 51 | { 52 | app.UseSwagger().UseSwaggerUI(options => 53 | { 54 | options.SwaggerEndpoint("/swagger/v1/swagger.json", "JWT API"); 55 | options.DocumentTitle = "JWT API"; 56 | }); 57 | 58 | return app; 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /securing_apis/jwtapi/JWTAPI.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | enable 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | all 18 | runtime; build; native; contentfiles; analyzers; buildtransitive 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | -------------------------------------------------------------------------------- /securing_apis/jwtapi/JWTAPI.sln: -------------------------------------------------------------------------------- 1 | 2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio Version 17 4 | VisualStudioVersion = 17.2.32602.215 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "JWTAPI", "JWTAPI.csproj", "{1D453E13-A5F5-4379-BE76-AF8D84E934A4}" 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 | {1D453E13-A5F5-4379-BE76-AF8D84E934A4}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 15 | {1D453E13-A5F5-4379-BE76-AF8D84E934A4}.Debug|Any CPU.Build.0 = Debug|Any CPU 16 | {1D453E13-A5F5-4379-BE76-AF8D84E934A4}.Release|Any CPU.ActiveCfg = Release|Any CPU 17 | {1D453E13-A5F5-4379-BE76-AF8D84E934A4}.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 = {5985A106-8CE1-4C0C-B55C-67D6AD3FCA33} 24 | EndGlobalSection 25 | EndGlobal 26 | -------------------------------------------------------------------------------- /securing_apis/jwtapi/Mapping/ModelToResourceProfile.cs: -------------------------------------------------------------------------------- 1 | using AutoMapper; 2 | using JWTAPI.Controllers.Resources; 3 | using JWTAPI.Core.Models; 4 | using JWTAPI.Core.Security.Tokens; 5 | 6 | namespace JWTAPI.Mapping; 7 | 8 | public class ModelToResourceProfile : Profile 9 | { 10 | public ModelToResourceProfile() 11 | { 12 | CreateMap() 13 | .ForMember(u => u.Roles, opt => opt.MapFrom(u => u.UserRoles.Select(ur => ur.Role.Name))); 14 | 15 | CreateMap() 16 | .ForMember(a => a.AccessToken, opt => opt.MapFrom(a => a.Token)) 17 | .ForMember(a => a.RefreshToken, opt => opt.MapFrom(a => a.RefreshToken.Token)) 18 | .ForMember(a => a.Expiration, opt => opt.MapFrom(a => a.Expiration)); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /securing_apis/jwtapi/Mapping/ResourceToModelProfile.cs: -------------------------------------------------------------------------------- 1 | using AutoMapper; 2 | using JWTAPI.Controllers.Resources; 3 | using JWTAPI.Core.Models; 4 | 5 | namespace JWTAPI.Mapping; 6 | 7 | public class ResourceToModelProfile : Profile 8 | { 9 | public ResourceToModelProfile() 10 | { 11 | CreateMap(); 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /securing_apis/jwtapi/Persistence/AppDbContext.cs: -------------------------------------------------------------------------------- 1 | using JWTAPI.Core.Models; 2 | using Microsoft.EntityFrameworkCore; 3 | 4 | namespace JWTAPI.Persistence; 5 | 6 | public class AppDbContext : DbContext 7 | { 8 | public DbSet Users { get; set; } 9 | public DbSet Roles { get; set; } 10 | 11 | public AppDbContext(DbContextOptions options) : base(options) 12 | { } 13 | 14 | protected override void OnModelCreating(ModelBuilder builder) 15 | { 16 | base.OnModelCreating(builder); 17 | 18 | builder.Entity().HasKey(ur => new { ur.UserId, ur.RoleId }); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /securing_apis/jwtapi/Persistence/DatabaseSeed.cs: -------------------------------------------------------------------------------- 1 | using JWTAPI.Core.Models; 2 | using JWTAPI.Core.Security.Hashing; 3 | 4 | namespace JWTAPI.Persistence; 5 | 6 | /// 7 | /// EF Core already supports database seeding throught overriding "OnModelCreating", 8 | /// but I decided to create a separate seed class to avoid 9 | /// injecting IPasswordHasher into AppDbContext. 10 | /// To understand how to use database seeding into DbContext classes, 11 | /// check this link: https://docs.microsoft.com/en-us/ef/core/modeling/data-seeding 12 | /// 13 | public class DatabaseSeed 14 | { 15 | public static void Seed(AppDbContext context, IPasswordHasher passwordHasher) 16 | { 17 | context.Database.EnsureCreated(); 18 | 19 | if (context.Roles.Count() == 0) 20 | { 21 | 22 | var roles = new List 23 | { 24 | new Role { Name = ApplicationRole.Common.ToString() }, 25 | new Role { Name = ApplicationRole.Administrator.ToString() } 26 | }; 27 | 28 | context.Roles.AddRange(roles); 29 | context.SaveChanges(); 30 | } 31 | 32 | if (context.Users.Count() == 0) 33 | { 34 | var users = new List 35 | { 36 | new User { Email = "admin@admin.com", Password = passwordHasher.HashPassword("12345678") }, 37 | new User { Email = "common@common.com", Password = passwordHasher.HashPassword("12345678") }, 38 | }; 39 | 40 | users[0].UserRoles.Add(new UserRole 41 | { 42 | RoleId = context.Roles.SingleOrDefault(r => r.Name == ApplicationRole.Administrator.ToString()).Id 43 | }); 44 | 45 | users[1].UserRoles.Add(new UserRole 46 | { 47 | RoleId = context.Roles.SingleOrDefault(r => r.Name == ApplicationRole.Common.ToString()).Id 48 | }); 49 | 50 | context.Users.AddRange(users); 51 | context.SaveChanges(); 52 | } 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /securing_apis/jwtapi/Persistence/UnitOfWork.cs: -------------------------------------------------------------------------------- 1 | using JWTAPI.Core.Repositories; 2 | 3 | namespace JWTAPI.Persistence; 4 | 5 | public class UnitOfWork : IUnitOfWork 6 | { 7 | private readonly AppDbContext _context; 8 | 9 | public UnitOfWork(AppDbContext context) 10 | { 11 | _context = context; 12 | } 13 | 14 | public async Task CompleteAsync() 15 | { 16 | await _context.SaveChangesAsync(); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /securing_apis/jwtapi/Persistence/UserRepository.cs: -------------------------------------------------------------------------------- 1 | using JWTAPI.Core.Models; 2 | using JWTAPI.Core.Repositories; 3 | using Microsoft.EntityFrameworkCore; 4 | 5 | namespace JWTAPI.Persistence; 6 | 7 | public class UserRepository : IUserRepository 8 | { 9 | private readonly AppDbContext _context; 10 | 11 | public UserRepository(AppDbContext context) 12 | { 13 | _context = context; 14 | } 15 | 16 | public async Task AddAsync(User user, ApplicationRole[] userRoles) 17 | { 18 | var roleNames = userRoles.Select(r => r.ToString()).ToList(); 19 | var roles = await _context.Roles.Where(r => roleNames.Contains(r.Name)).ToListAsync(); 20 | 21 | foreach (var role in roles) 22 | { 23 | user.UserRoles.Add(new UserRole { RoleId = role.Id }); 24 | } 25 | 26 | _context.Users.Add(user); 27 | } 28 | 29 | public async Task FindByEmailAsync(string email) 30 | { 31 | return await _context.Users.Include(u => u.UserRoles) 32 | .ThenInclude(ur => ur.Role) 33 | .SingleOrDefaultAsync(u => u.Email == email); 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /securing_apis/jwtapi/Program.cs: -------------------------------------------------------------------------------- 1 | using JWTAPI.Core.Security.Hashing; 2 | using JWTAPI.Persistence; 3 | 4 | namespace JWTAPI; 5 | 6 | public class Program 7 | { 8 | public static void Main(string[] args) 9 | { 10 | var host = CreateHostBuilder(args).Build(); 11 | 12 | using (var scope = host.Services.CreateScope()) 13 | { 14 | var services = scope.ServiceProvider; 15 | var context = services.GetService(); 16 | var passwordHasher = services.GetService(); 17 | DatabaseSeed.Seed(context, passwordHasher); 18 | } 19 | 20 | host.Run(); 21 | } 22 | 23 | public static IHostBuilder CreateHostBuilder(string[] args) 24 | { 25 | return Host.CreateDefaultBuilder(args) 26 | .ConfigureWebHostDefaults(webBuilder => 27 | { 28 | webBuilder.UseStartup(); 29 | }); 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /securing_apis/jwtapi/Properties/launchSettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "iisSettings": { 3 | "windowsAuthentication": false, 4 | "anonymousAuthentication": true, 5 | "iisExpress": { 6 | "applicationUrl": "http://localhost:5000", 7 | "sslPort": 44341 8 | } 9 | }, 10 | "$schema": "http://json.schemastore.org/launchsettings.json", 11 | "profiles": { 12 | "IIS Express": { 13 | "commandName": "IISExpress", 14 | "launchBrowser": true, 15 | "launchUrl": "swagger", 16 | "environmentVariables": { 17 | "ASPNETCORE_ENVIRONMENT": "Development" 18 | } 19 | }, 20 | "JWTAPI": { 21 | "commandName": "Project", 22 | "launchBrowser": true, 23 | "launchUrl": "swagger", 24 | "environmentVariables": { 25 | "ASPNETCORE_ENVIRONMENT": "Development" 26 | }, 27 | "applicationUrl": "https://localhost:5001;http://localhost:5000" 28 | } 29 | } 30 | } -------------------------------------------------------------------------------- /securing_apis/jwtapi/Security/Hashing/PasswordHasher.cs: -------------------------------------------------------------------------------- 1 | using System.Runtime.CompilerServices; 2 | using System.Security.Cryptography; 3 | using JWTAPI.Core.Security.Hashing; 4 | 5 | namespace JWTAPI.Security.Hashing; 6 | 7 | /// 8 | /// This password hasher is the same used by ASP.NET Identity. 9 | /// Explanation: https://stackoverflow.com/questions/20621950/asp-net-identity-default-password-hasher-how-does-it-work-and-is-it-secure 10 | /// Full implementation: https://gist.github.com/malkafly/e873228cb9515010bdbe 11 | /// 12 | public class PasswordHasher : IPasswordHasher 13 | { 14 | public string HashPassword(string password) 15 | { 16 | byte[] salt; 17 | byte[] buffer2; 18 | if (string.IsNullOrEmpty(password)) 19 | { 20 | throw new ArgumentNullException("password"); 21 | } 22 | using (Rfc2898DeriveBytes bytes = new Rfc2898DeriveBytes(password, 0x10, 0x3e8)) 23 | { 24 | salt = bytes.Salt; 25 | buffer2 = bytes.GetBytes(0x20); 26 | } 27 | byte[] dst = new byte[0x31]; 28 | Buffer.BlockCopy(salt, 0, dst, 1, 0x10); 29 | Buffer.BlockCopy(buffer2, 0, dst, 0x11, 0x20); 30 | return Convert.ToBase64String(dst); 31 | } 32 | 33 | public bool PasswordMatches(string providedPassword, string passwordHash) 34 | { 35 | byte[] buffer4; 36 | if (passwordHash == null) 37 | { 38 | return false; 39 | } 40 | if (providedPassword == null) 41 | { 42 | throw new ArgumentNullException("providedPassword"); 43 | } 44 | byte[] src = Convert.FromBase64String(passwordHash); 45 | if ((src.Length != 0x31) || (src[0] != 0)) 46 | { 47 | return false; 48 | } 49 | byte[] dst = new byte[0x10]; 50 | Buffer.BlockCopy(src, 1, dst, 0, 0x10); 51 | byte[] buffer3 = new byte[0x20]; 52 | Buffer.BlockCopy(src, 0x11, buffer3, 0, 0x20); 53 | using (Rfc2898DeriveBytes bytes = new Rfc2898DeriveBytes(providedPassword, dst, 0x3e8)) 54 | { 55 | buffer4 = bytes.GetBytes(0x20); 56 | } 57 | return ByteArraysEqual(buffer3, buffer4); 58 | } 59 | 60 | [MethodImpl(MethodImplOptions.NoOptimization)] 61 | private bool ByteArraysEqual(byte[] a, byte[] b) 62 | { 63 | if (ReferenceEquals(a, b)) 64 | { 65 | return true; 66 | } 67 | 68 | if (a == null || b == null || a.Length != b.Length) 69 | { 70 | return false; 71 | } 72 | 73 | bool areSame = true; 74 | for (int i = 0; i < a.Length; i++) 75 | { 76 | areSame &= (a[i] == b[i]); 77 | } 78 | return areSame; 79 | } 80 | } 81 | -------------------------------------------------------------------------------- /securing_apis/jwtapi/Security/Tokens/SigningConfigurations.cs: -------------------------------------------------------------------------------- 1 | using System.Text; 2 | using Microsoft.IdentityModel.Tokens; 3 | 4 | namespace JWTAPI.Security.Tokens; 5 | 6 | public class SigningConfigurations 7 | { 8 | public SecurityKey SecurityKey { get; } 9 | public SigningCredentials SigningCredentials { get; } 10 | 11 | public SigningConfigurations(string key) 12 | { 13 | var keyBytes = Encoding.ASCII.GetBytes(key); 14 | 15 | SecurityKey = new SymmetricSecurityKey(keyBytes); 16 | SigningCredentials = new SigningCredentials(SecurityKey, SecurityAlgorithms.HmacSha256Signature); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /securing_apis/jwtapi/Security/Tokens/TokenHandler.cs: -------------------------------------------------------------------------------- 1 | using System.IdentityModel.Tokens.Jwt; 2 | using System.Security.Claims; 3 | using JWTAPI.Core.Models; 4 | using JWTAPI.Core.Security.Hashing; 5 | using JWTAPI.Core.Security.Tokens; 6 | using Microsoft.Extensions.Options; 7 | 8 | namespace JWTAPI.Security.Tokens; 9 | 10 | public class TokenHandler : ITokenHandler 11 | { 12 | private readonly ISet _refreshTokens = new HashSet