Meu usuario não autentica meu código não vem com a claim, esta saindo no 1º If
meu program.cs
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using Microsoft.IdentityModel.Tokens;
using System.Text;
using UsuariosApi.Authorization;
using UsuariosApi.Data;
using UsuariosApi.Models;
using UsuariosApi.Services;
var builder = WebApplication
.CreateBuilder(args);
// Add services to the container.
// configura a aplicação para usar o context no mysql
builder.Services
.AddDbContext<UsuarioDbContext>(opts =>
{
string conn = builder.Configuration.GetConnectionString("UsuarioConnection");
opts.UseMySql(conn, ServerVersion.AutoDetect(conn));
});
// configura a aplicação para usar o entityframework, e o Identity
builder.Services
.AddIdentity<Usuario, IdentityRole>()
.AddEntityFrameworkStores<UsuarioDbContext>()
.AddDefaultTokenProviders();
// inclui o mapeamento
builder.Services
.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies());
builder.Services.AddSingleton<IAuthorizationHandler, IdadeAuthorization>();
// inclui controller
builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
// inclui o serviço swagger
builder.Services.AddSwaggerGen();
builder.Services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme =
JwtBearerDefaults.AuthenticationScheme;
}).AddJwtBearer(options =>
{
options.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters
{
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("HojeÉ:SextaFeiraVinteDeSetembroDeDoisMil&VinteQuatro21:48")),
ValidateAudience = false,
ValidateIssuer = false,
ClockSkew = TimeSpan.Zero
};
});
builder.Services.AddAuthorization(options =>
{
options.AddPolicy("IdadeMinima", policy =>
policy.AddRequirements(new IdadeMinima(18))
);
});
// cria um scopo de serviço usuario
builder.Services.AddScoped<UsuarioService>();
builder.Services.AddScoped<TokenService>();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseHttpsRedirection();
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();
app.Run();