refactor: manually create endpoints for auth

This commit is contained in:
Fernando Araoz 2025-01-15 20:28:04 -05:00
parent abd7a798c9
commit e2baf275ff
2 changed files with 61 additions and 7 deletions

View File

@ -0,0 +1,41 @@
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Identity.Data;
using Microsoft.AspNetCore.Mvc;
using Trazo.Model;
namespace Trazo.Controllers;
[ApiController]
[Route("api/[controller]")]
public class AuthController(
SignInManager<User> _signInManager,
UserManager<User> _userManager,
IConfiguration _configuration
) : ControllerBase
{
[HttpPost("login")]
public async Task<IActionResult> Login([FromBody] LoginRequest request)
{
var result = await _signInManager.PasswordSignInAsync(
request.Email,
request.Password,
false,
false);
if (!result.Succeeded)
return Unauthorized();
// Generate your JWT here
return Ok(new { token = "your-jwt-token" });
}
[Authorize]
[HttpPost("logout")]
public async Task<IActionResult> Logout()
{
await _signInManager.SignOutAsync();
return Ok();
}
}

View File

@ -9,16 +9,29 @@ builder.Services.AddControllers();
// Add services to the container.
builder.Services.AddAuthorization();
builder.Services.AddAuthentication().AddCookie(IdentityConstants.ApplicationScheme);
builder.Services.AddIdentityCore<User>()
.AddRoles<IdentityRole<Guid>>()
builder.Services.AddIdentity<User, IdentityRole<Guid>>(options =>
{
options.SignIn.RequireConfirmedAccount = true;
options.Password.RequiredLength = 8;
})
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddApiEndpoints();
.AddSignInManager();
builder.Services.AddDbContext<ApplicationDbContext>(options =>
options.UseNpgsql(builder.Configuration.GetConnectionString("Database")));
// CORS
builder.Services.AddCors(options =>
{
options.AddPolicy("ApiPolicy", builder =>
{
builder.WithOrigins("http://localhost")
.AllowAnyMethod()
.AllowAnyHeader();
});
});
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen(options =>
@ -39,11 +52,11 @@ if (app.Environment.IsDevelopment())
app.MapScalarApiReference();
}
app.MapIdentityApi<User>();
app.UseCors("ApiPolicy");
app.UseAuthentication();
app.UseAuthorization();
/*app.MapIdentityApi<User>();*/
app.MapControllers();
app.Run();