Skip to content

Commit

Permalink
auth
Browse files Browse the repository at this point in the history
  • Loading branch information
cyrogabrielcc committed Apr 4, 2021
1 parent 17170b1 commit f73c332
Show file tree
Hide file tree
Showing 5 changed files with 55 additions and 13 deletions.
14 changes: 7 additions & 7 deletions Controllers/CategoryController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,13 +7,13 @@
using Microsoft.EntityFrameworkCore;

//https://localhost:5001

namespace DataDriven.Controllers
{
[Route("categories")]
public class CategoryController : ControllerBase
{
//====================================================GET====================================================
//=================================================GET=======================================================
[HttpGet]
[Route("")]
public async Task<ActionResult<List<Category>>> GetById([FromServices] DataContext context)
Expand All @@ -23,7 +23,7 @@ public async Task<ActionResult<List<Category>>> GetById([FromServices] DataConte
}


//===============================================GETBYID====================================================
//===============================================GETBYID=====================================================
[HttpGet]
[Route("{id:int}")]
public async Task<ActionResult<Category>> GetById([FromServices] DataContext context, int id)
Expand All @@ -34,7 +34,7 @@ public async Task<ActionResult<Category>> GetById([FromServices] DataContext con



//===================================================POST==================================================
//================================================POST=======================================================
[HttpPost]
[Route("")]
public async Task<ActionResult<List<Category>>> Post([FromBody] Category model, [FromServices] DataContext context)
Expand All @@ -55,14 +55,14 @@ public async Task<ActionResult<List<Category>>> Post([FromBody] Category model,



//============================================PUT====================================================
//================================================PUT========================================================
[HttpPut]
[Route("{id:int}")]
public async Task<ActionResult<List<Category>>> Put(int id, [FromBody]Category model, [FromServices] DataContext context)
{
if(!ModelState.IsValid) return BadRequest(ModelState);
//se o id informado é o msm do modelo
if(model.Id == id) return NotFound(new {message = "Categoria não encontrada"});;
if(id != model.Id) return NotFound(new {message = "Categoria não encontrada"});;

try
{
Expand All @@ -79,7 +79,7 @@ public async Task<ActionResult<List<Category>>> Put(int id, [FromBody]Category m
}
}

//==============================DELETE==================================
//==============================================DELETE=======================================================
[HttpDelete]
[Route("{id:int}")]
public async Task<ActionResult<List<Category>>> Delete(int id,[FromServices] DataContext context)
Expand Down
12 changes: 8 additions & 4 deletions Controllers/ProductController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -60,12 +60,16 @@ public async Task<ActionResult<List<Product>>> Post([FromBody] Product model, [F
return Ok(model);
}
catch
{
{
return BadRequest(new {message = "Não foi possível criar a categoria"});
}
}



//============================================================PUT=====================================================================//
//============================================================DELETE=====================================================================//





}
}
2 changes: 2 additions & 0 deletions DataDriven.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.Authentication" Version="2.2.0" />
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="5.0.4" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="5.0.4">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
<PrivateAssets>all</PrivateAssets>
Expand Down
7 changes: 7 additions & 0 deletions Settings.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
namespace DataDriven
{
public class Settings
{
public static string Secret = "escreva seu hash aqui";
}
}
33 changes: 31 additions & 2 deletions Startup.cs
Original file line number Diff line number Diff line change
@@ -1,10 +1,13 @@
using System.Text;
using DataDriven.Data;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.IdentityModel.Tokens;
using Microsoft.OpenApi.Models;

namespace DataDriven
Expand All @@ -21,13 +24,38 @@ public Startup(IConfiguration configuration)
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{

var key = Encoding.ASCII.GetBytes(Settings.Secret);

services.AddAuthentication
(x =>
{
x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
x.DefaultChallengeScheme= JwtBearerDefaults.AuthenticationScheme;
}

)

.AddJwtBearer(x =>
{

//validações básicas
x.RequireHttpsMetadata = false;
x.SaveToken = true;
x.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(key),
ValidateIssuer = false,
ValidateAudience = false
};
});
services.AddControllers();


services.AddDbContext<DataContext>(
opt => opt.UseSqlServer(Configuration.GetConnectionString("connectionString")));



services.AddScoped<DataContext, DataContext>();

services.AddSwaggerGen(c =>
Expand All @@ -50,6 +78,7 @@ public void Configure(IApplicationBuilder app, IWebHostEnvironment env)

app.UseRouting();

app.UseAuthentication();
app.UseAuthorization();

app.UseEndpoints(endpoints =>
Expand Down

0 comments on commit f73c332

Please sign in to comment.