Feature(Auth): Add Login and Refresh Token

This commit is contained in:
Emmanuel Rojas committed 2026-09-04 12:35:11 -05:00
1 parent bd7e505432
commit dcc2e99bb1
20 files changed
+252 -20

No files matched your search

+31
View File
@@ -0,0 +1,31 @@
using Microsoft.AspNetCore.Mvc;
using RT.Application.Services.Contract;
using RT.Domain.DTOs.Auth;
namespace RT.API.Controllers;
[ApiController]
[Route("api/auth")]
public class AuthController(IAuthService authService) : ControllerBase
{
[HttpPost("login")]
public async Task<IActionResult> Login([FromBody] LoginRequestDto dto, CancellationToken ct)
{
var result = await authService.LoginAsync(dto, ct);
return Ok(result);
}
[HttpPost("refresh")]
public async Task<IActionResult> Refresh([FromBody] RefreshRequestDto dto, CancellationToken ct)
{
var result = await authService.RefreshAsync(dto, ct);
return Ok(result);
}
[HttpPost("revoke")]
public async Task<IActionResult> Revoke([FromBody] RefreshRequestDto dto, CancellationToken ct)
{
await authService.RevokeAsync(dto, ct);
return NoContent();
}
}
+35
View File
@@ -1,5 +1,11 @@
using System.Text;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Identity;
using Microsoft.IdentityModel.Tokens;
using RT.Application; using RT.Application;
using RT.Infrastructure; using RT.Infrastructure;
using RT.Infrastructure.Data;
using RT.Infrastructure.Identity;
using Scalar.AspNetCore; using Scalar.AspNetCore;
var builder = WebApplication.CreateBuilder(args); var builder = WebApplication.CreateBuilder(args);
@@ -9,6 +15,34 @@ builder.Services.AddOpenApi();
builder.Services.AddApplication(); builder.Services.AddApplication();
builder.Services.AddInfrastructure(builder.Configuration); builder.Services.AddInfrastructure(builder.Configuration);
builder.Services.AddIdentity<ApplicationUser, IdentityRole>(options =>
{
options.Password.RequireDigit = true;
options.Password.RequiredLength = 8;
options.Password.RequireUppercase = true;
options.Password.RequireNonAlphanumeric = false;
})
.AddEntityFrameworkStores<AppDbContext>()
.AddDefaultTokenProviders();
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
var jwt = builder.Configuration.GetSection("Jwt");
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidateAudience = true,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
ValidIssuer = jwt["Issuer"],
ValidAudience = jwt["Audience"],
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwt["Key"]!)),
};
});
builder.Services.AddAuthorization();
var app = builder.Build(); var app = builder.Build();
if (app.Environment.IsDevelopment()) if (app.Environment.IsDevelopment())
@@ -18,6 +52,7 @@ if (app.Environment.IsDevelopment())
} }
app.UseHttpsRedirection(); app.UseHttpsRedirection();
app.UseAuthentication();
app.UseAuthorization(); app.UseAuthorization();
app.MapControllers(); app.MapControllers();
+1
View File
@@ -6,6 +6,7 @@
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="10.0.11" />
<PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="10.0.11" /> <PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="10.0.11" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="10.0.11"> <PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="10.0.11">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets> <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
+8 -1
View File
@@ -8,5 +8,12 @@
"Microsoft.AspNetCore": "Warning" "Microsoft.AspNetCore": "Warning"
} }
}, },
"AllowedHosts": "*" "AllowedHosts": "*",
"Jwt": {
"Key": "CHANGE_THIS_SECRET_KEY_MIN_32_CHARS!!",
"Issuer": "RynextTemplate",
"Audience": "RynextTemplate",
"ExpiresMinutes": "60",
"RefreshExpiresDays": "7"
}
} }
-6
View File
@@ -1,6 +0,0 @@
namespace RT.Application;
public class Class1
{
}
+4
View File
@@ -1,4 +1,6 @@
using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection;
using RT.Application.Services.Contract;
using RT.Application.Services.Implementation;
namespace RT.Application; namespace RT.Application;
@@ -7,6 +9,8 @@ public static class DependencyInjection
public static IServiceCollection AddApplication(this IServiceCollection services) public static IServiceCollection AddApplication(this IServiceCollection services)
{ {
services.AddAutoMapper(cfg => cfg.AddMaps(typeof(DependencyInjection).Assembly)); services.AddAutoMapper(cfg => cfg.AddMaps(typeof(DependencyInjection).Assembly));
services.AddScoped<IAuthService, AuthService>();
services.AddScoped<ITokenService, TokenService>();
return services; return services;
} }
} }
+1
View File
@@ -7,6 +7,7 @@
<ItemGroup> <ItemGroup>
<PackageReference Include="AutoMapper" Version="16.2.0" /> <PackageReference Include="AutoMapper" Version="16.2.0" />
<PackageReference Include="System.IdentityModel.Tokens.Jwt" Version="8.22.0" />
</ItemGroup> </ItemGroup>
<PropertyGroup> <PropertyGroup>
@@ -0,0 +1,10 @@
using RT.Domain.DTOs.Auth;
namespace RT.Application.Services.Contract;
public interface IAuthService
{
Task<LoginResponseDto> LoginAsync(LoginRequestDto dto, CancellationToken ct = default);
Task<LoginResponseDto> RefreshAsync(RefreshRequestDto dto, CancellationToken ct = default);
Task RevokeAsync(RefreshRequestDto dto, CancellationToken ct = default);
}
@@ -0,0 +1,7 @@
namespace RT.Application.Services.Contract;
public interface ITokenService
{
(string token, DateTime expiresAt) GenerateToken(string userId, string email, string userName);
(string token, DateTime expiresAt) GenerateRefreshToken();
}
@@ -0,0 +1,71 @@
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using RT.Application.Services.Contract;
using RT.Domain.DTOs.Auth;
using RT.Domain.Entities;
using RT.Infrastructure.Data;
using RT.Infrastructure.Identity;
namespace RT.Application.Services.Implementation;
public class AuthService(
UserManager<ApplicationUser> userManager,
ITokenService tokenService,
AppDbContext db) : IAuthService
{
public async Task<LoginResponseDto> LoginAsync(LoginRequestDto dto, CancellationToken ct = default)
{
var user = await userManager.FindByEmailAsync(dto.Email)
?? throw new UnauthorizedAccessException("Invalid credentials.");
if (!await userManager.CheckPasswordAsync(user, dto.Password))
throw new UnauthorizedAccessException("Invalid credentials.");
return await BuildResponseAsync(user, ct);
}
public async Task<LoginResponseDto> RefreshAsync(RefreshRequestDto dto, CancellationToken ct = default)
{
var stored = await db.RefreshTokens.FirstOrDefaultAsync(r => r.Token == dto.RefreshToken, ct)
?? throw new UnauthorizedAccessException("Invalid refresh token.");
if (stored.IsRevoked)
throw new UnauthorizedAccessException("Refresh token revoked.");
if (stored.ExpiresAt < DateTime.UtcNow)
throw new UnauthorizedAccessException("Refresh token expired.");
stored.IsRevoked = true;
await db.SaveChangesAsync(ct);
var user = await userManager.FindByIdAsync(stored.UserId)
?? throw new UnauthorizedAccessException("User not found.");
return await BuildResponseAsync(user, ct);
}
public async Task RevokeAsync(RefreshRequestDto dto, CancellationToken ct = default)
{
var stored = await db.RefreshTokens.FirstOrDefaultAsync(r => r.Token == dto.RefreshToken, ct);
if (stored is null || stored.IsRevoked) return;
stored.IsRevoked = true;
await db.SaveChangesAsync(ct);
}
private async Task<LoginResponseDto> BuildResponseAsync(ApplicationUser user, CancellationToken ct)
{
var (token, expiresAt) = tokenService.GenerateToken(user.Id, user.Email!, user.UserName!);
var (refreshToken, refreshExpiresAt) = tokenService.GenerateRefreshToken();
db.RefreshTokens.Add(new RefreshToken
{
UserId = user.Id,
Token = refreshToken,
ExpiresAt = refreshExpiresAt,
});
await db.SaveChangesAsync(ct);
return new LoginResponseDto(token, expiresAt, refreshToken, refreshExpiresAt, user.MustChangePassword);
}
}
@@ -0,0 +1,43 @@
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Security.Cryptography;
using System.Text;
using Microsoft.Extensions.Configuration;
using Microsoft.IdentityModel.Tokens;
using RT.Application.Services.Contract;
namespace RT.Application.Services.Implementation;
public class TokenService(IConfiguration configuration) : ITokenService
{
public (string token, DateTime expiresAt) GenerateToken(string userId, string email, string userName)
{
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(configuration["Jwt:Key"]!));
var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
var expires = DateTime.UtcNow.AddMinutes(double.Parse(configuration["Jwt:ExpiresMinutes"] ?? "60"));
var claims = new[]
{
new Claim(JwtRegisteredClaimNames.Sub, userId),
new Claim(JwtRegisteredClaimNames.Email, email),
new Claim(JwtRegisteredClaimNames.Name, userName),
new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
};
var token = new JwtSecurityToken(
issuer: configuration["Jwt:Issuer"],
audience: configuration["Jwt:Audience"],
claims: claims,
expires: expires,
signingCredentials: creds);
return (new JwtSecurityTokenHandler().WriteToken(token), expires);
}
public (string token, DateTime expiresAt) GenerateRefreshToken()
{
var token = Convert.ToBase64String(RandomNumberGenerator.GetBytes(64));
var expires = DateTime.UtcNow.AddDays(double.Parse(configuration["Jwt:RefreshExpiresDays"] ?? "7"));
return (token, expires);
}
}
-6
View File
@@ -1,6 +0,0 @@
namespace RT.Domain;
public class Class1
{
}
+3
View File
@@ -0,0 +1,3 @@
namespace RT.Domain.DTOs.Auth;
public record LoginRequestDto(string Email, string Password);
+8
View File
@@ -0,0 +1,8 @@
namespace RT.Domain.DTOs.Auth;
public record LoginResponseDto(
string Token,
DateTime ExpiresAt,
string RefreshToken,
DateTime RefreshExpiresAt,
bool MustChangePassword);
+3
View File
@@ -0,0 +1,3 @@
namespace RT.Domain.DTOs.Auth;
public record RefreshRequestDto(string RefreshToken);
+10
View File
@@ -0,0 +1,10 @@
namespace RT.Domain.Entities;
public class RefreshToken
{
public Guid Id { get; set; } = Guid.NewGuid();
public string UserId { get; set; } = null!;
public string Token { get; set; } = null!;
public DateTime ExpiresAt { get; set; }
public bool IsRevoked { get; set; }
}
-6
View File
@@ -1,6 +0,0 @@
namespace RT.Infrastructure;
public class Class1
{
}
+7 -1
View File
@@ -1,9 +1,15 @@
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using RT.Domain.Entities;
using RT.Infrastructure.Identity;
namespace RT.Infrastructure.Data; namespace RT.Infrastructure.Data;
public class AppDbContext(DbContextOptions<AppDbContext> options) : DbContext(options) public class AppDbContext(DbContextOptions<AppDbContext> options)
: IdentityDbContext<ApplicationUser>(options)
{ {
public DbSet<RefreshToken> RefreshTokens => Set<RefreshToken>();
protected override void OnModelCreating(ModelBuilder modelBuilder) protected override void OnModelCreating(ModelBuilder modelBuilder)
{ {
base.OnModelCreating(modelBuilder); base.OnModelCreating(modelBuilder);
@@ -0,0 +1,8 @@
using Microsoft.AspNetCore.Identity;
namespace RT.Infrastructure.Identity;
public class ApplicationUser : IdentityUser
{
public bool MustChangePassword { get; set; }
}
@@ -6,8 +6,10 @@
<ItemGroup> <ItemGroup>
<PackageReference Include="EFCore.NamingConventions" Version="10.0.1" /> <PackageReference Include="EFCore.NamingConventions" Version="10.0.1" />
<PackageReference Include="Microsoft.AspNetCore.Identity.EntityFrameworkCore" Version="10.0.11" />
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="10.0.11" /> <PackageReference Include="Microsoft.EntityFrameworkCore" Version="10.0.11" />
<PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="10.0.3" /> <PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="10.0.3" />
<PackageReference Include="System.IdentityModel.Tokens.Jwt" Version="8.22.0" />
</ItemGroup> </ItemGroup>
<PropertyGroup> <PropertyGroup>