-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgram.cs
More file actions
192 lines (163 loc) · 5.84 KB
/
Program.cs
File metadata and controls
192 lines (163 loc) · 5.84 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
using Microsoft.EntityFrameworkCore;
using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
using ProductManagementAPI.Data;
using ProductManagementAPI.Services;
using ProductManagementAPI.DTOs;
using ProductManagementAPI.Models;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.OpenApi.Models;
using Microsoft.AspNetCore.Mvc;
var builder = WebApplication.CreateBuilder(args);
// --- Banco de Dados ---
builder.Services.AddDbContext<ProductDbContext>(options =>
options.UseSqlite("Data Source=products.db"));
// --- Serviço ---
builder.Services.AddScoped<ProductService>();
// --- JWT Authentication ---
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
var jwtSettings = builder.Configuration.GetSection("Jwt");
var key = Encoding.UTF8.GetBytes(jwtSettings["Key"] ?? "");
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidateAudience = true,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
ValidIssuer = jwtSettings["Issuer"],
ValidAudience = jwtSettings["Audience"],
IssuerSigningKey = new SymmetricSecurityKey(key)
};
});
builder.Services.AddAuthorization();
// --- Swagger ---
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen(options =>
{
options.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
{
Name = "Authorization",
Type = SecuritySchemeType.Http,
Scheme = "Bearer",
BearerFormat = "JWT",
In = ParameterLocation.Header,
Description = "Insira o token JWT desta forma: Bearer {seu token}"
});
options.AddSecurityRequirement(new OpenApiSecurityRequirement
{
{
new OpenApiSecurityScheme
{
Reference = new OpenApiReference
{
Type = ReferenceType.SecurityScheme,
Id = "Bearer"
}
},
new string[] {}
}
});
});
var app = builder.Build();
// --- Pipeline ---
app.UseSwagger();
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/v1/swagger.json", "Product Management API v1");
c.RoutePrefix = string.Empty; // Swagger na raiz: http://localhost:5000
});
app.UseHttpsRedirection();
app.UseAuthentication();
app.UseAuthorization();
// --- Endpoints ---
app.MapGet("/", () => Results.Ok(new
{
message = "Bem-vindo à Product Management API!",
endpoints = new[]
{
"GET /health",
"GET /products",
"POST /products",
"PUT /products/{id}",
"DELETE /products/{id}",
"POST /login"
},
swagger = "http://localhost:5000"
}));
app.MapGet("/health", () => "Healthy").AllowAnonymous();
// --- JWT Login Endpoint ---
app.MapPost("/login", (HttpContext context, [FromBody] User login) =>
{
var configuration = context.RequestServices.GetRequiredService<IConfiguration>();
if (login.Username == "admin" && login.Password == "senha123")
{
var key = Encoding.UTF8.GetBytes(configuration["Jwt:Key"] ?? "");
var issuer = configuration["Jwt:Issuer"];
var audience = configuration["Jwt:Audience"];
var tokenDescriptor = new SecurityTokenDescriptor
{
Subject = new ClaimsIdentity(new[]
{
new Claim(ClaimTypes.Name, login.Username),
new Claim(ClaimTypes.Role, "Admin")
}),
Expires = DateTime.UtcNow.AddHours(1),
Issuer = issuer,
Audience = audience,
SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
};
var tokenHandler = new JwtSecurityTokenHandler();
var token = tokenHandler.CreateToken(tokenDescriptor);
var jwtToken = tokenHandler.WriteToken(token);
return Results.Ok(new
{
token = jwtToken,
expires = tokenDescriptor.Expires
});
}
return Results.Unauthorized();
}).AllowAnonymous();
// --- Produtos (protegidos por JWT) ---
app.MapGet("/products", async (ProductService service) =>
{
var products = await service.GetAllAsync();
return Results.Ok(products);
}).RequireAuthorization();
app.MapGet("/products/{id}", async (int id, ProductService service) =>
{
var product = await service.GetByIdAsync(id);
return product is null ? Results.NotFound() : Results.Ok(product);
}).RequireAuthorization();
app.MapPost("/products", async (ProductDTO dto, ProductService service) =>
{
var product = new Product
{
Name = dto.Name,
Description = dto.Description,
Price = dto.Price
};
await service.AddAsync(product);
return Results.Created($"/products/{product.Id}", product);
}).RequireAuthorization();
app.MapPut("/products/{id}", async (int id, ProductDTO dto, ProductService service) =>
{
var existingProduct = await service.GetByIdAsync(id);
if (existingProduct is null) return Results.NotFound();
existingProduct.Name = dto.Name;
existingProduct.Description = dto.Description;
existingProduct.Price = dto.Price;
await service.UpdateAsync(existingProduct);
return Results.NoContent();
}).RequireAuthorization();
app.MapDelete("/products/{id}", async (int id, ProductService service) =>
{
var existingProduct = await service.GetByIdAsync(id);
if (existingProduct is null) return Results.NotFound();
await service.DeleteAsync(id);
return Results.NoContent();
}).RequireAuthorization();
app.Run();