└── APIProdutos ├── .vscode ├── launch.json └── tasks.json ├── APIProdutos.csproj ├── Business └── ProdutoService.cs ├── Controllers ├── LoginController.cs └── ProdutosController.cs ├── Data ├── ApplicationDbContext.cs └── CatalogoDbContext.cs ├── Models ├── ApplicationUser.cs ├── IdentityInitializer.cs ├── Produto.cs └── Resultado.cs ├── Program.cs ├── Properties └── launchSettings.json ├── Security ├── AccessManager.cs ├── Classes.cs ├── JwtSecurityExtension.cs └── SigningConfigurations.cs ├── Startup.cs ├── appsettings.Development.json └── appsettings.json /APIProdutos/.vscode/launch.json: -------------------------------------------------------------------------------- 1 | { 2 | // Use IntelliSense to learn about possible attributes. 3 | // Hover to view descriptions of existing attributes. 4 | // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 5 | "version": "0.2.0", 6 | "configurations": [ 7 | { 8 | "name": ".NET Core Launch (web)", 9 | "type": "coreclr", 10 | "request": "launch", 11 | "preLaunchTask": "build", 12 | "program": "${workspaceFolder}/bin/Debug/netcoreapp2.2/APIProdutos.dll", 13 | "args": [], 14 | "cwd": "${workspaceFolder}", 15 | "stopAtEntry": false, 16 | "internalConsoleOptions": "openOnSessionStart", 17 | "launchBrowser": { 18 | "enabled": true, 19 | "args": "${auto-detect-url}", 20 | "windows": { 21 | "command": "cmd.exe", 22 | "args": "/C start ${auto-detect-url}" 23 | }, 24 | "osx": { 25 | "command": "open" 26 | }, 27 | "linux": { 28 | "command": "xdg-open" 29 | } 30 | }, 31 | "env": { 32 | "ASPNETCORE_ENVIRONMENT": "Development" 33 | }, 34 | "sourceFileMap": { 35 | "/Views": "${workspaceFolder}/Views" 36 | } 37 | }, 38 | { 39 | "name": ".NET Core Attach", 40 | "type": "coreclr", 41 | "request": "attach", 42 | "processId": "${command:pickProcess}" 43 | } 44 | ] 45 | } -------------------------------------------------------------------------------- /APIProdutos/.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}/APIProdutos.csproj" 11 | ], 12 | "problemMatcher": "$msCompile" 13 | } 14 | ] 15 | } -------------------------------------------------------------------------------- /APIProdutos/APIProdutos.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | netcoreapp2.2 5 | InProcess 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | -------------------------------------------------------------------------------- /APIProdutos/Business/ProdutoService.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using APIProdutos.Data; 5 | using APIProdutos.Models; 6 | 7 | namespace APIProdutos.Business 8 | { 9 | public class ProdutoService 10 | { 11 | private CatalogoDbContext _context; 12 | 13 | public ProdutoService(CatalogoDbContext context) 14 | { 15 | _context = context; 16 | } 17 | 18 | public Produto Obter(string codigoBarras) 19 | { 20 | codigoBarras = codigoBarras?.Trim().ToUpper(); 21 | if (!String.IsNullOrWhiteSpace(codigoBarras)) 22 | { 23 | return _context.Produtos.Where( 24 | p => p.CodigoBarras == codigoBarras).FirstOrDefault(); 25 | } 26 | else 27 | return null; 28 | } 29 | 30 | public IEnumerable ListarTodos() 31 | { 32 | return _context.Produtos 33 | .OrderBy(p => p.Nome).ToList(); 34 | } 35 | 36 | public Resultado Incluir(Produto dadosProduto) 37 | { 38 | Resultado resultado = DadosValidos(dadosProduto); 39 | resultado.Acao = "Inclusão de Produto"; 40 | 41 | if (resultado.Inconsistencias.Count == 0 && 42 | _context.Produtos.Where( 43 | p => p.CodigoBarras == dadosProduto.CodigoBarras).Count() > 0) 44 | { 45 | resultado.Inconsistencias.Add( 46 | "Código de Barras já cadastrado"); 47 | } 48 | 49 | if (resultado.Inconsistencias.Count == 0) 50 | { 51 | _context.Produtos.Add(dadosProduto); 52 | _context.SaveChanges(); 53 | } 54 | 55 | return resultado; 56 | } 57 | 58 | public Resultado Atualizar(Produto dadosProduto) 59 | { 60 | Resultado resultado = DadosValidos(dadosProduto); 61 | resultado.Acao = "Atualização de Produto"; 62 | 63 | if (resultado.Inconsistencias.Count == 0) 64 | { 65 | Produto produto = _context.Produtos.Where( 66 | p => p.CodigoBarras == dadosProduto.CodigoBarras).FirstOrDefault(); 67 | 68 | if (produto == null) 69 | { 70 | resultado.Inconsistencias.Add( 71 | "Produto não encontrado"); 72 | } 73 | else 74 | { 75 | produto.Nome = dadosProduto.Nome; 76 | produto.Preco = dadosProduto.Preco; 77 | _context.SaveChanges(); 78 | } 79 | } 80 | 81 | return resultado; 82 | } 83 | 84 | public Resultado Excluir(string codigoBarras) 85 | { 86 | Resultado resultado = new Resultado(); 87 | resultado.Acao = "Exclusão de Produto"; 88 | 89 | Produto produto = Obter(codigoBarras); 90 | if (produto == null) 91 | { 92 | resultado.Inconsistencias.Add( 93 | "Produto não encontrado"); 94 | } 95 | else 96 | { 97 | _context.Produtos.Remove(produto); 98 | _context.SaveChanges(); 99 | } 100 | 101 | return resultado; 102 | } 103 | 104 | private Resultado DadosValidos(Produto produto) 105 | { 106 | var resultado = new Resultado(); 107 | if (produto == null) 108 | { 109 | resultado.Inconsistencias.Add( 110 | "Preencha os Dados do Produto"); 111 | } 112 | else 113 | { 114 | if (String.IsNullOrWhiteSpace(produto.CodigoBarras)) 115 | { 116 | resultado.Inconsistencias.Add( 117 | "Preencha o Código de Barras"); 118 | } 119 | if (String.IsNullOrWhiteSpace(produto.Nome)) 120 | { 121 | resultado.Inconsistencias.Add( 122 | "Preencha o Nome do Produto"); 123 | } 124 | if (produto.Preco <= 0) 125 | { 126 | resultado.Inconsistencias.Add( 127 | "O Preço do Produto deve ser maior do que zero"); 128 | } 129 | } 130 | 131 | return resultado; 132 | } 133 | } 134 | } -------------------------------------------------------------------------------- /APIProdutos/Controllers/LoginController.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Mvc; 2 | using Microsoft.AspNetCore.Authorization; 3 | using APIProdutos.Security; 4 | 5 | namespace APIProdutos.Controllers 6 | { 7 | [Route("api/[controller]")] 8 | public class LoginController : Controller 9 | { 10 | [AllowAnonymous] 11 | [HttpPost] 12 | public object Post( 13 | [FromBody]User usuario, 14 | [FromServices]AccessManager accessManager) 15 | { 16 | if (accessManager.ValidateCredentials(usuario)) 17 | { 18 | return accessManager.GenerateToken(usuario); 19 | } 20 | else 21 | { 22 | return new 23 | { 24 | Authenticated = false, 25 | Message = "Falha ao autenticar" 26 | }; 27 | } 28 | } 29 | } 30 | } -------------------------------------------------------------------------------- /APIProdutos/Controllers/ProdutosController.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using Microsoft.AspNetCore.Mvc; 3 | using Microsoft.AspNetCore.Authorization; 4 | using APIProdutos.Business; 5 | using APIProdutos.Models; 6 | 7 | namespace APIProdutos.Controllers 8 | { 9 | [Route("api/[controller]")] 10 | [ApiController] 11 | [Authorize("Bearer")] 12 | public class ProdutosController : ControllerBase 13 | { 14 | private ProdutoService _service; 15 | 16 | public ProdutosController(ProdutoService service) 17 | { 18 | _service = service; 19 | } 20 | 21 | [HttpGet] 22 | public IEnumerable Get() 23 | { 24 | return _service.ListarTodos(); 25 | } 26 | 27 | [HttpGet("{codigoBarras}")] 28 | public ActionResult Get(string codigoBarras) 29 | { 30 | var produto = _service.Obter(codigoBarras); 31 | if (produto != null) 32 | return produto; 33 | else 34 | return NotFound(); 35 | } 36 | 37 | [HttpPost] 38 | public Resultado Post([FromBody]Produto produto) 39 | { 40 | return _service.Incluir(produto); 41 | } 42 | 43 | [HttpPut] 44 | public Resultado Put([FromBody]Produto produto) 45 | { 46 | return _service.Atualizar(produto); 47 | } 48 | 49 | [HttpDelete("{codigoBarras}")] 50 | public Resultado Delete(string codigoBarras) 51 | { 52 | return _service.Excluir(codigoBarras); 53 | } 54 | } 55 | } -------------------------------------------------------------------------------- /APIProdutos/Data/ApplicationDbContext.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Identity.EntityFrameworkCore; 2 | using Microsoft.EntityFrameworkCore; 3 | using APIProdutos.Models; 4 | 5 | namespace APIProdutos.Data 6 | { 7 | public class ApplicationDbContext : IdentityDbContext 8 | { 9 | public ApplicationDbContext(DbContextOptions options) 10 | : base(options) 11 | { 12 | } 13 | 14 | protected override void OnModelCreating(ModelBuilder builder) 15 | { 16 | base.OnModelCreating(builder); 17 | } 18 | } 19 | } -------------------------------------------------------------------------------- /APIProdutos/Data/CatalogoDbContext.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.EntityFrameworkCore; 2 | using APIProdutos.Models; 3 | 4 | namespace APIProdutos.Data 5 | { 6 | public class CatalogoDbContext : DbContext 7 | { 8 | public CatalogoDbContext( 9 | DbContextOptions options) : base(options) 10 | { } 11 | 12 | public DbSet Produtos { get; set; } 13 | 14 | protected override void OnModelCreating(ModelBuilder modelBuilder) 15 | { 16 | modelBuilder.Entity() 17 | .HasKey(p => p.CodigoBarras); 18 | } 19 | } 20 | } -------------------------------------------------------------------------------- /APIProdutos/Models/ApplicationUser.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Identity; 2 | 3 | namespace APIProdutos.Models 4 | { 5 | public class ApplicationUser : IdentityUser 6 | { 7 | } 8 | } -------------------------------------------------------------------------------- /APIProdutos/Models/IdentityInitializer.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using Microsoft.AspNetCore.Identity; 3 | using APIProdutos.Data; 4 | using APIProdutos.Models; 5 | 6 | namespace APIProdutos.Security 7 | { 8 | public class IdentityInitializer 9 | { 10 | private readonly ApplicationDbContext _context; 11 | private readonly UserManager _userManager; 12 | private readonly RoleManager _roleManager; 13 | 14 | public IdentityInitializer( 15 | ApplicationDbContext context, 16 | UserManager userManager, 17 | RoleManager roleManager) 18 | { 19 | _context = context; 20 | _userManager = userManager; 21 | _roleManager = roleManager; 22 | } 23 | 24 | public void Initialize() 25 | { 26 | if (_context.Database.EnsureCreated()) 27 | { 28 | if (!_roleManager.RoleExistsAsync(Roles.ROLE_API_PRODUTOS).Result) 29 | { 30 | var resultado = _roleManager.CreateAsync( 31 | new IdentityRole(Roles.ROLE_API_PRODUTOS)).Result; 32 | if (!resultado.Succeeded) 33 | { 34 | throw new Exception( 35 | $"Erro durante a criação da role {Roles.ROLE_API_PRODUTOS}."); 36 | } 37 | } 38 | 39 | CreateUser( 40 | new ApplicationUser() 41 | { 42 | UserName = "admin_apiprodutos", 43 | Email = "admin-apiprodutos@teste.com.br", 44 | EmailConfirmed = true 45 | }, "AdminAPIProdutos01!", Roles.ROLE_API_PRODUTOS); 46 | 47 | CreateUser( 48 | new ApplicationUser() 49 | { 50 | UserName = "usrinvalido_apiprodutos", 51 | Email = "usrinvalido-apiprodutos@teste.com.br", 52 | EmailConfirmed = true 53 | }, "UsrInvAPIProdutos01!"); 54 | } 55 | } 56 | private void CreateUser( 57 | ApplicationUser user, 58 | string password, 59 | string initialRole = null) 60 | { 61 | if (_userManager.FindByNameAsync(user.UserName).Result == null) 62 | { 63 | var resultado = _userManager 64 | .CreateAsync(user, password).Result; 65 | 66 | if (resultado.Succeeded && 67 | !String.IsNullOrWhiteSpace(initialRole)) 68 | { 69 | _userManager.AddToRoleAsync(user, initialRole).Wait(); 70 | } 71 | } 72 | } 73 | } 74 | } -------------------------------------------------------------------------------- /APIProdutos/Models/Produto.cs: -------------------------------------------------------------------------------- 1 | namespace APIProdutos.Models 2 | { 3 | public class Produto 4 | { 5 | private string _codigoBarras; 6 | public string CodigoBarras 7 | { 8 | get => _codigoBarras; 9 | set => _codigoBarras = value?.Trim().ToUpper(); 10 | } 11 | 12 | private string _nome; 13 | public string Nome 14 | { 15 | get => _nome; 16 | set => _nome = value?.Trim(); 17 | } 18 | 19 | public double Preco { get; set; } 20 | } 21 | } -------------------------------------------------------------------------------- /APIProdutos/Models/Resultado.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | 3 | namespace APIProdutos.Models 4 | { 5 | public class Resultado 6 | { 7 | public string Acao { get; set; } 8 | 9 | public bool Sucesso 10 | { 11 | get { return Inconsistencias == null || Inconsistencias.Count == 0; } 12 | } 13 | 14 | public List Inconsistencias { get; } = new List(); 15 | } 16 | } -------------------------------------------------------------------------------- /APIProdutos/Program.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.IO; 4 | using System.Linq; 5 | using System.Threading.Tasks; 6 | using Microsoft.AspNetCore; 7 | using Microsoft.AspNetCore.Hosting; 8 | using Microsoft.Extensions.Configuration; 9 | using Microsoft.Extensions.Logging; 10 | 11 | namespace APIProdutos 12 | { 13 | public class Program 14 | { 15 | public static void Main(string[] args) 16 | { 17 | CreateWebHostBuilder(args).Build().Run(); 18 | } 19 | 20 | public static IWebHostBuilder CreateWebHostBuilder(string[] args) => 21 | WebHost.CreateDefaultBuilder(args) 22 | .UseStartup(); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /APIProdutos/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:62696", 8 | "sslPort": 44380 9 | } 10 | }, 11 | "profiles": { 12 | "IIS Express": { 13 | "commandName": "IISExpress", 14 | "launchBrowser": true, 15 | "launchUrl": "api/values", 16 | "environmentVariables": { 17 | "ASPNETCORE_ENVIRONMENT": "Development" 18 | } 19 | }, 20 | "APIProdutos": { 21 | "commandName": "Project", 22 | "launchBrowser": true, 23 | "launchUrl": "api/values", 24 | "applicationUrl": "https://localhost:5001;http://localhost:5000", 25 | "environmentVariables": { 26 | "ASPNETCORE_ENVIRONMENT": "Development" 27 | } 28 | } 29 | } 30 | } -------------------------------------------------------------------------------- /APIProdutos/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 APIProdutos.Models; 8 | 9 | namespace APIProdutos.Security 10 | { 11 | public class AccessManager 12 | { 13 | private UserManager _userManager; 14 | private SignInManager _signInManager; 15 | private SigningConfigurations _signingConfigurations; 16 | private TokenConfigurations _tokenConfigurations; 17 | 18 | public AccessManager( 19 | UserManager userManager, 20 | SignInManager signInManager, 21 | SigningConfigurations signingConfigurations, 22 | TokenConfigurations tokenConfigurations) 23 | { 24 | _userManager = userManager; 25 | _signInManager = signInManager; 26 | _signingConfigurations = signingConfigurations; 27 | _tokenConfigurations = tokenConfigurations; 28 | } 29 | 30 | public bool ValidateCredentials(User user) 31 | { 32 | bool credenciaisValidas = false; 33 | if (user != null && !String.IsNullOrWhiteSpace(user.UserID)) 34 | { 35 | // Verifica a existência do usuário nas tabelas do 36 | // ASP.NET Core Identity 37 | var userIdentity = _userManager 38 | .FindByNameAsync(user.UserID).Result; 39 | if (userIdentity != null) 40 | { 41 | // Efetua o login com base no Id do usuário e sua senha 42 | var resultadoLogin = _signInManager 43 | .CheckPasswordSignInAsync(userIdentity, user.Password, false) 44 | .Result; 45 | if (resultadoLogin.Succeeded) 46 | { 47 | // Verifica se o usuário em questão possui 48 | // a role Acesso-APIProdutos 49 | credenciaisValidas = _userManager.IsInRoleAsync( 50 | userIdentity, Roles.ROLE_API_PRODUTOS).Result; 51 | } 52 | } 53 | } 54 | 55 | return credenciaisValidas; 56 | } 57 | 58 | public Token GenerateToken(User user) 59 | { 60 | ClaimsIdentity identity = new ClaimsIdentity( 61 | new GenericIdentity(user.UserID, "Login"), 62 | new[] { 63 | new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString("N")), 64 | new Claim(JwtRegisteredClaimNames.UniqueName, user.UserID) 65 | } 66 | ); 67 | 68 | DateTime dataCriacao = DateTime.Now; 69 | DateTime dataExpiracao = dataCriacao + 70 | TimeSpan.FromSeconds(_tokenConfigurations.Seconds); 71 | 72 | var handler = new JwtSecurityTokenHandler(); 73 | var securityToken = handler.CreateToken(new SecurityTokenDescriptor 74 | { 75 | Issuer = _tokenConfigurations.Issuer, 76 | Audience = _tokenConfigurations.Audience, 77 | SigningCredentials = _signingConfigurations.SigningCredentials, 78 | Subject = identity, 79 | NotBefore = dataCriacao, 80 | Expires = dataExpiracao 81 | }); 82 | var token = handler.WriteToken(securityToken); 83 | 84 | return new Token() 85 | { 86 | Authenticated = true, 87 | Created = dataCriacao.ToString("yyyy-MM-dd HH:mm:ss"), 88 | Expiration = dataExpiracao.ToString("yyyy-MM-dd HH:mm:ss"), 89 | AccessToken = token, 90 | Message = "OK" 91 | }; 92 | } 93 | } 94 | } -------------------------------------------------------------------------------- /APIProdutos/Security/Classes.cs: -------------------------------------------------------------------------------- 1 | namespace APIProdutos.Security 2 | { 3 | public class User 4 | { 5 | public string UserID { get; set; } 6 | public string Password { get; set; } 7 | } 8 | 9 | public static class Roles 10 | { 11 | public const string ROLE_API_PRODUTOS = "Acesso-APIProdutos"; 12 | } 13 | 14 | public class TokenConfigurations 15 | { 16 | public string Audience { get; set; } 17 | public string Issuer { get; set; } 18 | public int Seconds { get; set; } 19 | public string Teste{get;set;} 20 | } 21 | 22 | public class Token 23 | { 24 | public bool Authenticated { get; set; } 25 | public string Created { get; set; } 26 | public string Expiration { get; set; } 27 | public string AccessToken { get; set; } 28 | public string Message { get; set; } 29 | } 30 | } -------------------------------------------------------------------------------- /APIProdutos/Security/JwtSecurityExtension.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using Microsoft.AspNetCore.Authentication.JwtBearer; 3 | using Microsoft.AspNetCore.Authorization; 4 | using Microsoft.Extensions.DependencyInjection; 5 | using APIProdutos.Security; 6 | 7 | namespace APIProdutos.Security 8 | { 9 | public static class JwtSecurityExtension 10 | { 11 | public static IServiceCollection AddJwtSecurity( 12 | this IServiceCollection services, 13 | SigningConfigurations signingConfigurations, 14 | TokenConfigurations tokenConfigurations) 15 | { 16 | services.AddAuthentication(authOptions => 17 | { 18 | authOptions.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; 19 | authOptions.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; 20 | }).AddJwtBearer(bearerOptions => 21 | { 22 | var paramsValidation = bearerOptions.TokenValidationParameters; 23 | paramsValidation.IssuerSigningKey = signingConfigurations.Key; 24 | paramsValidation.ValidAudience = tokenConfigurations.Audience; 25 | paramsValidation.ValidIssuer = tokenConfigurations.Issuer; 26 | 27 | // Valida a assinatura de um token recebido 28 | paramsValidation.ValidateIssuerSigningKey = true; 29 | 30 | // Verifica se um token recebido ainda é válido 31 | paramsValidation.ValidateLifetime = true; 32 | 33 | // Tempo de tolerância para a expiração de um token (utilizado 34 | // caso haja problemas de sincronismo de horário entre diferentes 35 | // computadores envolvidos no processo de comunicação) 36 | paramsValidation.ClockSkew = TimeSpan.Zero; 37 | }); 38 | 39 | // Ativa o uso do token como forma de autorizar o acesso 40 | // a recursos deste projeto 41 | services.AddAuthorization(auth => 42 | { 43 | auth.AddPolicy("Bearer", new AuthorizationPolicyBuilder() 44 | .AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme‌​) 45 | .RequireAuthenticatedUser().Build()); 46 | }); 47 | 48 | return services; 49 | } 50 | } 51 | } -------------------------------------------------------------------------------- /APIProdutos/Security/SigningConfigurations.cs: -------------------------------------------------------------------------------- 1 | using System.Security.Cryptography; 2 | using Microsoft.IdentityModel.Tokens; 3 | 4 | namespace APIProdutos.Security 5 | { 6 | public class SigningConfigurations 7 | { 8 | public SecurityKey Key { get; } 9 | public SigningCredentials SigningCredentials { get; } 10 | 11 | public SigningConfigurations() 12 | { 13 | using (var provider = new RSACryptoServiceProvider(2048)) 14 | { 15 | Key = new RsaSecurityKey(provider.ExportParameters(true)); 16 | } 17 | 18 | SigningCredentials = new SigningCredentials( 19 | Key, SecurityAlgorithms.RsaSha256Signature); 20 | } 21 | } 22 | } -------------------------------------------------------------------------------- /APIProdutos/Startup.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Threading.Tasks; 5 | using Microsoft.AspNetCore.Builder; 6 | using Microsoft.AspNetCore.Hosting; 7 | using Microsoft.AspNetCore.HttpsPolicy; 8 | using Microsoft.AspNetCore.Mvc; 9 | using Microsoft.AspNetCore.Identity; 10 | using Microsoft.Extensions.Configuration; 11 | using Microsoft.Extensions.DependencyInjection; 12 | using Microsoft.Extensions.Logging; 13 | using Microsoft.Extensions.Options; 14 | using Microsoft.EntityFrameworkCore; 15 | using APIProdutos.Data; 16 | using APIProdutos.Models; 17 | using APIProdutos.Security; 18 | using APIProdutos.Business; 19 | 20 | namespace APIProdutos 21 | { 22 | public class Startup 23 | { 24 | public Startup(IConfiguration configuration) 25 | { 26 | Configuration = configuration; 27 | } 28 | 29 | public IConfiguration Configuration { get; } 30 | 31 | public void ConfigureServices(IServiceCollection services) 32 | { 33 | // Configurando o acesso a dados de produtos 34 | services.AddDbContext(options => 35 | options.UseInMemoryDatabase("InMemoryDatabase")); 36 | services.AddScoped(); 37 | 38 | // Configurando o uso da classe de contexto para 39 | // acesso às tabelas do ASP.NET Identity Core 40 | services.AddDbContext(options => 41 | options.UseInMemoryDatabase("InMemoryDatabase")); 42 | 43 | // Ativando a utilização do ASP.NET Identity, a fim de 44 | // permitir a recuperação de seus objetos via injeção de 45 | // dependências 46 | services.AddIdentity() 47 | .AddEntityFrameworkStores() 48 | .AddDefaultTokenProviders(); 49 | 50 | // Configurando a dependência para a classe de validação 51 | // de credenciais e geração de tokens 52 | services.AddScoped(); 53 | 54 | var signingConfigurations = new SigningConfigurations(); 55 | services.AddSingleton(signingConfigurations); 56 | 57 | var tokenConfigurations = new TokenConfigurations(); 58 | new ConfigureFromConfigurationOptions( 59 | Configuration.GetSection("TokenConfigurations")) 60 | .Configure(tokenConfigurations); 61 | services.AddSingleton(tokenConfigurations); 62 | 63 | // Aciona a extensão que irá configurar o uso de 64 | // autenticação e autorização via tokens 65 | services.AddJwtSecurity( 66 | signingConfigurations, tokenConfigurations); 67 | 68 | services.AddCors(); 69 | services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2); 70 | } 71 | 72 | public void Configure(IApplicationBuilder app, IHostingEnvironment env, 73 | ApplicationDbContext context, 74 | UserManager userManager, 75 | RoleManager roleManager) 76 | { 77 | if (env.IsDevelopment()) 78 | { 79 | app.UseDeveloperExceptionPage(); 80 | } 81 | else 82 | { 83 | app.UseHsts(); 84 | } 85 | 86 | // Criação de estruturas, usuários e permissões 87 | // na base do ASP.NET Identity Core (caso ainda não 88 | // existam) 89 | new IdentityInitializer(context, userManager, roleManager) 90 | .Initialize(); 91 | 92 | app.UseHttpsRedirection(); 93 | app.UseMvc(); 94 | } 95 | } 96 | } -------------------------------------------------------------------------------- /APIProdutos/appsettings.Development.json: -------------------------------------------------------------------------------- 1 | { 2 | "Logging": { 3 | "LogLevel": { 4 | "Default": "Debug", 5 | "System": "Information", 6 | "Microsoft": "Information" 7 | } 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /APIProdutos/appsettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "TokenConfigurations": { 3 | "Audience": "ExemploAudience", 4 | "Issuer": "ExemploIssuer", 5 | "Seconds": 1200 6 | }, 7 | "Logging": { 8 | "LogLevel": { 9 | "Default": "Warning" 10 | } 11 | }, 12 | "AllowedHosts": "*" 13 | } 14 | --------------------------------------------------------------------------------