├── .gitignore └── APIContagem ├── .vscode ├── launch.json └── tasks.json ├── APIContagem.csproj ├── Contador.cs ├── Controllers ├── ContadorController.cs └── LoginController.cs ├── Models └── ResultadoContador.cs ├── Program.cs ├── Properties └── launchSettings.json ├── Security ├── AccessManager.cs ├── Classes.cs ├── Data │ ├── APISecurityDbContext.cs │ └── IdentityInitializer.cs ├── JwtSecurityExtension.cs └── SigningConfigurations.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 | -------------------------------------------------------------------------------- /APIContagem/.vscode/launch.json: -------------------------------------------------------------------------------- 1 | { 2 | // Use IntelliSense to find out which attributes exist for C# debugging 3 | // Use hover for the description of the existing attributes 4 | // For further information visit https://github.com/OmniSharp/omnisharp-vscode/blob/master/debugger-launchjson.md 5 | "version": "0.2.0", 6 | "configurations": [ 7 | { 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/net5.0/APIContagem.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 | }, 22 | "env": { 23 | "ASPNETCORE_ENVIRONMENT": "Development" 24 | }, 25 | "sourceFileMap": { 26 | "/Views": "${workspaceFolder}/Views" 27 | } 28 | }, 29 | { 30 | "name": ".NET Core Attach", 31 | "type": "coreclr", 32 | "request": "attach", 33 | "processId": "${command:pickProcess}" 34 | } 35 | ] 36 | } -------------------------------------------------------------------------------- /APIContagem/.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}/APIContagem.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}/APIContagem.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}/APIContagem.csproj", 36 | "/property:GenerateFullPaths=true", 37 | "/consoleloggerparameters:NoSummary" 38 | ], 39 | "problemMatcher": "$msCompile" 40 | } 41 | ] 42 | } -------------------------------------------------------------------------------- /APIContagem/APIContagem.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | net5.0 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | -------------------------------------------------------------------------------- /APIContagem/Contador.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Reflection; 3 | using System.Runtime.Versioning; 4 | 5 | namespace APIContagem 6 | { 7 | public class Contador 8 | { 9 | private static readonly string _LOCAL; 10 | private static readonly string _KERNEL; 11 | private static readonly string _TARGET_FRAMEWORK; 12 | 13 | static Contador() 14 | { 15 | _LOCAL = Environment.MachineName; 16 | _KERNEL = Environment.OSVersion.VersionString; 17 | _TARGET_FRAMEWORK = Assembly 18 | .GetEntryAssembly()? 19 | .GetCustomAttribute()? 20 | .FrameworkName; 21 | } 22 | 23 | private int _valorAtual = 0; 24 | 25 | public int ValorAtual { get => _valorAtual; } 26 | public string Local { get => _LOCAL; } 27 | public string Kernel { get => _KERNEL; } 28 | public string TargetFramework { get => _TARGET_FRAMEWORK; } 29 | 30 | public void Incrementar() 31 | { 32 | _valorAtual++; 33 | } 34 | } 35 | } -------------------------------------------------------------------------------- /APIContagem/Controllers/ContadorController.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Authorization; 2 | using Microsoft.AspNetCore.Mvc; 3 | using Microsoft.Extensions.Configuration; 4 | using Microsoft.Extensions.Logging; 5 | using APIContagem.Models; 6 | 7 | namespace APIContagem.Controllers 8 | { 9 | [ApiController] 10 | [Route("[controller]")] 11 | [Authorize("Bearer")] 12 | public class ContadorController : ControllerBase 13 | { 14 | private static readonly Contador _CONTADOR = new Contador(); 15 | private readonly ILogger _logger; 16 | private readonly IConfiguration _configuration; 17 | 18 | public ContadorController(ILogger logger, 19 | IConfiguration configuration) 20 | { 21 | _logger = logger; 22 | _configuration = configuration; 23 | } 24 | 25 | [HttpGet] 26 | public ResultadoContador Get() 27 | { 28 | lock (_CONTADOR) 29 | { 30 | _CONTADOR.Incrementar(); 31 | _logger.LogInformation($"Contador - Valor atual: {_CONTADOR.ValorAtual}"); 32 | 33 | return new() 34 | { 35 | ValorAtual = _CONTADOR.ValorAtual, 36 | Local = _CONTADOR.Local, 37 | Kernel = _CONTADOR.Kernel, 38 | TargetFramework = _CONTADOR.TargetFramework, 39 | MensagemFixa = "Teste", 40 | MensagemVariavel = _configuration["MensagemVariavel"] 41 | }; 42 | } 43 | } 44 | } 45 | } -------------------------------------------------------------------------------- /APIContagem/Controllers/LoginController.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Mvc; 2 | using APIContagem.Security; 3 | 4 | namespace APIContagem.Controllers 5 | { 6 | [ApiController] 7 | [Route("[controller]")] 8 | public class LoginController : ControllerBase 9 | { 10 | [HttpPost] 11 | public Token Post(AccessCredentials credenciais, 12 | [FromServices]AccessManager accessManager) 13 | { 14 | if (accessManager.ValidateCredentials(credenciais)) 15 | return accessManager.GenerateToken(credenciais); 16 | else 17 | return new () 18 | { 19 | Authenticated = false, 20 | Message = "Falha ao autenticar" 21 | }; 22 | } 23 | } 24 | } -------------------------------------------------------------------------------- /APIContagem/Models/ResultadoContador.cs: -------------------------------------------------------------------------------- 1 | namespace APIContagem.Models 2 | { 3 | public class ResultadoContador 4 | { 5 | public int ValorAtual { get; set; } 6 | public string Local { get; set; } 7 | public string Kernel { get; set; } 8 | public string TargetFramework { get; set; } 9 | public string MensagemFixa { get; set; } 10 | public object MensagemVariavel { get; set; } 11 | } 12 | } -------------------------------------------------------------------------------- /APIContagem/Program.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Threading.Tasks; 5 | using Microsoft.AspNetCore.Hosting; 6 | using Microsoft.Extensions.Configuration; 7 | using Microsoft.Extensions.Hosting; 8 | using Microsoft.Extensions.Logging; 9 | 10 | namespace APIContagem 11 | { 12 | public class Program 13 | { 14 | public static void Main(string[] args) 15 | { 16 | CreateHostBuilder(args).Build().Run(); 17 | } 18 | 19 | public static IHostBuilder CreateHostBuilder(string[] args) => 20 | Host.CreateDefaultBuilder(args) 21 | .ConfigureWebHostDefaults(webBuilder => 22 | { 23 | webBuilder.UseStartup(); 24 | }); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /APIContagem/Properties/launchSettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "http://json.schemastore.org/launchsettings.json", 3 | "iisSettings": { 4 | "windowsAuthentication": false, 5 | "anonymousAuthentication": true, 6 | "iisExpress": { 7 | "applicationUrl": "http://localhost:60107", 8 | "sslPort": 44336 9 | } 10 | }, 11 | "profiles": { 12 | "IIS Express": { 13 | "commandName": "IISExpress", 14 | "launchBrowser": true, 15 | "launchUrl": "swagger", 16 | "environmentVariables": { 17 | "ASPNETCORE_ENVIRONMENT": "Development" 18 | } 19 | }, 20 | "APIContagem": { 21 | "commandName": "Project", 22 | "dotnetRunMessages": "true", 23 | "launchBrowser": true, 24 | "launchUrl": "swagger", 25 | "applicationUrl": "http://localhost:5000", 26 | "environmentVariables": { 27 | "ASPNETCORE_ENVIRONMENT": "Development" 28 | } 29 | } 30 | } 31 | } -------------------------------------------------------------------------------- /APIContagem/Security/AccessManager.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.IdentityModel.Tokens.Jwt; 3 | using System.Security.Claims; 4 | using System.Security.Principal; 5 | using Microsoft.AspNetCore.Identity; 6 | using Microsoft.IdentityModel.Tokens; 7 | using Microsoft.Extensions.Caching.Distributed; 8 | using System.Text.Json; 9 | 10 | namespace APIContagem.Security 11 | { 12 | public class AccessManager 13 | { 14 | private UserManager _userManager; 15 | private SignInManager _signInManager; 16 | private SigningConfigurations _signingConfigurations; 17 | private TokenConfigurations _tokenConfigurations; 18 | private IDistributedCache _cache; 19 | 20 | public AccessManager( 21 | UserManager userManager, 22 | SignInManager signInManager, 23 | SigningConfigurations signingConfigurations, 24 | TokenConfigurations tokenConfigurations, 25 | IDistributedCache cache) 26 | { 27 | _userManager = userManager; 28 | _signInManager = signInManager; 29 | _signingConfigurations = signingConfigurations; 30 | _tokenConfigurations = tokenConfigurations; 31 | _cache = cache; 32 | } 33 | 34 | public bool ValidateCredentials(AccessCredentials credenciais) 35 | { 36 | bool credenciaisValidas = false; 37 | if (credenciais != null && !String.IsNullOrWhiteSpace(credenciais.UserID)) 38 | { 39 | if (credenciais.GrantType == "password") 40 | { 41 | // Verifica a existência do usuário nas tabelas do 42 | // ASP.NET Core Identity 43 | var userIdentity = _userManager 44 | .FindByNameAsync(credenciais.UserID).Result; 45 | if (userIdentity != null) 46 | { 47 | // Efetua o login com base no Id do usuário e sua senha 48 | var resultadoLogin = _signInManager 49 | .CheckPasswordSignInAsync(userIdentity, credenciais.Password, false) 50 | .Result; 51 | if (resultadoLogin.Succeeded) 52 | { 53 | // Verifica se o usuário em questão possui 54 | // a role de acesso 55 | credenciaisValidas = _userManager.IsInRoleAsync( 56 | userIdentity, _tokenConfigurations.AccessRole).Result; 57 | } 58 | } 59 | } 60 | else if (credenciais.GrantType == "refresh_token") 61 | { 62 | if (!String.IsNullOrWhiteSpace(credenciais.RefreshToken)) 63 | { 64 | RefreshTokenData refreshTokenBase = null; 65 | 66 | string strTokenArmazenado = 67 | _cache.GetString(credenciais.RefreshToken); 68 | if (!String.IsNullOrWhiteSpace(strTokenArmazenado)) 69 | { 70 | refreshTokenBase = JsonSerializer 71 | .Deserialize(strTokenArmazenado); 72 | } 73 | 74 | credenciaisValidas = (refreshTokenBase != null && 75 | credenciais.UserID == refreshTokenBase.UserID && 76 | credenciais.RefreshToken == refreshTokenBase.RefreshToken); 77 | 78 | // Elimina o token de refresh já que um novo será gerado 79 | if (credenciaisValidas) 80 | _cache.Remove(credenciais.RefreshToken); 81 | } 82 | } 83 | } 84 | 85 | return credenciaisValidas; 86 | } 87 | 88 | public Token GenerateToken(AccessCredentials credenciais) 89 | { 90 | ClaimsIdentity identity = new ClaimsIdentity( 91 | new GenericIdentity(credenciais.UserID, "Login"), 92 | new[] { 93 | new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString("N")), 94 | new Claim(JwtRegisteredClaimNames.UniqueName, credenciais.UserID) 95 | } 96 | ); 97 | 98 | DateTime dataCriacao = DateTime.Now; 99 | DateTime dataExpiracao = dataCriacao + 100 | TimeSpan.FromSeconds(_tokenConfigurations.Seconds); 101 | 102 | var handler = new JwtSecurityTokenHandler(); 103 | var securityToken = handler.CreateToken(new SecurityTokenDescriptor 104 | { 105 | Issuer = _tokenConfigurations.Issuer, 106 | Audience = _tokenConfigurations.Audience, 107 | SigningCredentials = _signingConfigurations.SigningCredentials, 108 | Subject = identity, 109 | NotBefore = dataCriacao, 110 | Expires = dataExpiracao 111 | }); 112 | var token = handler.WriteToken(securityToken); 113 | 114 | var resultado = new Token() 115 | { 116 | Authenticated = true, 117 | Created = dataCriacao.ToString("yyyy-MM-dd HH:mm:ss"), 118 | Expiration = dataExpiracao.ToString("yyyy-MM-dd HH:mm:ss"), 119 | AccessToken = token, 120 | RefreshToken = Guid.NewGuid().ToString().Replace("-", String.Empty), 121 | Message = "OK" 122 | }; 123 | 124 | // Armazena o refresh token em cache através do Redis 125 | var refreshTokenData = new RefreshTokenData(); 126 | refreshTokenData.RefreshToken = resultado.RefreshToken; 127 | refreshTokenData.UserID = credenciais.UserID; 128 | 129 | 130 | // Calcula o tempo máximo de validade do refresh token 131 | // (o mesmo será invalidado automaticamente pelo Redis) 132 | TimeSpan finalExpiration = 133 | TimeSpan.FromSeconds(_tokenConfigurations.FinalExpiration); 134 | 135 | DistributedCacheEntryOptions opcoesCache = 136 | new DistributedCacheEntryOptions(); 137 | opcoesCache.SetAbsoluteExpiration(finalExpiration); 138 | _cache.SetString(resultado.RefreshToken, 139 | JsonSerializer.Serialize(refreshTokenData), 140 | opcoesCache); 141 | 142 | return resultado; 143 | } 144 | } 145 | } -------------------------------------------------------------------------------- /APIContagem/Security/Classes.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Identity; 2 | 3 | namespace APIContagem.Security 4 | { 5 | public class ApplicationUser : IdentityUser 6 | { 7 | } 8 | 9 | public class AccessCredentials 10 | { 11 | public string UserID { get; set; } 12 | public string Password { get; set; } 13 | public string RefreshToken { get; set; } 14 | public string GrantType { get; set; } 15 | } 16 | 17 | public class TokenConfigurations 18 | { 19 | public string AccessRole { get; set; } 20 | public string SecretJWTKey { get; set; } 21 | public string Audience { get; set; } 22 | public string Issuer { get; set; } 23 | public int Seconds { get; set; } 24 | public int FinalExpiration { get; set; } 25 | } 26 | 27 | public class Token 28 | { 29 | public bool Authenticated { get; set; } 30 | public string Created { get; set; } 31 | public string Expiration { get; set; } 32 | public string AccessToken { get; set; } 33 | public string RefreshToken { get; set; } 34 | public string Message { get; set; } 35 | } 36 | 37 | public class RefreshTokenData 38 | { 39 | public string RefreshToken { get; set; } 40 | public string UserID { get; set; } 41 | } 42 | } -------------------------------------------------------------------------------- /APIContagem/Security/Data/APISecurityDbContext.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Identity.EntityFrameworkCore; 2 | using Microsoft.EntityFrameworkCore; 3 | 4 | namespace APIContagem.Security.Data 5 | { 6 | public class APISecurityDbContext : IdentityDbContext 7 | { 8 | public APISecurityDbContext(DbContextOptions options) 9 | : base(options) 10 | { 11 | } 12 | 13 | protected override void OnModelCreating(ModelBuilder builder) 14 | { 15 | base.OnModelCreating(builder); 16 | } 17 | } 18 | } -------------------------------------------------------------------------------- /APIContagem/Security/Data/IdentityInitializer.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using Microsoft.AspNetCore.Identity; 3 | 4 | namespace APIContagem.Security.Data 5 | { 6 | public class IdentityInitializer 7 | { 8 | private readonly TokenConfigurations _tokenConfigurations; 9 | private readonly APISecurityDbContext _context; 10 | private readonly UserManager _userManager; 11 | private readonly RoleManager _roleManager; 12 | 13 | public IdentityInitializer( 14 | TokenConfigurations tokenConfigurations, 15 | APISecurityDbContext context, 16 | UserManager userManager, 17 | RoleManager roleManager) 18 | { 19 | _tokenConfigurations = tokenConfigurations; 20 | _context = context; 21 | _userManager = userManager; 22 | _roleManager = roleManager; 23 | } 24 | 25 | public void Initialize() 26 | { 27 | if (_context.Database.EnsureCreated()) 28 | { 29 | if (!_roleManager.RoleExistsAsync(_tokenConfigurations.AccessRole).Result) 30 | { 31 | var resultado = _roleManager.CreateAsync( 32 | new IdentityRole(_tokenConfigurations.AccessRole)).Result; 33 | if (!resultado.Succeeded) 34 | { 35 | throw new Exception( 36 | $"Erro durante a criação da role {_tokenConfigurations.AccessRole}."); 37 | } 38 | } 39 | 40 | CreateUser( 41 | new ApplicationUser() 42 | { 43 | UserName = "admin_apicontagem", 44 | Email = "admin-apicontagem@teste.com.br", 45 | EmailConfirmed = true 46 | }, "AdminAPIContagem01!", _tokenConfigurations.AccessRole); 47 | 48 | CreateUser( 49 | new ApplicationUser() 50 | { 51 | UserName = "usrinvalido_apicontagem", 52 | Email = "usrinvalido-apicontagem@teste.com.br", 53 | EmailConfirmed = true 54 | }, "UsrInvAPIContagem01!"); 55 | } 56 | } 57 | 58 | private void CreateUser( 59 | ApplicationUser user, 60 | string password, 61 | string initialRole = null) 62 | { 63 | if (_userManager.FindByNameAsync(user.UserName).Result == null) 64 | { 65 | var resultado = _userManager 66 | .CreateAsync(user, password).Result; 67 | 68 | if (resultado.Succeeded && 69 | !String.IsNullOrWhiteSpace(initialRole)) 70 | { 71 | _userManager.AddToRoleAsync(user, initialRole).Wait(); 72 | } 73 | } 74 | } 75 | } 76 | } -------------------------------------------------------------------------------- /APIContagem/Security/JwtSecurityExtension.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using Microsoft.AspNetCore.Identity; 3 | using Microsoft.AspNetCore.Authentication.JwtBearer; 4 | using Microsoft.AspNetCore.Authorization; 5 | using Microsoft.Extensions.DependencyInjection; 6 | using APIContagem.Security.Data; 7 | 8 | namespace APIContagem.Security 9 | { 10 | public static class JwtSecurityExtension 11 | { 12 | public static IServiceCollection AddJwtSecurity( 13 | this IServiceCollection services, 14 | TokenConfigurations tokenConfigurations) 15 | { 16 | services.AddSingleton(tokenConfigurations); 17 | 18 | // Ativando a utilização do ASP.NET Identity, a fim de 19 | // permitir a recuperação de seus objetos via injeção de 20 | // dependências 21 | services.AddIdentity() 22 | .AddEntityFrameworkStores() 23 | .AddDefaultTokenProviders(); 24 | 25 | // Configurando a dependência para a classe de validação 26 | // de credenciais e geração de tokens 27 | services.AddScoped(); 28 | 29 | var signingConfigurations = 30 | new SigningConfigurations(tokenConfigurations); 31 | services.AddSingleton(signingConfigurations); 32 | 33 | // Configura a dependência da classe que cria usuários 34 | // para testes da API 35 | services.AddTransient(); 36 | 37 | services.AddAuthentication(authOptions => 38 | { 39 | authOptions.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; 40 | authOptions.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; 41 | }).AddJwtBearer(bearerOptions => 42 | { 43 | var paramsValidation = bearerOptions.TokenValidationParameters; 44 | paramsValidation.IssuerSigningKey = signingConfigurations.Key; 45 | paramsValidation.ValidAudience = tokenConfigurations.Audience; 46 | paramsValidation.ValidIssuer = tokenConfigurations.Issuer; 47 | 48 | // Valida a assinatura de um token recebido 49 | paramsValidation.ValidateIssuerSigningKey = true; 50 | 51 | // Verifica se um token recebido ainda é válido 52 | paramsValidation.ValidateLifetime = true; 53 | 54 | // Tempo de tolerância para a expiração de um token (utilizado 55 | // caso haja problemas de sincronismo de horário entre diferentes 56 | // computadores envolvidos no processo de comunicação) 57 | paramsValidation.ClockSkew = TimeSpan.Zero; 58 | }); 59 | 60 | // Ativa o uso do token como forma de autorizar o acesso 61 | // a recursos deste projeto 62 | services.AddAuthorization(auth => 63 | { 64 | auth.AddPolicy("Bearer", new AuthorizationPolicyBuilder() 65 | .AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme‌​) 66 | .RequireAuthenticatedUser().Build()); 67 | }); 68 | 69 | return services; 70 | } 71 | } 72 | } -------------------------------------------------------------------------------- /APIContagem/Security/SigningConfigurations.cs: -------------------------------------------------------------------------------- 1 | using System.Text; 2 | using Microsoft.IdentityModel.Tokens; 3 | 4 | namespace APIContagem.Security 5 | { 6 | public class SigningConfigurations 7 | { 8 | public SecurityKey Key { get; } 9 | public SigningCredentials SigningCredentials { get; } 10 | 11 | public SigningConfigurations(TokenConfigurations tokenConfigurations) 12 | { 13 | Key = new SymmetricSecurityKey( 14 | Encoding.UTF8.GetBytes(tokenConfigurations.SecretJWTKey)); 15 | 16 | SigningCredentials = new ( 17 | Key, SecurityAlgorithms.HmacSha256Signature); 18 | } 19 | } 20 | } -------------------------------------------------------------------------------- /APIContagem/Startup.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Builder; 2 | using Microsoft.AspNetCore.Hosting; 3 | using Microsoft.EntityFrameworkCore; 4 | using Microsoft.Extensions.Configuration; 5 | using Microsoft.Extensions.DependencyInjection; 6 | using Microsoft.Extensions.Hosting; 7 | using Microsoft.Extensions.Options; 8 | using Microsoft.OpenApi.Models; 9 | using APIContagem.Security; 10 | using APIContagem.Security.Data; 11 | 12 | namespace APIContagem 13 | { 14 | public class Startup 15 | { 16 | public Startup(IConfiguration configuration) 17 | { 18 | Configuration = configuration; 19 | } 20 | 21 | public IConfiguration Configuration { get; } 22 | 23 | public void ConfigureServices(IServiceCollection services) 24 | { 25 | // Ativando o uso de cache via Redis 26 | services.AddDistributedRedisCache(options => 27 | { 28 | options.Configuration = 29 | Configuration.GetConnectionString("ConexaoRedis"); 30 | options.InstanceName = "APIContagem"; 31 | }); 32 | 33 | // Configurando o uso da classe de contexto para 34 | // acesso às tabelas do ASP.NET Identity Core 35 | services.AddDbContext(options => 36 | options.UseInMemoryDatabase("InMemoryDatabase")); 37 | 38 | var tokenConfigurations = new TokenConfigurations(); 39 | new ConfigureFromConfigurationOptions( 40 | Configuration.GetSection("TokenConfigurations")) 41 | .Configure(tokenConfigurations); 42 | 43 | // Aciona a extensão que irá configurar o uso de 44 | // autenticação e autorização via tokens 45 | services.AddJwtSecurity(tokenConfigurations); 46 | 47 | services.AddControllers(); 48 | services.AddSwaggerGen(c => 49 | { 50 | c.SwaggerDoc("v1", new OpenApiInfo { Title = "APIContagem", Version = "v1" }); 51 | }); 52 | } 53 | 54 | public void Configure(IApplicationBuilder app, IWebHostEnvironment env, 55 | IdentityInitializer identityInitializer) 56 | { 57 | if (env.IsDevelopment()) 58 | app.UseDeveloperExceptionPage(); 59 | app.UseSwagger(); 60 | app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "APIContagem v1")); 61 | 62 | app.UseCors(builder => builder.AllowAnyMethod() 63 | .AllowAnyOrigin() 64 | .AllowAnyHeader()); 65 | 66 | app.UseHttpsRedirection(); 67 | 68 | app.UseRouting(); 69 | 70 | // Criação de estruturas, usuários e permissões 71 | // na base do ASP.NET Identity Core (caso ainda não 72 | // existam) 73 | identityInitializer.Initialize(); 74 | 75 | // Habilita o uso de autorização para acesso a métodos 76 | // protegidos de API 77 | app.UseAuthorization(); 78 | 79 | app.UseEndpoints(endpoints => 80 | { 81 | endpoints.MapControllers(); 82 | }); 83 | } 84 | } 85 | } -------------------------------------------------------------------------------- /APIContagem/appsettings.Development.json: -------------------------------------------------------------------------------- 1 | { 2 | "Logging": { 3 | "LogLevel": { 4 | "Default": "Information", 5 | "Microsoft": "Warning", 6 | "Microsoft.Hosting.Lifetime": "Information" 7 | } 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /APIContagem/appsettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "MensagemVariavel": "Teste utilizando o arquivo appsettings.json", 3 | "ConnectionStrings": { 4 | "ConexaoRedis": "" 5 | }, 6 | "TokenConfigurations": { 7 | "AccessRole": "Acesso-APIContagem", 8 | "SecretJWTKey": "VGVzdGVzIGNvbSBBU1AuTkVUIDUgZSBKV1Q=", 9 | "Audience": "Clients-APIContagem", 10 | "Issuer": "APIContagem", 11 | "Seconds": 60, 12 | "FinalExpiration": 120 13 | }, 14 | "Logging": { 15 | "LogLevel": { 16 | "Default": "Information", 17 | "Microsoft": "Warning", 18 | "Microsoft.Hosting.Lifetime": "Information" 19 | } 20 | }, 21 | "AllowedHosts": "*" 22 | } 23 | --------------------------------------------------------------------------------