├── .dockerignore ├── .gitattributes ├── .gitignore ├── ApiGateway ├── ApiGateway.csproj ├── Dockerfile ├── Program.cs ├── Properties │ └── launchSettings.json ├── appsettings.Development.json ├── appsettings.json └── ocelot.json ├── AuthenticationWebApi ├── AuthenticationWebApi.csproj ├── Controllers │ └── AccountController.cs ├── Dockerfile ├── Program.cs ├── Properties │ └── launchSettings.json ├── appsettings.Development.json └── appsettings.json ├── CustomerWebApi ├── Controllers │ └── CustomerController.cs ├── CustomerDbContext.cs ├── CustomerWebApi.csproj ├── Dockerfile ├── Models │ └── Customer.cs ├── Program.cs ├── Properties │ └── launchSettings.json ├── appsettings.Development.json └── appsettings.json ├── JwtAuthenticationManager ├── CustomJwtAuthExtension.cs ├── JwtAuthenticationManager.csproj ├── JwtTokenHandler.cs └── Models │ ├── AuthenticationRequest.cs │ ├── AuthenticationResponse.cs │ └── UserAccount.cs ├── OcelotDemoSolution.sln ├── OrderWebApi ├── Controllers │ └── OrderController.cs ├── Dockerfile ├── Models │ ├── Order.cs │ └── OrderDetail.cs ├── OrderWebApi.csproj ├── Program.cs ├── Properties │ └── launchSettings.json ├── appsettings.Development.json └── appsettings.json ├── ProductWebApi ├── Controllers │ └── ProductController.cs ├── Dockerfile ├── Models │ └── Product.cs ├── ProductDbContext.cs ├── ProductWebApi.csproj ├── Program.cs ├── Properties │ └── launchSettings.json ├── appsettings.Development.json └── appsettings.json ├── docker-compose.dcproj ├── docker-compose.override.yml └── docker-compose.yml /.dockerignore: -------------------------------------------------------------------------------- 1 | **/.classpath 2 | **/.dockerignore 3 | **/.env 4 | **/.git 5 | **/.gitignore 6 | **/.project 7 | **/.settings 8 | **/.toolstarget 9 | **/.vs 10 | **/.vscode 11 | **/*.*proj.user 12 | **/*.dbmdl 13 | **/*.jfm 14 | **/azds.yaml 15 | **/bin 16 | **/charts 17 | **/docker-compose* 18 | **/Dockerfile* 19 | **/node_modules 20 | **/npm-debug.log 21 | **/obj 22 | **/secrets.dev.yaml 23 | **/values.dev.yaml 24 | LICENSE 25 | README.md -------------------------------------------------------------------------------- /.gitattributes: -------------------------------------------------------------------------------- 1 | ############################################################################### 2 | # Set default behavior to automatically normalize line endings. 3 | ############################################################################### 4 | * text=auto 5 | 6 | ############################################################################### 7 | # Set default behavior for command prompt diff. 8 | # 9 | # This is need for earlier builds of msysgit that does not have it on by 10 | # default for csharp files. 11 | # Note: This is only used by command line 12 | ############################################################################### 13 | #*.cs diff=csharp 14 | 15 | ############################################################################### 16 | # Set the merge driver for project and solution files 17 | # 18 | # Merging from the command prompt will add diff markers to the files if there 19 | # are conflicts (Merging from VS is not affected by the settings below, in VS 20 | # the diff markers are never inserted). Diff markers may cause the following 21 | # file extensions to fail to load in VS. An alternative would be to treat 22 | # these files as binary and thus will always conflict and require user 23 | # intervention with every merge. To do so, just uncomment the entries below 24 | ############################################################################### 25 | #*.sln merge=binary 26 | #*.csproj merge=binary 27 | #*.vbproj merge=binary 28 | #*.vcxproj merge=binary 29 | #*.vcproj merge=binary 30 | #*.dbproj merge=binary 31 | #*.fsproj merge=binary 32 | #*.lsproj merge=binary 33 | #*.wixproj merge=binary 34 | #*.modelproj merge=binary 35 | #*.sqlproj merge=binary 36 | #*.wwaproj merge=binary 37 | 38 | ############################################################################### 39 | # behavior for image files 40 | # 41 | # image files are treated as binary by default. 42 | ############################################################################### 43 | #*.jpg binary 44 | #*.png binary 45 | #*.gif binary 46 | 47 | ############################################################################### 48 | # diff behavior for common document formats 49 | # 50 | # Convert binary document formats to text before diffing them. This feature 51 | # is only available from the command line. Turn it on by uncommenting the 52 | # entries below. 53 | ############################################################################### 54 | #*.doc diff=astextplain 55 | #*.DOC diff=astextplain 56 | #*.docx diff=astextplain 57 | #*.DOCX diff=astextplain 58 | #*.dot diff=astextplain 59 | #*.DOT diff=astextplain 60 | #*.pdf diff=astextplain 61 | #*.PDF diff=astextplain 62 | #*.rtf diff=astextplain 63 | #*.RTF diff=astextplain 64 | -------------------------------------------------------------------------------- /.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 | [Ww][Ii][Nn]32/ 27 | [Aa][Rr][Mm]/ 28 | [Aa][Rr][Mm]64/ 29 | bld/ 30 | [Bb]in/ 31 | [Oo]bj/ 32 | [Oo]ut/ 33 | [Ll]og/ 34 | [Ll]ogs/ 35 | 36 | # Visual Studio 2015/2017 cache/options directory 37 | .vs/ 38 | # Uncomment if you have tasks that create the project's static files in wwwroot 39 | #wwwroot/ 40 | 41 | # Visual Studio 2017 auto generated files 42 | Generated\ Files/ 43 | 44 | # MSTest test Results 45 | [Tt]est[Rr]esult*/ 46 | [Bb]uild[Ll]og.* 47 | 48 | # NUnit 49 | *.VisualState.xml 50 | TestResult.xml 51 | nunit-*.xml 52 | 53 | # Build Results of an ATL Project 54 | [Dd]ebugPS/ 55 | [Rr]eleasePS/ 56 | dlldata.c 57 | 58 | # Benchmark Results 59 | BenchmarkDotNet.Artifacts/ 60 | 61 | # .NET Core 62 | project.lock.json 63 | project.fragment.lock.json 64 | artifacts/ 65 | 66 | # ASP.NET Scaffolding 67 | ScaffoldingReadMe.txt 68 | 69 | # StyleCop 70 | StyleCopReport.xml 71 | 72 | # Files built by Visual Studio 73 | *_i.c 74 | *_p.c 75 | *_h.h 76 | *.ilk 77 | *.meta 78 | *.obj 79 | *.iobj 80 | *.pch 81 | *.pdb 82 | *.ipdb 83 | *.pgc 84 | *.pgd 85 | *.rsp 86 | *.sbr 87 | *.tlb 88 | *.tli 89 | *.tlh 90 | *.tmp 91 | *.tmp_proj 92 | *_wpftmp.csproj 93 | *.log 94 | *.vspscc 95 | *.vssscc 96 | .builds 97 | *.pidb 98 | *.svclog 99 | *.scc 100 | 101 | # Chutzpah Test files 102 | _Chutzpah* 103 | 104 | # Visual C++ cache files 105 | ipch/ 106 | *.aps 107 | *.ncb 108 | *.opendb 109 | *.opensdf 110 | *.sdf 111 | *.cachefile 112 | *.VC.db 113 | *.VC.VC.opendb 114 | 115 | # Visual Studio profiler 116 | *.psess 117 | *.vsp 118 | *.vspx 119 | *.sap 120 | 121 | # Visual Studio Trace Files 122 | *.e2e 123 | 124 | # TFS 2012 Local Workspace 125 | $tf/ 126 | 127 | # Guidance Automation Toolkit 128 | *.gpState 129 | 130 | # ReSharper is a .NET coding add-in 131 | _ReSharper*/ 132 | *.[Rr]e[Ss]harper 133 | *.DotSettings.user 134 | 135 | # TeamCity is a build add-in 136 | _TeamCity* 137 | 138 | # DotCover is a Code Coverage Tool 139 | *.dotCover 140 | 141 | # AxoCover is a Code Coverage Tool 142 | .axoCover/* 143 | !.axoCover/settings.json 144 | 145 | # Coverlet is a free, cross platform Code Coverage Tool 146 | coverage*.json 147 | coverage*.xml 148 | coverage*.info 149 | 150 | # Visual Studio code coverage results 151 | *.coverage 152 | *.coveragexml 153 | 154 | # NCrunch 155 | _NCrunch_* 156 | .*crunch*.local.xml 157 | nCrunchTemp_* 158 | 159 | # MightyMoose 160 | *.mm.* 161 | AutoTest.Net/ 162 | 163 | # Web workbench (sass) 164 | .sass-cache/ 165 | 166 | # Installshield output folder 167 | [Ee]xpress/ 168 | 169 | # DocProject is a documentation generator add-in 170 | DocProject/buildhelp/ 171 | DocProject/Help/*.HxT 172 | DocProject/Help/*.HxC 173 | DocProject/Help/*.hhc 174 | DocProject/Help/*.hhk 175 | DocProject/Help/*.hhp 176 | DocProject/Help/Html2 177 | DocProject/Help/html 178 | 179 | # Click-Once directory 180 | publish/ 181 | 182 | # Publish Web Output 183 | *.[Pp]ublish.xml 184 | *.azurePubxml 185 | # Note: Comment the next line if you want to checkin your web deploy settings, 186 | # but database connection strings (with potential passwords) will be unencrypted 187 | *.pubxml 188 | *.publishproj 189 | 190 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 191 | # checkin your Azure Web App publish settings, but sensitive information contained 192 | # in these scripts will be unencrypted 193 | PublishScripts/ 194 | 195 | # NuGet Packages 196 | *.nupkg 197 | # NuGet Symbol Packages 198 | *.snupkg 199 | # The packages folder can be ignored because of Package Restore 200 | **/[Pp]ackages/* 201 | # except build/, which is used as an MSBuild target. 202 | !**/[Pp]ackages/build/ 203 | # Uncomment if necessary however generally it will be regenerated when needed 204 | #!**/[Pp]ackages/repositories.config 205 | # NuGet v3's project.json files produces more ignorable files 206 | *.nuget.props 207 | *.nuget.targets 208 | 209 | # Microsoft Azure Build Output 210 | csx/ 211 | *.build.csdef 212 | 213 | # Microsoft Azure Emulator 214 | ecf/ 215 | rcf/ 216 | 217 | # Windows Store app package directories and files 218 | AppPackages/ 219 | BundleArtifacts/ 220 | Package.StoreAssociation.xml 221 | _pkginfo.txt 222 | *.appx 223 | *.appxbundle 224 | *.appxupload 225 | 226 | # Visual Studio cache files 227 | # files ending in .cache can be ignored 228 | *.[Cc]ache 229 | # but keep track of directories ending in .cache 230 | !?*.[Cc]ache/ 231 | 232 | # Others 233 | ClientBin/ 234 | ~$* 235 | *~ 236 | *.dbmdl 237 | *.dbproj.schemaview 238 | *.jfm 239 | *.pfx 240 | *.publishsettings 241 | orleans.codegen.cs 242 | 243 | # Including strong name files can present a security risk 244 | # (https://github.com/github/gitignore/pull/2483#issue-259490424) 245 | #*.snk 246 | 247 | # Since there are multiple workflows, uncomment next line to ignore bower_components 248 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 249 | #bower_components/ 250 | 251 | # RIA/Silverlight projects 252 | Generated_Code/ 253 | 254 | # Backup & report files from converting an old project file 255 | # to a newer Visual Studio version. Backup files are not needed, 256 | # because we have git ;-) 257 | _UpgradeReport_Files/ 258 | Backup*/ 259 | UpgradeLog*.XML 260 | UpgradeLog*.htm 261 | ServiceFabricBackup/ 262 | *.rptproj.bak 263 | 264 | # SQL Server files 265 | *.mdf 266 | *.ldf 267 | *.ndf 268 | 269 | # Business Intelligence projects 270 | *.rdl.data 271 | *.bim.layout 272 | *.bim_*.settings 273 | *.rptproj.rsuser 274 | *- [Bb]ackup.rdl 275 | *- [Bb]ackup ([0-9]).rdl 276 | *- [Bb]ackup ([0-9][0-9]).rdl 277 | 278 | # Microsoft Fakes 279 | FakesAssemblies/ 280 | 281 | # GhostDoc plugin setting file 282 | *.GhostDoc.xml 283 | 284 | # Node.js Tools for Visual Studio 285 | .ntvs_analysis.dat 286 | node_modules/ 287 | 288 | # Visual Studio 6 build log 289 | *.plg 290 | 291 | # Visual Studio 6 workspace options file 292 | *.opt 293 | 294 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.) 295 | *.vbw 296 | 297 | # Visual Studio LightSwitch build output 298 | **/*.HTMLClient/GeneratedArtifacts 299 | **/*.DesktopClient/GeneratedArtifacts 300 | **/*.DesktopClient/ModelManifest.xml 301 | **/*.Server/GeneratedArtifacts 302 | **/*.Server/ModelManifest.xml 303 | _Pvt_Extensions 304 | 305 | # Paket dependency manager 306 | .paket/paket.exe 307 | paket-files/ 308 | 309 | # FAKE - F# Make 310 | .fake/ 311 | 312 | # CodeRush personal settings 313 | .cr/personal 314 | 315 | # Python Tools for Visual Studio (PTVS) 316 | __pycache__/ 317 | *.pyc 318 | 319 | # Cake - Uncomment if you are using it 320 | # tools/** 321 | # !tools/packages.config 322 | 323 | # Tabs Studio 324 | *.tss 325 | 326 | # Telerik's JustMock configuration file 327 | *.jmconfig 328 | 329 | # BizTalk build output 330 | *.btp.cs 331 | *.btm.cs 332 | *.odx.cs 333 | *.xsd.cs 334 | 335 | # OpenCover UI analysis results 336 | OpenCover/ 337 | 338 | # Azure Stream Analytics local run output 339 | ASALocalRun/ 340 | 341 | # MSBuild Binary and Structured Log 342 | *.binlog 343 | 344 | # NVidia Nsight GPU debugger configuration file 345 | *.nvuser 346 | 347 | # MFractors (Xamarin productivity tool) working folder 348 | .mfractor/ 349 | 350 | # Local History for Visual Studio 351 | .localhistory/ 352 | 353 | # BeatPulse healthcheck temp database 354 | healthchecksdb 355 | 356 | # Backup folder for Package Reference Convert tool in Visual Studio 2017 357 | MigrationBackup/ 358 | 359 | # Ionide (cross platform F# VS Code tools) working folder 360 | .ionide/ 361 | 362 | # Fody - auto-generated XML schema 363 | FodyWeavers.xsd -------------------------------------------------------------------------------- /ApiGateway/ApiGateway.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | net6.0 5 | enable 6 | enable 7 | Linux 8 | ..\docker-compose.dcproj 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | -------------------------------------------------------------------------------- /ApiGateway/Dockerfile: -------------------------------------------------------------------------------- 1 | #See https://aka.ms/containerfastmode to understand how Visual Studio uses this Dockerfile to build your images for faster debugging. 2 | 3 | FROM mcr.microsoft.com/dotnet/aspnet:6.0 AS base 4 | WORKDIR /app 5 | EXPOSE 80 6 | 7 | FROM mcr.microsoft.com/dotnet/sdk:6.0 AS build 8 | WORKDIR /src 9 | COPY ["ApiGateway/ApiGateway.csproj", "ApiGateway/"] 10 | RUN dotnet restore "ApiGateway/ApiGateway.csproj" 11 | COPY . . 12 | WORKDIR "/src/ApiGateway" 13 | RUN dotnet build "ApiGateway.csproj" -c Release -o /app/build 14 | 15 | FROM build AS publish 16 | RUN dotnet publish "ApiGateway.csproj" -c Release -o /app/publish 17 | 18 | FROM base AS final 19 | WORKDIR /app 20 | COPY --from=publish /app/publish . 21 | ENTRYPOINT ["dotnet", "ApiGateway.dll"] -------------------------------------------------------------------------------- /ApiGateway/Program.cs: -------------------------------------------------------------------------------- 1 | using JwtAuthenticationManager; 2 | using Ocelot.DependencyInjection; 3 | using Ocelot.Middleware; 4 | 5 | var builder = WebApplication.CreateBuilder(args); 6 | builder.Configuration.SetBasePath(builder.Environment.ContentRootPath) 7 | .AddJsonFile("ocelot.json", optional: false, reloadOnChange: true) 8 | .AddEnvironmentVariables(); 9 | builder.Services.AddOcelot(builder.Configuration); 10 | builder.Services.AddCustomJwtAuthentication(); 11 | 12 | var app = builder.Build(); 13 | await app.UseOcelot(); 14 | 15 | app.UseAuthentication(); 16 | app.UseAuthorization(); 17 | 18 | app.Run(); 19 | -------------------------------------------------------------------------------- /ApiGateway/Properties/launchSettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "iisSettings": { 3 | "windowsAuthentication": false, 4 | "anonymousAuthentication": true, 5 | "iisExpress": { 6 | "applicationUrl": "http://localhost:17341", 7 | "sslPort": 0 8 | } 9 | }, 10 | "profiles": { 11 | "ApiGateway": { 12 | "commandName": "Project", 13 | "launchBrowser": true, 14 | "environmentVariables": { 15 | "ASPNETCORE_ENVIRONMENT": "Development" 16 | }, 17 | "applicationUrl": "http://localhost:5075", 18 | "dotnetRunMessages": true 19 | }, 20 | "IIS Express": { 21 | "commandName": "IISExpress", 22 | "launchBrowser": true, 23 | "environmentVariables": { 24 | "ASPNETCORE_ENVIRONMENT": "Development" 25 | } 26 | }, 27 | "Docker": { 28 | "commandName": "Docker", 29 | "launchBrowser": true, 30 | "launchUrl": "{Scheme}://{ServiceHost}:{ServicePort}", 31 | "publishAllPorts": true 32 | } 33 | } 34 | } -------------------------------------------------------------------------------- /ApiGateway/appsettings.Development.json: -------------------------------------------------------------------------------- 1 | { 2 | "Logging": { 3 | "LogLevel": { 4 | "Default": "Information", 5 | "Microsoft.AspNetCore": "Warning" 6 | } 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /ApiGateway/appsettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "Logging": { 3 | "LogLevel": { 4 | "Default": "Information", 5 | "Microsoft.AspNetCore": "Warning" 6 | } 7 | }, 8 | "AllowedHosts": "*" 9 | } 10 | -------------------------------------------------------------------------------- /ApiGateway/ocelot.json: -------------------------------------------------------------------------------- 1 | { 2 | "Routes": [ 3 | // Authentication Web API 4 | { 5 | "UpstreamPathTemplate": "/api/Account", 6 | "UpstreamHttpMethod": [ "Post" ], 7 | "DownstreamScheme": "http", 8 | "DownstreamHostAndPorts": [ 9 | { 10 | "Host": "authenticationwebapi", 11 | "Port": 80 12 | } 13 | ], 14 | "DownstreamPathTemplate": "/api/Account" 15 | }, 16 | // Customer Web API 17 | { 18 | "UpstreamPathTemplate": "/api/Customer", 19 | "UpstreamHttpMethod": [ "Get", "Post", "Put" ], 20 | "DownstreamScheme": "http", 21 | "DownstreamHostAndPorts": [ 22 | { 23 | "Host": "customerwebapi", 24 | "Port": 80 25 | } 26 | ], 27 | "DownstreamPathTemplate": "/api/Customer" 28 | }, 29 | { 30 | "UpstreamPathTemplate": "/api/Customer/{customerId}", 31 | "UpstreamHttpMethod": [ "Get", "Delete" ], 32 | "DownstreamScheme": "http", 33 | "DownstreamHostAndPorts": [ 34 | { 35 | "Host": "customerwebapi", 36 | "Port": 80 37 | } 38 | ], 39 | "DownstreamPathTemplate": "/api/Customer/{customerId}" 40 | }, 41 | 42 | //Product Web API 43 | { 44 | "UpstreamPathTemplate": "/api/Product", 45 | "UpstreamHttpMethod": [ "Get", "Post", "Put" ], 46 | "DownstreamScheme": "http", 47 | "DownstreamHostAndPorts": [ 48 | { 49 | "Host": "productwebapi", 50 | "Port": 80 51 | } 52 | ], 53 | "DownstreamPathTemplate": "/api/Product", 54 | "AuthenticationOptions": { 55 | "AuthenticationProviderKey": "Bearer", 56 | "AllowedScopes": [] 57 | }, 58 | "RouteClaimsRequirement": { 59 | "Role": "Administrator" 60 | } 61 | }, 62 | { 63 | "UpstreamPathTemplate": "/api/Product/{productId}", 64 | "UpstreamHttpMethod": [ "Get", "Delete" ], 65 | "DownstreamScheme": "http", 66 | "DownstreamHostAndPorts": [ 67 | { 68 | "Host": "productwebapi", 69 | "Port": 80 70 | } 71 | ], 72 | "DownstreamPathTemplate": "/api/Product/{productId}" 73 | }, 74 | 75 | // Order Web API 76 | { 77 | "UpstreamPathTemplate": "/api/Order", 78 | "UpstreamHttpMethod": [ "Get", "Post", "Put" ], 79 | "DownstreamScheme": "http", 80 | "DownstreamHostAndPorts": [ 81 | { 82 | "Host": "orderwebapi", 83 | "Port": 80 84 | } 85 | ], 86 | "DownstreamPathTemplate": "/api/Order", 87 | "RateLimitOptions": { 88 | "ClientWhitelist": [], 89 | "EnableRateLimiting": true, 90 | "Period": "60s", 91 | "PeriodTimespan": 60, 92 | "Limit": 1 93 | } 94 | }, 95 | { 96 | "UpstreamPathTemplate": "/api/Order/{orderId}", 97 | "UpstreamHttpMethod": [ "Get", "Delete" ], 98 | "DownstreamScheme": "http", 99 | "DownstreamHostAndPorts": [ 100 | { 101 | "Host": "orderwebapi", 102 | "Port": 80 103 | } 104 | ], 105 | "DownstreamPathTemplate": "/api/Order/{orderId}" 106 | } 107 | ], 108 | "GlobalConfiguration": { 109 | "BaseUrl": "http://localhost:8001", 110 | "RateLimitOptions": { 111 | "QuotaExceededMessage": "Request not allowed", 112 | "HttpStatusCode": 909 113 | } 114 | } 115 | } 116 | -------------------------------------------------------------------------------- /AuthenticationWebApi/AuthenticationWebApi.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | net6.0 5 | enable 6 | enable 7 | Linux 8 | ..\docker-compose.dcproj 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | -------------------------------------------------------------------------------- /AuthenticationWebApi/Controllers/AccountController.cs: -------------------------------------------------------------------------------- 1 | using JwtAuthenticationManager; 2 | using JwtAuthenticationManager.Models; 3 | using Microsoft.AspNetCore.Http; 4 | using Microsoft.AspNetCore.Mvc; 5 | 6 | namespace AuthenticationWebApi.Controllers 7 | { 8 | [Route("api/[controller]")] 9 | [ApiController] 10 | public class AccountController : ControllerBase 11 | { 12 | private readonly JwtTokenHandler _jwtTokenHandler; 13 | 14 | public AccountController(JwtTokenHandler jwtTokenHandler) 15 | { 16 | _jwtTokenHandler = jwtTokenHandler; 17 | } 18 | 19 | [HttpPost] 20 | public ActionResult Authenticate([FromBody] AuthenticationRequest authenticationRequest) 21 | { 22 | var authenticationResponse = _jwtTokenHandler.GenerateJwtToken(authenticationRequest); 23 | if (authenticationResponse == null) return Unauthorized(); 24 | return authenticationResponse; 25 | } 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /AuthenticationWebApi/Dockerfile: -------------------------------------------------------------------------------- 1 | #See https://aka.ms/containerfastmode to understand how Visual Studio uses this Dockerfile to build your images for faster debugging. 2 | 3 | FROM mcr.microsoft.com/dotnet/aspnet:6.0 AS base 4 | WORKDIR /app 5 | EXPOSE 80 6 | 7 | FROM mcr.microsoft.com/dotnet/sdk:6.0 AS build 8 | WORKDIR /src 9 | COPY ["AuthenticationWebApi/AuthenticationWebApi.csproj", "AuthenticationWebApi/"] 10 | COPY ["JwtAuthenticationManager/JwtAuthenticationManager.csproj", "JwtAuthenticationManager/"] 11 | RUN dotnet restore "AuthenticationWebApi/AuthenticationWebApi.csproj" 12 | COPY . . 13 | WORKDIR "/src/AuthenticationWebApi" 14 | RUN dotnet build "AuthenticationWebApi.csproj" -c Release -o /app/build 15 | 16 | FROM build AS publish 17 | RUN dotnet publish "AuthenticationWebApi.csproj" -c Release -o /app/publish 18 | 19 | FROM base AS final 20 | WORKDIR /app 21 | COPY --from=publish /app/publish . 22 | ENTRYPOINT ["dotnet", "AuthenticationWebApi.dll"] -------------------------------------------------------------------------------- /AuthenticationWebApi/Program.cs: -------------------------------------------------------------------------------- 1 | using JwtAuthenticationManager; 2 | 3 | var builder = WebApplication.CreateBuilder(args); 4 | 5 | // Add services to the container. 6 | 7 | builder.Services.AddControllers(); 8 | builder.Services.AddSingleton(); 9 | var app = builder.Build(); 10 | 11 | // Configure the HTTP request pipeline. 12 | 13 | app.UseAuthorization(); 14 | 15 | app.MapControllers(); 16 | 17 | app.Run(); 18 | -------------------------------------------------------------------------------- /AuthenticationWebApi/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:36146", 8 | "sslPort": 0 9 | } 10 | }, 11 | "profiles": { 12 | "AuthenticationWebApi": { 13 | "commandName": "Project", 14 | "launchBrowser": true, 15 | "launchUrl": "weatherforecast", 16 | "environmentVariables": { 17 | "ASPNETCORE_ENVIRONMENT": "Development" 18 | }, 19 | "applicationUrl": "http://localhost:5163", 20 | "dotnetRunMessages": true 21 | }, 22 | "IIS Express": { 23 | "commandName": "IISExpress", 24 | "launchBrowser": true, 25 | "launchUrl": "weatherforecast", 26 | "environmentVariables": { 27 | "ASPNETCORE_ENVIRONMENT": "Development" 28 | } 29 | }, 30 | "Docker": { 31 | "commandName": "Docker", 32 | "launchBrowser": true, 33 | "launchUrl": "{Scheme}://{ServiceHost}:{ServicePort}/weatherforecast", 34 | "publishAllPorts": true 35 | } 36 | } 37 | } -------------------------------------------------------------------------------- /AuthenticationWebApi/appsettings.Development.json: -------------------------------------------------------------------------------- 1 | { 2 | "Logging": { 3 | "LogLevel": { 4 | "Default": "Information", 5 | "Microsoft.AspNetCore": "Warning" 6 | } 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /AuthenticationWebApi/appsettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "Logging": { 3 | "LogLevel": { 4 | "Default": "Information", 5 | "Microsoft.AspNetCore": "Warning" 6 | } 7 | }, 8 | "AllowedHosts": "*" 9 | } 10 | -------------------------------------------------------------------------------- /CustomerWebApi/Controllers/CustomerController.cs: -------------------------------------------------------------------------------- 1 | using CustomerWebApi.Models; 2 | using Microsoft.AspNetCore.Authorization; 3 | using Microsoft.AspNetCore.Http; 4 | using Microsoft.AspNetCore.Mvc; 5 | 6 | namespace CustomerWebApi.Controllers 7 | { 8 | [Route("api/[controller]")] 9 | [ApiController] 10 | public class CustomerController : ControllerBase 11 | { 12 | private readonly CustomerDbContext _customerDbContext; 13 | 14 | public CustomerController(CustomerDbContext customerDbContext) 15 | { 16 | _customerDbContext = customerDbContext; 17 | } 18 | 19 | [HttpGet] 20 | [Authorize] 21 | public ActionResult> GetCustomers() 22 | { 23 | return _customerDbContext.Customers; 24 | } 25 | 26 | [HttpGet("{customerId:int}")] 27 | public async Task> GetById(int customerId) 28 | { 29 | var customer = await _customerDbContext.Customers.FindAsync(customerId); 30 | return customer; 31 | } 32 | 33 | [HttpPost] 34 | [Authorize(Roles = "Administrator")] 35 | public async Task Create(Customer customer) 36 | { 37 | await _customerDbContext.Customers.AddAsync(customer); 38 | await _customerDbContext.SaveChangesAsync(); 39 | return Ok(); 40 | } 41 | 42 | [HttpPut] 43 | [Authorize(Roles = "Administrator,User")] 44 | public async Task Update(Customer customer) 45 | { 46 | _customerDbContext.Customers.Update(customer); 47 | await _customerDbContext.SaveChangesAsync(); 48 | return Ok(); 49 | } 50 | 51 | [HttpDelete("{customerId:int}")] 52 | public async Task Delete(int customerId) 53 | { 54 | var customer = await _customerDbContext.Customers.FindAsync(customerId); 55 | _customerDbContext.Customers.Remove(customer); 56 | await _customerDbContext.SaveChangesAsync(); 57 | return Ok(); 58 | } 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /CustomerWebApi/CustomerDbContext.cs: -------------------------------------------------------------------------------- 1 | using CustomerWebApi.Models; 2 | using Microsoft.EntityFrameworkCore; 3 | using Microsoft.EntityFrameworkCore.Infrastructure; 4 | using Microsoft.EntityFrameworkCore.Storage; 5 | 6 | namespace CustomerWebApi 7 | { 8 | public class CustomerDbContext : DbContext 9 | { 10 | public CustomerDbContext(DbContextOptions dbContextOptions) : base(dbContextOptions) 11 | { 12 | try 13 | { 14 | var databaseCreator = Database.GetService() as RelationalDatabaseCreator; 15 | if (databaseCreator != null) 16 | { 17 | if (!databaseCreator.CanConnect()) databaseCreator.Create(); 18 | if (!databaseCreator.HasTables()) databaseCreator.CreateTables(); 19 | } 20 | } 21 | catch (Exception ex) 22 | { 23 | Console.WriteLine(ex.Message); 24 | } 25 | } 26 | 27 | public DbSet Customers { get; set; } 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /CustomerWebApi/CustomerWebApi.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | net6.0 5 | enable 6 | enable 7 | ..\docker-compose.dcproj 8 | Linux 9 | 10 | 11 | 12 | 13 | all 14 | runtime; build; native; contentfiles; analyzers; buildtransitive 15 | 16 | 17 | 18 | all 19 | runtime; build; native; contentfiles; analyzers; buildtransitive 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | -------------------------------------------------------------------------------- /CustomerWebApi/Dockerfile: -------------------------------------------------------------------------------- 1 | #See https://aka.ms/containerfastmode to understand how Visual Studio uses this Dockerfile to build your images for faster debugging. 2 | 3 | FROM mcr.microsoft.com/dotnet/aspnet:6.0 AS base 4 | WORKDIR /app 5 | EXPOSE 80 6 | 7 | FROM mcr.microsoft.com/dotnet/sdk:6.0 AS build 8 | WORKDIR /src 9 | COPY ["CustomerWebApi/CustomerWebApi.csproj", "CustomerWebApi/"] 10 | RUN dotnet restore "CustomerWebApi/CustomerWebApi.csproj" 11 | COPY . . 12 | WORKDIR "/src/CustomerWebApi" 13 | RUN dotnet build "CustomerWebApi.csproj" -c Release -o /app/build 14 | 15 | FROM build AS publish 16 | RUN dotnet publish "CustomerWebApi.csproj" -c Release -o /app/publish 17 | 18 | FROM base AS final 19 | WORKDIR /app 20 | COPY --from=publish /app/publish . 21 | ENTRYPOINT ["dotnet", "CustomerWebApi.dll"] 22 | -------------------------------------------------------------------------------- /CustomerWebApi/Models/Customer.cs: -------------------------------------------------------------------------------- 1 | using System.ComponentModel.DataAnnotations; 2 | using System.ComponentModel.DataAnnotations.Schema; 3 | 4 | namespace CustomerWebApi.Models 5 | { 6 | [Table("customer", Schema = "dbo")] 7 | public class Customer 8 | { 9 | [Key] 10 | [DatabaseGenerated(DatabaseGeneratedOption.Identity)] 11 | [Column("customer_id")] 12 | public int CustomerId { get; set; } 13 | 14 | [Column("customer_name")] 15 | public string CustomerName { get; set; } 16 | 17 | [Column("mobile_no")] 18 | public string MobileNumber { get; set; } 19 | 20 | [Column("email")] 21 | public string Email { get; set; } 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /CustomerWebApi/Program.cs: -------------------------------------------------------------------------------- 1 | using CustomerWebApi; 2 | using JwtAuthenticationManager; 3 | using Microsoft.EntityFrameworkCore; 4 | 5 | var builder = WebApplication.CreateBuilder(args); 6 | 7 | // Add services to the container. 8 | 9 | builder.Services.AddControllers(); 10 | builder.Services.AddCustomJwtAuthentication(); 11 | 12 | /* Database Context Dependency Injection */ 13 | var dbHost = Environment.GetEnvironmentVariable("DB_HOST"); 14 | var dbName = Environment.GetEnvironmentVariable("DB_NAME"); 15 | var dbPassword = Environment.GetEnvironmentVariable("DB_SA_PASSWORD"); 16 | var connectionString = $"Data Source={dbHost};Initial Catalog={dbName};User ID=sa;Password={dbPassword}"; 17 | builder.Services.AddDbContext(opt => opt.UseSqlServer(connectionString)); 18 | /* ===================================== */ 19 | 20 | var app = builder.Build(); 21 | 22 | // Configure the HTTP request pipeline. 23 | 24 | app.UseAuthentication(); 25 | app.UseAuthorization(); 26 | 27 | app.MapControllers(); 28 | 29 | app.Run(); 30 | -------------------------------------------------------------------------------- /CustomerWebApi/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:62096", 8 | "sslPort": 0 9 | } 10 | }, 11 | "profiles": { 12 | "CustomerWebApi": { 13 | "commandName": "Project", 14 | "launchBrowser": true, 15 | "launchUrl": "weatherforecast", 16 | "environmentVariables": { 17 | "ASPNETCORE_ENVIRONMENT": "Development" 18 | }, 19 | "applicationUrl": "http://localhost:5284", 20 | "dotnetRunMessages": true 21 | }, 22 | "IIS Express": { 23 | "commandName": "IISExpress", 24 | "launchBrowser": true, 25 | "launchUrl": "weatherforecast", 26 | "environmentVariables": { 27 | "ASPNETCORE_ENVIRONMENT": "Development" 28 | } 29 | }, 30 | "Docker": { 31 | "commandName": "Docker", 32 | "launchBrowser": true, 33 | "launchUrl": "{Scheme}://{ServiceHost}:{ServicePort}/weatherforecast", 34 | "publishAllPorts": true 35 | } 36 | } 37 | } -------------------------------------------------------------------------------- /CustomerWebApi/appsettings.Development.json: -------------------------------------------------------------------------------- 1 | { 2 | "Logging": { 3 | "LogLevel": { 4 | "Default": "Information", 5 | "Microsoft.AspNetCore": "Warning" 6 | } 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /CustomerWebApi/appsettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "Logging": { 3 | "LogLevel": { 4 | "Default": "Information", 5 | "Microsoft.AspNetCore": "Warning" 6 | } 7 | }, 8 | "AllowedHosts": "*" 9 | } 10 | -------------------------------------------------------------------------------- /JwtAuthenticationManager/CustomJwtAuthExtension.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Authentication.JwtBearer; 2 | using Microsoft.Extensions.DependencyInjection; 3 | using Microsoft.IdentityModel.Tokens; 4 | using System.Text; 5 | 6 | namespace JwtAuthenticationManager 7 | { 8 | public static class CustomJwtAuthExtension 9 | { 10 | public static void AddCustomJwtAuthentication(this IServiceCollection services) 11 | { 12 | services.AddAuthentication(o => 13 | { 14 | o.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; 15 | o.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; 16 | }).AddJwtBearer(o => 17 | { 18 | o.RequireHttpsMetadata = false; 19 | o.SaveToken = true; 20 | o.TokenValidationParameters = new TokenValidationParameters 21 | { 22 | ValidateIssuerSigningKey = true, 23 | ValidateIssuer = false, 24 | ValidateAudience = false, 25 | IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(JwtTokenHandler.JWT_SECURITY_KEY)) 26 | }; 27 | }); 28 | } 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /JwtAuthenticationManager/JwtAuthenticationManager.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | net6.0 5 | enable 6 | enable 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | -------------------------------------------------------------------------------- /JwtAuthenticationManager/JwtTokenHandler.cs: -------------------------------------------------------------------------------- 1 | using JwtAuthenticationManager.Models; 2 | using Microsoft.IdentityModel.Tokens; 3 | using System.IdentityModel.Tokens.Jwt; 4 | using System.Security.Claims; 5 | using System.Text; 6 | 7 | namespace JwtAuthenticationManager 8 | { 9 | public class JwtTokenHandler 10 | { 11 | public const string JWT_SECURITY_KEY = "yPkCqn4kSWLtaJwXvN2jGzpQRyTZ3gdXkt7FeBJP"; 12 | private const int JWT_TOKEN_VALIDITY_MINS = 20; 13 | private readonly List _userAccountList; 14 | 15 | public JwtTokenHandler() 16 | { 17 | _userAccountList = new List 18 | { 19 | new UserAccount{ UserName = "admin", Password = "admin123", Role = "Administrator" }, 20 | new UserAccount{ UserName = "user01", Password = "user01", Role = "User" }, 21 | }; 22 | } 23 | 24 | public AuthenticationResponse? GenerateJwtToken(AuthenticationRequest authenticationRequest) 25 | { 26 | if (string.IsNullOrWhiteSpace(authenticationRequest.UserName) || string.IsNullOrWhiteSpace(authenticationRequest.Password)) 27 | return null; 28 | 29 | /* Validation */ 30 | var userAccount = _userAccountList.Where(x => x.UserName == authenticationRequest.UserName && x.Password == authenticationRequest.Password).FirstOrDefault(); 31 | if (userAccount == null) return null; 32 | 33 | var tokenExpiryTimeStamp = DateTime.Now.AddMinutes(JWT_TOKEN_VALIDITY_MINS); 34 | var tokenKey = Encoding.ASCII.GetBytes(JWT_SECURITY_KEY); 35 | var claimsIdentity = new ClaimsIdentity(new List 36 | { 37 | new Claim(JwtRegisteredClaimNames.Name, authenticationRequest.UserName), 38 | new Claim("Role", userAccount.Role) 39 | }); 40 | 41 | var signingCredentials = new SigningCredentials( 42 | new SymmetricSecurityKey(tokenKey), 43 | SecurityAlgorithms.HmacSha256Signature); 44 | 45 | var securityTokenDescriptor = new SecurityTokenDescriptor 46 | { 47 | Subject = claimsIdentity, 48 | Expires = tokenExpiryTimeStamp, 49 | SigningCredentials = signingCredentials 50 | }; 51 | 52 | var jwtSecurityTokenHandler = new JwtSecurityTokenHandler(); 53 | var securityToken = jwtSecurityTokenHandler.CreateToken(securityTokenDescriptor); 54 | var token = jwtSecurityTokenHandler.WriteToken(securityToken); 55 | 56 | return new AuthenticationResponse 57 | { 58 | UserName = userAccount.UserName, 59 | ExpiresIn = (int)tokenExpiryTimeStamp.Subtract(DateTime.Now).TotalSeconds, 60 | JwtToken = token 61 | }; 62 | } 63 | } 64 | } 65 | -------------------------------------------------------------------------------- /JwtAuthenticationManager/Models/AuthenticationRequest.cs: -------------------------------------------------------------------------------- 1 | namespace JwtAuthenticationManager.Models 2 | { 3 | public class AuthenticationRequest 4 | { 5 | public string UserName { get; set; } 6 | public string Password { get; set; } 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /JwtAuthenticationManager/Models/AuthenticationResponse.cs: -------------------------------------------------------------------------------- 1 | namespace JwtAuthenticationManager.Models 2 | { 3 | public class AuthenticationResponse 4 | { 5 | public string UserName { get; set; } 6 | public string JwtToken { get; set; } 7 | public int ExpiresIn { get; set; } 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /JwtAuthenticationManager/Models/UserAccount.cs: -------------------------------------------------------------------------------- 1 | namespace JwtAuthenticationManager.Models 2 | { 3 | public class UserAccount 4 | { 5 | public string UserName { get; set; } 6 | public string Password { get; set; } 7 | public string Role { get; set; } 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /OcelotDemoSolution.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio Version 17 4 | VisualStudioVersion = 17.2.32519.379 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Microservices", "Microservices", "{8B3334A0-D766-4442-B7E1-AD89940F2AEC}" 7 | EndProject 8 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "CustomerWebApi", "CustomerWebApi\CustomerWebApi.csproj", "{90F7B965-8F15-4F6E-B750-335FB23A78DB}" 9 | EndProject 10 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "OrderWebApi", "OrderWebApi\OrderWebApi.csproj", "{9B0A674A-CD76-4D95-867A-D8640A7D9696}" 11 | EndProject 12 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ProductWebApi", "ProductWebApi\ProductWebApi.csproj", "{CEF024B3-E7E4-49E6-909E-CDDC9866C662}" 13 | EndProject 14 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "ApiGateway", "ApiGateway", "{4836CCA0-7102-4DF2-B273-FF0C8641333C}" 15 | EndProject 16 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ApiGateway", "ApiGateway\ApiGateway.csproj", "{762E8B2B-C3FE-45BF-9F69-3E5EEA83B4BB}" 17 | EndProject 18 | Project("{E53339B2-1760-4266-BCC7-CA923CBCF16C}") = "docker-compose", "docker-compose.dcproj", "{D00B1C36-22E7-4B17-96C4-99E0EAAFA3ED}" 19 | EndProject 20 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "JwtAuthenticationManager", "JwtAuthenticationManager\JwtAuthenticationManager.csproj", "{4E7C769E-AC3A-4675-BFB7-CDBCEF42E757}" 21 | EndProject 22 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AuthenticationWebApi", "AuthenticationWebApi\AuthenticationWebApi.csproj", "{DACEA6BD-DD3B-468A-9481-14E4541AB4C2}" 23 | EndProject 24 | Global 25 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 26 | Debug|Any CPU = Debug|Any CPU 27 | Release|Any CPU = Release|Any CPU 28 | EndGlobalSection 29 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 30 | {90F7B965-8F15-4F6E-B750-335FB23A78DB}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 31 | {90F7B965-8F15-4F6E-B750-335FB23A78DB}.Debug|Any CPU.Build.0 = Debug|Any CPU 32 | {90F7B965-8F15-4F6E-B750-335FB23A78DB}.Release|Any CPU.ActiveCfg = Release|Any CPU 33 | {90F7B965-8F15-4F6E-B750-335FB23A78DB}.Release|Any CPU.Build.0 = Release|Any CPU 34 | {9B0A674A-CD76-4D95-867A-D8640A7D9696}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 35 | {9B0A674A-CD76-4D95-867A-D8640A7D9696}.Debug|Any CPU.Build.0 = Debug|Any CPU 36 | {9B0A674A-CD76-4D95-867A-D8640A7D9696}.Release|Any CPU.ActiveCfg = Release|Any CPU 37 | {9B0A674A-CD76-4D95-867A-D8640A7D9696}.Release|Any CPU.Build.0 = Release|Any CPU 38 | {CEF024B3-E7E4-49E6-909E-CDDC9866C662}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 39 | {CEF024B3-E7E4-49E6-909E-CDDC9866C662}.Debug|Any CPU.Build.0 = Debug|Any CPU 40 | {CEF024B3-E7E4-49E6-909E-CDDC9866C662}.Release|Any CPU.ActiveCfg = Release|Any CPU 41 | {CEF024B3-E7E4-49E6-909E-CDDC9866C662}.Release|Any CPU.Build.0 = Release|Any CPU 42 | {762E8B2B-C3FE-45BF-9F69-3E5EEA83B4BB}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 43 | {762E8B2B-C3FE-45BF-9F69-3E5EEA83B4BB}.Debug|Any CPU.Build.0 = Debug|Any CPU 44 | {762E8B2B-C3FE-45BF-9F69-3E5EEA83B4BB}.Release|Any CPU.ActiveCfg = Release|Any CPU 45 | {762E8B2B-C3FE-45BF-9F69-3E5EEA83B4BB}.Release|Any CPU.Build.0 = Release|Any CPU 46 | {D00B1C36-22E7-4B17-96C4-99E0EAAFA3ED}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 47 | {D00B1C36-22E7-4B17-96C4-99E0EAAFA3ED}.Debug|Any CPU.Build.0 = Debug|Any CPU 48 | {D00B1C36-22E7-4B17-96C4-99E0EAAFA3ED}.Release|Any CPU.ActiveCfg = Release|Any CPU 49 | {D00B1C36-22E7-4B17-96C4-99E0EAAFA3ED}.Release|Any CPU.Build.0 = Release|Any CPU 50 | {4E7C769E-AC3A-4675-BFB7-CDBCEF42E757}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 51 | {4E7C769E-AC3A-4675-BFB7-CDBCEF42E757}.Debug|Any CPU.Build.0 = Debug|Any CPU 52 | {4E7C769E-AC3A-4675-BFB7-CDBCEF42E757}.Release|Any CPU.ActiveCfg = Release|Any CPU 53 | {4E7C769E-AC3A-4675-BFB7-CDBCEF42E757}.Release|Any CPU.Build.0 = Release|Any CPU 54 | {DACEA6BD-DD3B-468A-9481-14E4541AB4C2}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 55 | {DACEA6BD-DD3B-468A-9481-14E4541AB4C2}.Debug|Any CPU.Build.0 = Debug|Any CPU 56 | {DACEA6BD-DD3B-468A-9481-14E4541AB4C2}.Release|Any CPU.ActiveCfg = Release|Any CPU 57 | {DACEA6BD-DD3B-468A-9481-14E4541AB4C2}.Release|Any CPU.Build.0 = Release|Any CPU 58 | EndGlobalSection 59 | GlobalSection(SolutionProperties) = preSolution 60 | HideSolutionNode = FALSE 61 | EndGlobalSection 62 | GlobalSection(NestedProjects) = preSolution 63 | {90F7B965-8F15-4F6E-B750-335FB23A78DB} = {8B3334A0-D766-4442-B7E1-AD89940F2AEC} 64 | {9B0A674A-CD76-4D95-867A-D8640A7D9696} = {8B3334A0-D766-4442-B7E1-AD89940F2AEC} 65 | {CEF024B3-E7E4-49E6-909E-CDDC9866C662} = {8B3334A0-D766-4442-B7E1-AD89940F2AEC} 66 | {762E8B2B-C3FE-45BF-9F69-3E5EEA83B4BB} = {4836CCA0-7102-4DF2-B273-FF0C8641333C} 67 | EndGlobalSection 68 | GlobalSection(ExtensibilityGlobals) = postSolution 69 | SolutionGuid = {BE7C3D52-B773-4BFD-B659-31451DC97995} 70 | EndGlobalSection 71 | EndGlobal 72 | -------------------------------------------------------------------------------- /OrderWebApi/Controllers/OrderController.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Http; 2 | using Microsoft.AspNetCore.Mvc; 3 | using MongoDB.Driver; 4 | using OrderWebApi.Models; 5 | 6 | namespace OrderWebApi.Controllers 7 | { 8 | [Route("api/[controller]")] 9 | [ApiController] 10 | public class OrderController : ControllerBase 11 | { 12 | private readonly IMongoCollection _orderCollection; 13 | 14 | public OrderController() 15 | { 16 | var dbHost = Environment.GetEnvironmentVariable("DB_HOST"); 17 | var dbName = Environment.GetEnvironmentVariable("DB_NAME"); 18 | var connectionString = $"mongodb://{dbHost}:27017/{dbName}"; 19 | 20 | var mongoUrl = MongoUrl.Create(connectionString); 21 | var mongoClient = new MongoClient(mongoUrl); 22 | var database = mongoClient.GetDatabase(mongoUrl.DatabaseName); 23 | _orderCollection = database.GetCollection("order"); 24 | } 25 | 26 | [HttpGet] 27 | public async Task>> GetOrders() 28 | { 29 | return await _orderCollection.Find(Builders.Filter.Empty).ToListAsync(); 30 | } 31 | 32 | [HttpGet("{orderId}")] 33 | public async Task> GetById(string orderId) 34 | { 35 | var filterDefinition = Builders.Filter.Eq(x => x.OrderId, orderId); 36 | return await _orderCollection.Find(filterDefinition).SingleOrDefaultAsync(); 37 | } 38 | 39 | [HttpPost] 40 | public async Task Create(Order order) 41 | { 42 | await _orderCollection.InsertOneAsync(order); 43 | return Ok(); 44 | } 45 | 46 | [HttpPut] 47 | public async Task Update(Order order) 48 | { 49 | var filterDefinition = Builders.Filter.Eq(x => x.OrderId, order.OrderId); 50 | await _orderCollection.ReplaceOneAsync(filterDefinition, order); 51 | return Ok(); 52 | } 53 | 54 | [HttpDelete("{orderId}")] 55 | public async Task Delete(string orderId) 56 | { 57 | var filterDefinition = Builders.Filter.Eq(x => x.OrderId, orderId); 58 | await _orderCollection.DeleteOneAsync(filterDefinition); 59 | return Ok(); 60 | } 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /OrderWebApi/Dockerfile: -------------------------------------------------------------------------------- 1 | #See https://aka.ms/containerfastmode to understand how Visual Studio uses this Dockerfile to build your images for faster debugging. 2 | 3 | FROM mcr.microsoft.com/dotnet/aspnet:6.0 AS base 4 | WORKDIR /app 5 | EXPOSE 80 6 | 7 | FROM mcr.microsoft.com/dotnet/sdk:6.0 AS build 8 | WORKDIR /src 9 | COPY ["OrderWebApi/OrderWebApi.csproj", "OrderWebApi/"] 10 | RUN dotnet restore "OrderWebApi/OrderWebApi.csproj" 11 | COPY . . 12 | WORKDIR "/src/OrderWebApi" 13 | RUN dotnet build "OrderWebApi.csproj" -c Release -o /app/build 14 | 15 | FROM build AS publish 16 | RUN dotnet publish "OrderWebApi.csproj" -c Release -o /app/publish 17 | 18 | FROM base AS final 19 | WORKDIR /app 20 | COPY --from=publish /app/publish . 21 | ENTRYPOINT ["dotnet", "OrderWebApi.dll"] -------------------------------------------------------------------------------- /OrderWebApi/Models/Order.cs: -------------------------------------------------------------------------------- 1 | using MongoDB.Bson; 2 | using MongoDB.Bson.Serialization.Attributes; 3 | 4 | namespace OrderWebApi.Models 5 | { 6 | [Serializable, BsonIgnoreExtraElements] 7 | public class Order 8 | { 9 | [BsonId, BsonElement("_id"), BsonRepresentation(BsonType.ObjectId)] 10 | public string OrderId { get; set; } 11 | 12 | [BsonElement("customer_id"), BsonRepresentation(BsonType.Int32)] 13 | public int CustomerId { get; set; } 14 | 15 | [BsonElement("ordered_on"), BsonRepresentation(BsonType.DateTime)] 16 | public DateTime OrderedOn { get; set; } 17 | 18 | [BsonElement("order_details")] 19 | public List OrderDetails { get; set; } 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /OrderWebApi/Models/OrderDetail.cs: -------------------------------------------------------------------------------- 1 | using MongoDB.Bson; 2 | using MongoDB.Bson.Serialization.Attributes; 3 | 4 | namespace OrderWebApi.Models 5 | { 6 | [Serializable, BsonIgnoreExtraElements] 7 | public class OrderDetail 8 | { 9 | [BsonElement("product_id"), BsonRepresentation(BsonType.Int32)] 10 | public int ProductId { get; set; } 11 | 12 | [BsonElement("quantity"), BsonRepresentation(BsonType.Decimal128)] 13 | public decimal Quantity { get; set; } 14 | 15 | [BsonElement("unit_price"), BsonRepresentation(BsonType.Decimal128)] 16 | public decimal UnitPrice { get; set; } 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /OrderWebApi/OrderWebApi.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | net6.0 5 | enable 6 | enable 7 | Linux 8 | ..\docker-compose.dcproj 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | -------------------------------------------------------------------------------- /OrderWebApi/Program.cs: -------------------------------------------------------------------------------- 1 | var builder = WebApplication.CreateBuilder(args); 2 | 3 | // Add services to the container. 4 | 5 | builder.Services.AddControllers(); 6 | 7 | var app = builder.Build(); 8 | 9 | // Configure the HTTP request pipeline. 10 | 11 | app.UseAuthorization(); 12 | 13 | app.MapControllers(); 14 | 15 | app.Run(); 16 | -------------------------------------------------------------------------------- /OrderWebApi/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:26376", 8 | "sslPort": 0 9 | } 10 | }, 11 | "profiles": { 12 | "OrderWebApi": { 13 | "commandName": "Project", 14 | "launchBrowser": true, 15 | "launchUrl": "weatherforecast", 16 | "environmentVariables": { 17 | "ASPNETCORE_ENVIRONMENT": "Development" 18 | }, 19 | "applicationUrl": "http://localhost:5117", 20 | "dotnetRunMessages": true 21 | }, 22 | "IIS Express": { 23 | "commandName": "IISExpress", 24 | "launchBrowser": true, 25 | "launchUrl": "weatherforecast", 26 | "environmentVariables": { 27 | "ASPNETCORE_ENVIRONMENT": "Development" 28 | } 29 | }, 30 | "Docker": { 31 | "commandName": "Docker", 32 | "launchBrowser": true, 33 | "launchUrl": "{Scheme}://{ServiceHost}:{ServicePort}/weatherforecast", 34 | "publishAllPorts": true 35 | } 36 | } 37 | } -------------------------------------------------------------------------------- /OrderWebApi/appsettings.Development.json: -------------------------------------------------------------------------------- 1 | { 2 | "Logging": { 3 | "LogLevel": { 4 | "Default": "Information", 5 | "Microsoft.AspNetCore": "Warning" 6 | } 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /OrderWebApi/appsettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "Logging": { 3 | "LogLevel": { 4 | "Default": "Information", 5 | "Microsoft.AspNetCore": "Warning" 6 | } 7 | }, 8 | "AllowedHosts": "*" 9 | } 10 | -------------------------------------------------------------------------------- /ProductWebApi/Controllers/ProductController.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Http; 2 | using Microsoft.AspNetCore.Mvc; 3 | using ProductWebApi.Models; 4 | 5 | namespace ProductWebApi.Controllers 6 | { 7 | [Route("api/[controller]")] 8 | [ApiController] 9 | public class ProductController : ControllerBase 10 | { 11 | private readonly ProductDbContext _dbContext; 12 | 13 | public ProductController(ProductDbContext productDbContext) 14 | { 15 | _dbContext = productDbContext; 16 | } 17 | 18 | [HttpGet] 19 | public ActionResult> GetProducts() 20 | { 21 | return _dbContext.Products; 22 | } 23 | 24 | [HttpGet("{productId:int}")] 25 | public async Task> GetById(int productId) 26 | { 27 | var product = await _dbContext.Products.FindAsync(productId); 28 | return product; 29 | } 30 | 31 | [HttpPost] 32 | public async Task Create(Product product) 33 | { 34 | await _dbContext.Products.AddAsync(product); 35 | await _dbContext.SaveChangesAsync(); 36 | return Ok(); 37 | } 38 | 39 | [HttpPut] 40 | public async Task Update(Product product) 41 | { 42 | _dbContext.Products.Update(product); 43 | await _dbContext.SaveChangesAsync(); 44 | return Ok(); 45 | } 46 | 47 | [HttpDelete("{productId:int}")] 48 | public async Task Delete(int productId) 49 | { 50 | var product = await _dbContext.Products.FindAsync(productId); 51 | _dbContext.Products.Remove(product); 52 | await _dbContext.SaveChangesAsync(); 53 | return Ok(); 54 | } 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /ProductWebApi/Dockerfile: -------------------------------------------------------------------------------- 1 | #See https://aka.ms/containerfastmode to understand how Visual Studio uses this Dockerfile to build your images for faster debugging. 2 | 3 | FROM mcr.microsoft.com/dotnet/aspnet:6.0 AS base 4 | WORKDIR /app 5 | EXPOSE 80 6 | 7 | FROM mcr.microsoft.com/dotnet/sdk:6.0 AS build 8 | WORKDIR /src 9 | COPY ["ProductWebApi/ProductWebApi.csproj", "ProductWebApi/"] 10 | RUN dotnet restore "ProductWebApi/ProductWebApi.csproj" 11 | COPY . . 12 | WORKDIR "/src/ProductWebApi" 13 | RUN dotnet build "ProductWebApi.csproj" -c Release -o /app/build 14 | 15 | FROM build AS publish 16 | RUN dotnet publish "ProductWebApi.csproj" -c Release -o /app/publish 17 | 18 | FROM base AS final 19 | WORKDIR /app 20 | COPY --from=publish /app/publish . 21 | ENTRYPOINT ["dotnet", "ProductWebApi.dll"] 22 | -------------------------------------------------------------------------------- /ProductWebApi/Models/Product.cs: -------------------------------------------------------------------------------- 1 | using System.ComponentModel.DataAnnotations; 2 | using System.ComponentModel.DataAnnotations.Schema; 3 | 4 | namespace ProductWebApi.Models 5 | { 6 | [Table("product")] 7 | public class Product 8 | { 9 | [Key] 10 | [Column("product_id")] 11 | public int ProductId { get; set; } 12 | 13 | [Column("product_name")] 14 | public string ProductName { get; set; } 15 | 16 | [Column("product_code")] 17 | public string ProductCode { get; set; } 18 | 19 | [Column("product_price")] 20 | public decimal ProductPrice { get; set; } 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /ProductWebApi/ProductDbContext.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.EntityFrameworkCore; 2 | using Microsoft.EntityFrameworkCore.Infrastructure; 3 | using Microsoft.EntityFrameworkCore.Storage; 4 | using ProductWebApi.Models; 5 | 6 | namespace ProductWebApi 7 | { 8 | public class ProductDbContext : DbContext 9 | { 10 | public DbSet Products { get; set; } 11 | 12 | public ProductDbContext(DbContextOptions dbContextOptions) : base(dbContextOptions) 13 | { 14 | try 15 | { 16 | var databaseCreator = Database.GetService() as RelationalDatabaseCreator; 17 | if (databaseCreator != null) 18 | { 19 | // Create Database if cannot connect 20 | if (!databaseCreator.CanConnect()) databaseCreator.Create(); 21 | 22 | // Create Tables if no tables exist 23 | if (!databaseCreator.HasTables()) databaseCreator.CreateTables(); 24 | } 25 | } 26 | catch (Exception ex) 27 | { 28 | Console.WriteLine(ex.Message); 29 | } 30 | } 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /ProductWebApi/ProductWebApi.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | net6.0 5 | enable 6 | enable 7 | Linux 8 | ..\docker-compose.dcproj 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | -------------------------------------------------------------------------------- /ProductWebApi/Program.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.EntityFrameworkCore; 2 | using ProductWebApi; 3 | 4 | var builder = WebApplication.CreateBuilder(args); 5 | 6 | // Add services to the container. 7 | 8 | builder.Services.AddControllers(); 9 | 10 | /* Database Context Dependency Injection */ 11 | var dbHost = Environment.GetEnvironmentVariable("DB_HOST"); 12 | var dbName = Environment.GetEnvironmentVariable("DB_NAME"); 13 | var dbPassword = Environment.GetEnvironmentVariable("DB_ROOT_PASSWORD"); 14 | 15 | var connectionString = $"server={dbHost};port=3306;database={dbName};user=root;password={dbPassword}"; 16 | builder.Services.AddDbContext(o => o.UseMySQL(connectionString)); 17 | /* ===================================== */ 18 | 19 | var app = builder.Build(); 20 | 21 | // Configure the HTTP request pipeline. 22 | 23 | app.UseAuthorization(); 24 | 25 | app.MapControllers(); 26 | 27 | app.Run(); 28 | -------------------------------------------------------------------------------- /ProductWebApi/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:43575", 8 | "sslPort": 0 9 | } 10 | }, 11 | "profiles": { 12 | "ProductWebApi": { 13 | "commandName": "Project", 14 | "launchBrowser": true, 15 | "launchUrl": "weatherforecast", 16 | "environmentVariables": { 17 | "ASPNETCORE_ENVIRONMENT": "Development" 18 | }, 19 | "applicationUrl": "http://localhost:5197", 20 | "dotnetRunMessages": true 21 | }, 22 | "IIS Express": { 23 | "commandName": "IISExpress", 24 | "launchBrowser": true, 25 | "launchUrl": "weatherforecast", 26 | "environmentVariables": { 27 | "ASPNETCORE_ENVIRONMENT": "Development" 28 | } 29 | }, 30 | "Docker": { 31 | "commandName": "Docker", 32 | "launchBrowser": true, 33 | "launchUrl": "{Scheme}://{ServiceHost}:{ServicePort}/weatherforecast", 34 | "publishAllPorts": true 35 | } 36 | } 37 | } -------------------------------------------------------------------------------- /ProductWebApi/appsettings.Development.json: -------------------------------------------------------------------------------- 1 | { 2 | "Logging": { 3 | "LogLevel": { 4 | "Default": "Information", 5 | "Microsoft.AspNetCore": "Warning" 6 | } 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /ProductWebApi/appsettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "Logging": { 3 | "LogLevel": { 4 | "Default": "Information", 5 | "Microsoft.AspNetCore": "Warning" 6 | } 7 | }, 8 | "AllowedHosts": "*" 9 | } 10 | -------------------------------------------------------------------------------- /docker-compose.dcproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 2.1 5 | Linux 6 | d00b1c36-22e7-4b17-96c4-99e0eaafa3ed 7 | LaunchBrowser 8 | {Scheme}://localhost:{ServicePort}/weatherforecast 9 | customerwebapi 10 | 11 | 12 | 13 | docker-compose.yml 14 | 15 | 16 | 17 | 18 | -------------------------------------------------------------------------------- /docker-compose.override.yml: -------------------------------------------------------------------------------- 1 | version: '3.4' 2 | 3 | services: 4 | customerwebapi: 5 | environment: 6 | - ASPNETCORE_ENVIRONMENT=Development 7 | ports: 8 | - "80" 9 | 10 | productwebapi: 11 | environment: 12 | - ASPNETCORE_ENVIRONMENT=Development 13 | ports: 14 | - "80" 15 | 16 | 17 | orderwebapi: 18 | environment: 19 | - ASPNETCORE_ENVIRONMENT=Development 20 | ports: 21 | - "80" 22 | 23 | 24 | apigateway: 25 | environment: 26 | - ASPNETCORE_ENVIRONMENT=Development 27 | ports: 28 | - "80" 29 | authenticationwebapi: 30 | environment: 31 | - ASPNETCORE_ENVIRONMENT=Development 32 | ports: 33 | - "80" 34 | 35 | -------------------------------------------------------------------------------- /docker-compose.yml: -------------------------------------------------------------------------------- 1 | version: '3.4' 2 | 3 | networks: 4 | backend: 5 | 6 | services: 7 | customerdb: 8 | container_name: customer-db 9 | image: mcr.microsoft.com/mssql/server:2019-latest 10 | environment: 11 | - ACCEPT_EULA=Y 12 | - SA_PASSWORD=password@12345# 13 | networks: 14 | - backend 15 | ports: 16 | - 18001:1433 17 | 18 | customerwebapi: 19 | container_name: customer-api 20 | image: ${DOCKER_REGISTRY-}customerwebapi 21 | build: 22 | context: . 23 | dockerfile: CustomerWebApi/Dockerfile 24 | networks: 25 | - backend 26 | environment: 27 | - DB_HOST=customerdb 28 | - DB_NAME=dms_customer 29 | - DB_SA_PASSWORD=password@12345# 30 | 31 | productdb: 32 | container_name: product-db 33 | image: mysql:8.0.29-oracle 34 | environment: 35 | - MYSQL_ROOT_PASSWORD=password@12345# 36 | ports: 37 | - 18003:3306 38 | networks: 39 | - backend 40 | 41 | productwebapi: 42 | container_name: product-api 43 | image: ${DOCKER_REGISTRY-}productwebapi 44 | build: 45 | context: . 46 | dockerfile: ProductWebApi/Dockerfile 47 | networks: 48 | - backend 49 | environment: 50 | - DB_HOST=productdb 51 | - DB_NAME=dms_product 52 | - DB_ROOT_PASSWORD=password@12345# 53 | 54 | orderdb: 55 | container_name: order-db 56 | image: mongo 57 | ports: 58 | - 18005:27017 59 | networks: 60 | - backend 61 | 62 | orderwebapi: 63 | container_name: order-api 64 | image: ${DOCKER_REGISTRY-}orderwebapi 65 | build: 66 | context: . 67 | dockerfile: OrderWebApi/Dockerfile 68 | networks: 69 | - backend 70 | environment: 71 | - DB_HOST=orderdb 72 | - DB_NAME=dms_order 73 | 74 | apigateway: 75 | container_name: api-gateway 76 | image: ${DOCKER_REGISTRY-}apigateway 77 | build: 78 | context: . 79 | dockerfile: ApiGateway/Dockerfile 80 | ports: 81 | - 8001:80 82 | networks: 83 | - backend 84 | 85 | authenticationwebapi: 86 | container_name: authentication-api 87 | image: ${DOCKER_REGISTRY-}authenticationwebapi 88 | build: 89 | context: . 90 | dockerfile: AuthenticationWebApi/Dockerfile 91 | networks: 92 | - backend --------------------------------------------------------------------------------