first commit
This commit is contained in:
@@ -0,0 +1,8 @@
|
||||
<Solution>
|
||||
<Folder Name="/example/">
|
||||
<Project Path="example/SequenceAuth.Example.csproj" />
|
||||
</Folder>
|
||||
<Folder Name="/lib/">
|
||||
<Project Path="lib/SequenceAuth.Lib.csproj" />
|
||||
</Folder>
|
||||
</Solution>
|
||||
@@ -0,0 +1,17 @@
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
|
||||
namespace SequenceAuth.Example.Controllers;
|
||||
|
||||
[ApiController]
|
||||
[Route("[controller]/[action]")]
|
||||
public abstract class ApiControllerBase : ControllerBase
|
||||
{
|
||||
protected Guid UserId
|
||||
{
|
||||
get
|
||||
{
|
||||
var options = HttpContext.RequestServices.GetRequiredService<Microsoft.Extensions.Options.IOptions<SequenceAuth.Lib.SequenceAuthOptions>>().Value;
|
||||
return Guid.Parse(HttpContext.Items[options.UserIdItemKey]?.ToString() ?? throw new UnauthorizedAccessException());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
using MediatR;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using SequenceAuth.Example.Features.Auth;
|
||||
|
||||
namespace SequenceAuth.Example.Controllers;
|
||||
|
||||
public class AuthController(IMediator mediator) : ApiControllerBase
|
||||
{
|
||||
public record LoginRequest(string Username);
|
||||
|
||||
[HttpPost]
|
||||
public async Task<IActionResult> Login([FromBody] LoginRequest request)
|
||||
{
|
||||
var result = await mediator.Send(new LoginCommand(request.Username));
|
||||
return Ok(result.User);
|
||||
}
|
||||
|
||||
[HttpPost]
|
||||
public async Task<IActionResult> Logout()
|
||||
{
|
||||
await mediator.Send(new LogoutCommand());
|
||||
return Ok();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
|
||||
namespace SequenceAuth.Example.Controllers;
|
||||
|
||||
public class SecureController : ApiControllerBase
|
||||
{
|
||||
[HttpGet]
|
||||
public IActionResult GetData()
|
||||
{
|
||||
return Ok(new { Message = "This is protected data. You must have a valid sequence to see this." });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
using MediatR;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using SequenceAuth.Example.Domain;
|
||||
using SequenceAuth.Example.Features.Todos;
|
||||
|
||||
namespace SequenceAuth.Example.Controllers;
|
||||
|
||||
public class TodoController(IMediator mediator) : ApiControllerBase
|
||||
{
|
||||
public record CreateTodoRequest(string Title);
|
||||
|
||||
[HttpPost]
|
||||
public async Task<IActionResult> Create([FromBody] CreateTodoRequest request)
|
||||
{
|
||||
var result = await mediator.Send(new CreateTodoCommand(UserId, request.Title));
|
||||
return Ok(result);
|
||||
}
|
||||
|
||||
[HttpGet]
|
||||
public async Task<IActionResult> List([FromQuery] TodoStatus? status)
|
||||
{
|
||||
var result = await mediator.Send(new GetTodosQuery(UserId, status));
|
||||
return Ok(result);
|
||||
}
|
||||
|
||||
[HttpPut("{id}")]
|
||||
public async Task<IActionResult> ChangeStatus(Guid id, [FromQuery] TodoStatus status)
|
||||
{
|
||||
var result = await mediator.Send(new ChangeTodoStatusCommand(id, UserId, status));
|
||||
|
||||
return result.Outcome switch
|
||||
{
|
||||
ChangeTodoStatusOutcome.Success => Ok(result.Item),
|
||||
ChangeTodoStatusOutcome.NotFound => NotFound(),
|
||||
ChangeTodoStatusOutcome.Unauthorized => StatusCode(403), // No identity claims for Forbid() without auth scheme
|
||||
_ => StatusCode(500)
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
namespace SequenceAuth.Example.Domain;
|
||||
|
||||
public record User(Guid Id, string Username);
|
||||
|
||||
public enum TodoStatus
|
||||
{
|
||||
Pending,
|
||||
InProgress,
|
||||
Completed,
|
||||
Canceled
|
||||
}
|
||||
|
||||
public record TodoItem(Guid Id, Guid UserId, string Title, TodoStatus Status);
|
||||
@@ -0,0 +1,42 @@
|
||||
using MediatR;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using SequenceAuth.Example.Domain;
|
||||
using SequenceAuth.Example.Infrastructure;
|
||||
using SequenceAuth.Lib;
|
||||
|
||||
namespace SequenceAuth.Example.Features.Auth;
|
||||
|
||||
public record LoginCommand(string Username) : IRequest<LoginResult>;
|
||||
public record LoginResult(User User, string InitialSequence);
|
||||
|
||||
public class LoginCommandHandler(AppDbContext dbContext, ISequenceStore sequenceStore, Microsoft.AspNetCore.Http.IHttpContextAccessor httpContextAccessor, Microsoft.Extensions.Options.IOptions<SequenceAuth.Lib.SequenceAuthOptions> options) : IRequestHandler<LoginCommand, LoginResult>
|
||||
{
|
||||
public async Task<LoginResult> Handle(LoginCommand request, CancellationToken cancellationToken)
|
||||
{
|
||||
var userOpt = await dbContext.Users.FirstOrDefaultAsync(u => u.Username == request.Username, cancellationToken);
|
||||
|
||||
var user = userOpt switch
|
||||
{
|
||||
null => await CreateUser(request.Username, cancellationToken),
|
||||
_ => userOpt
|
||||
};
|
||||
|
||||
var initialSequenceId = Guid.NewGuid().ToString("N");
|
||||
var sequenceData = new SequenceData(UserId: user.Id.ToString(), RequestsRemaining: 1000, State: SequenceState.Initialized, NextSequenceId: initialSequenceId);
|
||||
|
||||
await sequenceStore.SaveSequenceAsync(initialSequenceId, sequenceData);
|
||||
|
||||
httpContextAccessor.HttpContext?.Response.Headers.Append(options.Value.NextHeaderName, initialSequenceId);
|
||||
httpContextAccessor.HttpContext?.Response.Headers.Append(options.Value.RequestsRemainingHeaderName, "1000");
|
||||
|
||||
return new LoginResult(user, initialSequenceId);
|
||||
}
|
||||
|
||||
private async Task<User> CreateUser(string username, CancellationToken cancellationToken)
|
||||
{
|
||||
var user = new User(Guid.NewGuid(), username);
|
||||
dbContext.Users.Add(user);
|
||||
await dbContext.SaveChangesAsync(cancellationToken);
|
||||
return user;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
using MediatR;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using SequenceAuth.Lib;
|
||||
|
||||
namespace SequenceAuth.Example.Features.Auth;
|
||||
|
||||
public record LogoutCommand() : IRequest;
|
||||
|
||||
public class LogoutCommandHandler(ISequenceStore sequenceStore, IHttpContextAccessor httpContextAccessor, Microsoft.Extensions.Options.IOptions<SequenceAuthOptions> options) : IRequestHandler<LogoutCommand>
|
||||
{
|
||||
public async Task Handle(LogoutCommand request, CancellationToken cancellationToken)
|
||||
{
|
||||
var userIdStr = httpContextAccessor.HttpContext?.Items[options.Value.UserIdItemKey]?.ToString();
|
||||
var isUserIdPresent = string.IsNullOrEmpty(userIdStr);
|
||||
|
||||
_ = isUserIdPresent switch
|
||||
{
|
||||
false => await ProcessLogout(userIdStr!),
|
||||
true => 0
|
||||
};
|
||||
}
|
||||
|
||||
private async Task<int> ProcessLogout(string userId)
|
||||
{
|
||||
await sequenceStore.InvalidateUserSessionsAsync(userId);
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
using MediatR;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using SequenceAuth.Example.Domain;
|
||||
using SequenceAuth.Example.Infrastructure;
|
||||
|
||||
namespace SequenceAuth.Example.Features.Todos;
|
||||
|
||||
public enum ChangeTodoStatusOutcome { Success, NotFound, Unauthorized }
|
||||
|
||||
public record ChangeTodoStatusResult(ChangeTodoStatusOutcome Outcome, TodoItem? Item);
|
||||
|
||||
public record ChangeTodoStatusCommand(Guid TodoId, Guid UserId, TodoStatus NewStatus) : IRequest<ChangeTodoStatusResult>;
|
||||
|
||||
public class ChangeTodoStatusCommandHandler(AppDbContext dbContext) : IRequestHandler<ChangeTodoStatusCommand, ChangeTodoStatusResult>
|
||||
{
|
||||
public async Task<ChangeTodoStatusResult> Handle(ChangeTodoStatusCommand request, CancellationToken cancellationToken)
|
||||
{
|
||||
var todo = await dbContext.Todos.FirstOrDefaultAsync(t => t.Id == request.TodoId, cancellationToken);
|
||||
|
||||
return todo switch
|
||||
{
|
||||
null => new ChangeTodoStatusResult(ChangeTodoStatusOutcome.NotFound, null),
|
||||
{ UserId: var userId } when userId != request.UserId => new ChangeTodoStatusResult(ChangeTodoStatusOutcome.Unauthorized, null),
|
||||
_ => await UpdateStatusAsync(todo, request.NewStatus, cancellationToken)
|
||||
};
|
||||
}
|
||||
|
||||
private async Task<ChangeTodoStatusResult> UpdateStatusAsync(TodoItem todo, TodoStatus newStatus, CancellationToken cancellationToken)
|
||||
{
|
||||
var updatedTodo = todo with { Status = newStatus };
|
||||
|
||||
dbContext.Entry(todo).CurrentValues.SetValues(updatedTodo);
|
||||
await dbContext.SaveChangesAsync(cancellationToken);
|
||||
|
||||
return new ChangeTodoStatusResult(ChangeTodoStatusOutcome.Success, updatedTodo);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
using MediatR;
|
||||
using SequenceAuth.Example.Domain;
|
||||
using SequenceAuth.Example.Infrastructure;
|
||||
|
||||
namespace SequenceAuth.Example.Features.Todos;
|
||||
|
||||
public record CreateTodoCommand(Guid UserId, string Title) : IRequest<TodoItem>;
|
||||
|
||||
public class CreateTodoCommandHandler(AppDbContext dbContext) : IRequestHandler<CreateTodoCommand, TodoItem>
|
||||
{
|
||||
public async Task<TodoItem> Handle(CreateTodoCommand request, CancellationToken cancellationToken)
|
||||
{
|
||||
var todo = new TodoItem(Guid.NewGuid(), request.UserId, request.Title, TodoStatus.Pending);
|
||||
dbContext.Todos.Add(todo);
|
||||
await dbContext.SaveChangesAsync(cancellationToken);
|
||||
return todo;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
using MediatR;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using SequenceAuth.Example.Domain;
|
||||
using SequenceAuth.Example.Infrastructure;
|
||||
|
||||
namespace SequenceAuth.Example.Features.Todos;
|
||||
|
||||
public record GetTodosQuery(Guid UserId, TodoStatus? StatusFilter) : IRequest<List<TodoItem>>;
|
||||
|
||||
public class GetTodosQueryHandler(AppDbContext dbContext) : IRequestHandler<GetTodosQuery, List<TodoItem>>
|
||||
{
|
||||
public async Task<List<TodoItem>> Handle(GetTodosQuery request, CancellationToken cancellationToken)
|
||||
{
|
||||
var query = dbContext.Todos.Where(t => t.UserId == request.UserId);
|
||||
|
||||
query = request.StatusFilter switch
|
||||
{
|
||||
null => query,
|
||||
var status => query.Where(t => t.Status == status)
|
||||
};
|
||||
|
||||
return await query.ToListAsync(cancellationToken);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using SequenceAuth.Example.Domain;
|
||||
|
||||
namespace SequenceAuth.Example.Infrastructure;
|
||||
|
||||
public class AppDbContext(DbContextOptions<AppDbContext> options) : DbContext(options)
|
||||
{
|
||||
public DbSet<User> Users => Set<User>();
|
||||
public DbSet<TodoItem> Todos => Set<TodoItem>();
|
||||
|
||||
protected override void OnModelCreating(ModelBuilder modelBuilder)
|
||||
{
|
||||
modelBuilder.Entity<User>(entity =>
|
||||
{
|
||||
entity.HasKey(e => e.Id);
|
||||
entity.Property(e => e.Username).IsRequired();
|
||||
entity.HasIndex(e => e.Username).IsUnique();
|
||||
});
|
||||
|
||||
modelBuilder.Entity<TodoItem>(entity =>
|
||||
{
|
||||
entity.HasKey(e => e.Id);
|
||||
entity.Property(e => e.Title).IsRequired();
|
||||
entity.Property(e => e.Status).HasConversion<string>();
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
using System.Text.RegularExpressions;
|
||||
using Microsoft.AspNetCore.Routing;
|
||||
|
||||
namespace SequenceAuth.Example.Infrastructure;
|
||||
|
||||
public class KebabCaseParameterTransformer : IOutboundParameterTransformer
|
||||
{
|
||||
public string? TransformOutbound(object? value)
|
||||
{
|
||||
return value == null ? null : value.ToString()!.ToKebabCase();
|
||||
}
|
||||
}
|
||||
|
||||
public static partial class StringExtension
|
||||
{
|
||||
[GeneratedRegex("([a-z0-9])([A-Z])", RegexOptions.Compiled)]
|
||||
private static partial Regex KebabCaseRule();
|
||||
|
||||
public static string ToKebabCase(this string input)
|
||||
=> KebabCaseRule().Replace(input, "$1-$2").ToLower().Trim('-');
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
// <auto-generated />
|
||||
using System;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore.Infrastructure;
|
||||
using Microsoft.EntityFrameworkCore.Migrations;
|
||||
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
|
||||
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
|
||||
using SequenceAuth.Example.Infrastructure;
|
||||
|
||||
#nullable disable
|
||||
|
||||
namespace SequenceAuth.Example.Migrations
|
||||
{
|
||||
[DbContext(typeof(AppDbContext))]
|
||||
[Migration("20260612174016_InitialCreate")]
|
||||
partial class InitialCreate
|
||||
{
|
||||
/// <inheritdoc />
|
||||
protected override void BuildTargetModel(ModelBuilder modelBuilder)
|
||||
{
|
||||
#pragma warning disable 612, 618
|
||||
modelBuilder
|
||||
.HasAnnotation("ProductVersion", "10.0.9")
|
||||
.HasAnnotation("Relational:MaxIdentifierLength", 63);
|
||||
|
||||
NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
|
||||
|
||||
modelBuilder.Entity("SequenceAuth.Example.Domain.TodoItem", b =>
|
||||
{
|
||||
b.Property<Guid>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("uuid");
|
||||
|
||||
b.Property<string>("Status")
|
||||
.IsRequired()
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<string>("Title")
|
||||
.IsRequired()
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<Guid>("UserId")
|
||||
.HasColumnType("uuid");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.ToTable("Todos");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("SequenceAuth.Example.Domain.User", b =>
|
||||
{
|
||||
b.Property<Guid>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("uuid");
|
||||
|
||||
b.Property<string>("Username")
|
||||
.IsRequired()
|
||||
.HasColumnType("text");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("Username")
|
||||
.IsUnique();
|
||||
|
||||
b.ToTable("Users");
|
||||
});
|
||||
#pragma warning restore 612, 618
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
using System;
|
||||
using Microsoft.EntityFrameworkCore.Migrations;
|
||||
|
||||
#nullable disable
|
||||
|
||||
namespace SequenceAuth.Example.Migrations
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public partial class InitialCreate : Migration
|
||||
{
|
||||
/// <inheritdoc />
|
||||
protected override void Up(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.CreateTable(
|
||||
name: "Todos",
|
||||
columns: table => new
|
||||
{
|
||||
Id = table.Column<Guid>(type: "uuid", nullable: false),
|
||||
UserId = table.Column<Guid>(type: "uuid", nullable: false),
|
||||
Title = table.Column<string>(type: "text", nullable: false),
|
||||
Status = table.Column<string>(type: "text", nullable: false)
|
||||
},
|
||||
constraints: table =>
|
||||
{
|
||||
table.PrimaryKey("PK_Todos", x => x.Id);
|
||||
});
|
||||
|
||||
migrationBuilder.CreateTable(
|
||||
name: "Users",
|
||||
columns: table => new
|
||||
{
|
||||
Id = table.Column<Guid>(type: "uuid", nullable: false),
|
||||
Username = table.Column<string>(type: "text", nullable: false)
|
||||
},
|
||||
constraints: table =>
|
||||
{
|
||||
table.PrimaryKey("PK_Users", x => x.Id);
|
||||
});
|
||||
|
||||
migrationBuilder.CreateIndex(
|
||||
name: "IX_Users_Username",
|
||||
table: "Users",
|
||||
column: "Username",
|
||||
unique: true);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override void Down(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.DropTable(
|
||||
name: "Todos");
|
||||
|
||||
migrationBuilder.DropTable(
|
||||
name: "Users");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
// <auto-generated />
|
||||
using System;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore.Infrastructure;
|
||||
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
|
||||
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
|
||||
using SequenceAuth.Example.Infrastructure;
|
||||
|
||||
#nullable disable
|
||||
|
||||
namespace SequenceAuth.Example.Migrations
|
||||
{
|
||||
[DbContext(typeof(AppDbContext))]
|
||||
partial class AppDbContextModelSnapshot : ModelSnapshot
|
||||
{
|
||||
protected override void BuildModel(ModelBuilder modelBuilder)
|
||||
{
|
||||
#pragma warning disable 612, 618
|
||||
modelBuilder
|
||||
.HasAnnotation("ProductVersion", "10.0.9")
|
||||
.HasAnnotation("Relational:MaxIdentifierLength", 63);
|
||||
|
||||
NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
|
||||
|
||||
modelBuilder.Entity("SequenceAuth.Example.Domain.TodoItem", b =>
|
||||
{
|
||||
b.Property<Guid>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("uuid");
|
||||
|
||||
b.Property<string>("Status")
|
||||
.IsRequired()
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<string>("Title")
|
||||
.IsRequired()
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<Guid>("UserId")
|
||||
.HasColumnType("uuid");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.ToTable("Todos");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("SequenceAuth.Example.Domain.User", b =>
|
||||
{
|
||||
b.Property<Guid>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("uuid");
|
||||
|
||||
b.Property<string>("Username")
|
||||
.IsRequired()
|
||||
.HasColumnType("text");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("Username")
|
||||
.IsUnique();
|
||||
|
||||
b.ToTable("Users");
|
||||
});
|
||||
#pragma warning restore 612, 618
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
namespace SequenceAuth.Example.Options;
|
||||
|
||||
public record RedisOptions
|
||||
{
|
||||
public required string Configuration { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
using Microsoft.AspNetCore.Mvc.ApplicationModels;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.Options;
|
||||
using Scalar.AspNetCore;
|
||||
using SequenceAuth.Example.Infrastructure;
|
||||
using SequenceAuth.Example.Options;
|
||||
using SequenceAuth.Lib;
|
||||
using StackExchange.Redis;
|
||||
|
||||
var builder = WebApplication.CreateBuilder(args);
|
||||
|
||||
builder.Services.AddControllers(options =>
|
||||
{
|
||||
options.Conventions.Add(new RouteTokenTransformerConvention(new KebabCaseParameterTransformer()));
|
||||
});
|
||||
|
||||
builder.Services.AddDbContext<AppDbContext>(options =>
|
||||
{
|
||||
options.UseNpgsql(builder.Configuration.GetConnectionString("DefaultConnection") ?? "Host=localhost;Database=sequencedb;Username=sequence_user;Password=sequence_password");
|
||||
});
|
||||
|
||||
builder.Services.AddHttpContextAccessor();
|
||||
builder.Services.AddMediatR(cfg => cfg.RegisterServicesFromAssembly(typeof(Program).Assembly));
|
||||
|
||||
var sequenceOptions = new SequenceAuthOptions();
|
||||
builder.Services.AddSequenceAuth(opts =>
|
||||
{
|
||||
opts.IgnoredPaths = sequenceOptions.IgnoredPaths.Concat(["/auth/login"]).ToHashSet();
|
||||
});
|
||||
|
||||
builder.Services.AddOpenApi();
|
||||
|
||||
builder.Services.AddCors(options =>
|
||||
{
|
||||
options.AddDefaultPolicy(policy =>
|
||||
{
|
||||
policy.AllowAnyOrigin()
|
||||
.AllowAnyMethod()
|
||||
.AllowAnyHeader()
|
||||
.WithExposedHeaders(sequenceOptions.NextHeaderName, sequenceOptions.RequestsRemainingHeaderName);
|
||||
});
|
||||
});
|
||||
|
||||
builder.Services.Configure<RedisOptions>(builder.Configuration.GetSection("RedisOptions"));
|
||||
|
||||
builder.Services.AddSingleton<IConnectionMultiplexer>(sp =>
|
||||
ConnectionMultiplexer.Connect(sp.GetRequiredService<IOptions<RedisOptions>>().Value.Configuration));
|
||||
|
||||
builder.Services.AddSingleton<ISequenceStore, SequenceAuth.Example.RedisSequenceStore>();
|
||||
|
||||
var app = builder.Build();
|
||||
|
||||
using (var scope = app.Services.CreateScope())
|
||||
{
|
||||
var db = scope.ServiceProvider.GetRequiredService<AppDbContext>();
|
||||
await db.Database.MigrateAsync();
|
||||
}
|
||||
|
||||
app.MapOpenApi();
|
||||
|
||||
app.MapScalarApiReference(options =>
|
||||
{
|
||||
options.Title = "SequenceAuth API";
|
||||
options.WithDefaultHttpClient(ScalarTarget.CSharp, ScalarClient.HttpClient);
|
||||
});
|
||||
|
||||
app.MapGet("/", () => Results.Redirect("/scalar/v1"));
|
||||
|
||||
app.UseCors();
|
||||
app.UseMiddleware<SequenceAuthMiddleware>();
|
||||
app.MapControllers();
|
||||
|
||||
app.Run();
|
||||
|
||||
public partial class Program { }
|
||||
@@ -0,0 +1,23 @@
|
||||
{
|
||||
"$schema": "https://json.schemastore.org/launchsettings.json",
|
||||
"profiles": {
|
||||
"http": {
|
||||
"commandName": "Project",
|
||||
"dotnetRunMessages": true,
|
||||
"launchBrowser": false,
|
||||
"applicationUrl": "http://localhost:5064",
|
||||
"environmentVariables": {
|
||||
"ASPNETCORE_ENVIRONMENT": "Development"
|
||||
}
|
||||
},
|
||||
"https": {
|
||||
"commandName": "Project",
|
||||
"dotnetRunMessages": true,
|
||||
"launchBrowser": false,
|
||||
"applicationUrl": "https://localhost:7215;http://localhost:5064",
|
||||
"environmentVariables": {
|
||||
"ASPNETCORE_ENVIRONMENT": "Development"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
using StackExchange.Redis;
|
||||
using System.Text.Json;
|
||||
using SequenceAuth.Lib;
|
||||
|
||||
namespace SequenceAuth.Example;
|
||||
|
||||
public class RedisSequenceStore(IConnectionMultiplexer redis) : ISequenceStore
|
||||
{
|
||||
private readonly IDatabase _db = redis.GetDatabase();
|
||||
|
||||
public async Task<Option<SequenceData>> GetSequenceAsync(string sequenceId)
|
||||
{
|
||||
var value = await _db.StringGetAsync(sequenceId);
|
||||
|
||||
return ((string?)value) switch
|
||||
{
|
||||
null => Option<SequenceData>.None(),
|
||||
string str => ParseData(str)
|
||||
};
|
||||
}
|
||||
|
||||
private static Option<SequenceData> ParseData(string str)
|
||||
{
|
||||
var data = JsonSerializer.Deserialize<SequenceData>(str);
|
||||
return data switch
|
||||
{
|
||||
null => Option<SequenceData>.None(),
|
||||
_ => Option<SequenceData>.Some(data)
|
||||
};
|
||||
}
|
||||
|
||||
public async Task<StoreOutcome> SaveSequenceAsync(string sequenceId, SequenceData data)
|
||||
{
|
||||
var json = JsonSerializer.Serialize(data);
|
||||
_ = await _db.StringSetAsync(sequenceId, json);
|
||||
_ = await _db.SetAddAsync($"UserSessions:{data.UserId}", sequenceId);
|
||||
return StoreOutcome.Success;
|
||||
}
|
||||
|
||||
public async Task<StoreOutcome> InvalidateUserSessionsAsync(string userId)
|
||||
{
|
||||
var sessionKeys = await _db.SetMembersAsync($"UserSessions:{userId}");
|
||||
foreach(var key in sessionKeys)
|
||||
{
|
||||
var seqOpt = await GetSequenceAsync(key.ToString());
|
||||
_ = seqOpt.State switch
|
||||
{
|
||||
OptionState.Some => await UpdateToCompromisedAsync(key.ToString(), seqOpt.Value!),
|
||||
_ => StoreOutcome.Failure
|
||||
};
|
||||
}
|
||||
return StoreOutcome.Success;
|
||||
}
|
||||
|
||||
private async Task<StoreOutcome> UpdateToCompromisedAsync(string sequenceId, SequenceData data)
|
||||
{
|
||||
var compData = data with { State = SequenceState.Compromised };
|
||||
var json = JsonSerializer.Serialize(compData);
|
||||
_ = await _db.StringSetAsync(sequenceId, json);
|
||||
return StoreOutcome.Success;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk.Web">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net10.0</TargetFramework>
|
||||
<Nullable>enable</Nullable>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="MediatR" Version="14.1.0" />
|
||||
<PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="10.0.9" />
|
||||
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="10.0.9">
|
||||
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
|
||||
<PrivateAssets>all</PrivateAssets>
|
||||
</PackageReference>
|
||||
<PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="10.0.2" />
|
||||
<PackageReference Include="Scalar.AspNetCore" Version="2.16.3" />
|
||||
<PackageReference Include="StackExchange.Redis" Version="2.13.17" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\lib\SequenceAuth.Lib.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
@@ -0,0 +1,6 @@
|
||||
@SequenceAuth.Example_HostAddress = http://localhost:5064
|
||||
|
||||
GET {{SequenceAuth.Example_HostAddress}}/weatherforecast/
|
||||
Accept: application/json
|
||||
|
||||
###
|
||||
@@ -0,0 +1,8 @@
|
||||
{
|
||||
"Logging": {
|
||||
"LogLevel": {
|
||||
"Default": "Information",
|
||||
"Microsoft.AspNetCore": "Warning"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
{
|
||||
"Logging": {
|
||||
"LogLevel": {
|
||||
"Default": "Information",
|
||||
"Microsoft.AspNetCore": "Warning"
|
||||
}
|
||||
},
|
||||
"ConnectionStrings": {
|
||||
"DefaultConnection": "Host=localhost;Port=5432;Database=sequencedb;Username=sequence_user;Password=sequence_password"
|
||||
},
|
||||
"RedisOptions": {
|
||||
"Configuration": "localhost:6379"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
namespace SequenceAuth.Lib;
|
||||
|
||||
public interface ISequenceStore
|
||||
{
|
||||
Task<Option<SequenceData>> GetSequenceAsync(string sequenceId);
|
||||
Task<StoreOutcome> SaveSequenceAsync(string sequenceId, SequenceData data);
|
||||
Task<StoreOutcome> InvalidateUserSessionsAsync(string userId);
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
namespace SequenceAuth.Lib;
|
||||
|
||||
public enum SequenceState
|
||||
{
|
||||
Initialized,
|
||||
Active,
|
||||
Rotated,
|
||||
Compromised
|
||||
}
|
||||
|
||||
public enum ValidationOutcome
|
||||
{
|
||||
Success,
|
||||
SequenceNotFound,
|
||||
LimitExceeded,
|
||||
CompromisedSequenceDetected,
|
||||
InternalError
|
||||
}
|
||||
|
||||
public enum OptionState
|
||||
{
|
||||
Some,
|
||||
None
|
||||
}
|
||||
|
||||
public record Option<T>(T? Value, OptionState State)
|
||||
{
|
||||
public static Option<T> Some(T value) => new(value, OptionState.Some);
|
||||
public static Option<T> None() => new(default, OptionState.None);
|
||||
}
|
||||
|
||||
public enum StoreOutcome
|
||||
{
|
||||
Success,
|
||||
Failure
|
||||
}
|
||||
|
||||
public record SequenceData(string UserId, int RequestsRemaining, SequenceState State, string NextSequenceId);
|
||||
@@ -0,0 +1,23 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net10.0</TargetFramework>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Nullable>enable</Nullable>
|
||||
|
||||
<!-- NuGet Package Metadata -->
|
||||
<PackageId>SequenceAuth</PackageId>
|
||||
<Version>1.0.0</Version>
|
||||
<Authors>YourName</Authors>
|
||||
<Description>A C# library for Sequence Token Rotation authorization using Redis.</Description>
|
||||
<RepositoryUrl>https://github.com/your-repo/SequenceAuth</RepositoryUrl>
|
||||
<PackageTags>authentication;redis;security</PackageTags>
|
||||
<GeneratePackageOnBuild>true</GeneratePackageOnBuild>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<!-- Use FrameworkReference for ASP.NET Core types (like HttpContext) instead of the outdated NuGet package -->
|
||||
<FrameworkReference Include="Microsoft.AspNetCore.App" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
@@ -0,0 +1,17 @@
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using System;
|
||||
|
||||
namespace SequenceAuth.Lib;
|
||||
|
||||
public static class SequenceAuthExtensions
|
||||
{
|
||||
public static IServiceCollection AddSequenceAuth(this IServiceCollection services, Action<SequenceAuthOptions> configureOptions)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(configureOptions);
|
||||
|
||||
services.Configure(configureOptions);
|
||||
services.AddScoped<SequenceManager>();
|
||||
|
||||
return services;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,109 @@
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.Extensions.Options;
|
||||
|
||||
namespace SequenceAuth.Lib;
|
||||
|
||||
public class SequenceAuthMiddleware(RequestDelegate next, IOptions<SequenceAuthOptions> options)
|
||||
{
|
||||
private readonly SequenceAuthOptions _options = options?.Value ?? throw new InvalidOperationException("SequenceAuthOptions must be registered in DI using AddSequenceAuth.");
|
||||
|
||||
public async Task InvokeAsync(HttpContext context, SequenceManager sequenceManager)
|
||||
{
|
||||
await (context.Request.Method switch
|
||||
{
|
||||
"OPTIONS" => next(context),
|
||||
_ => ProcessPath(context, sequenceManager)
|
||||
});
|
||||
}
|
||||
|
||||
private async Task ProcessPath(HttpContext context, SequenceManager sequenceManager)
|
||||
{
|
||||
var path = context.Request.Path.Value?.ToLowerInvariant() ?? "";
|
||||
|
||||
var isIgnored = _options.IgnoredPaths.FirstOrDefault(x => path.StartsWith(x));
|
||||
await (isIgnored switch
|
||||
{
|
||||
null => CheckHeader(context, sequenceManager),
|
||||
_ => next(context)
|
||||
});
|
||||
}
|
||||
|
||||
private async Task CheckHeader(HttpContext context, SequenceManager sequenceManager)
|
||||
{
|
||||
var headerCount = context.Request.Headers[_options.AuthHeaderName].Count;
|
||||
|
||||
await (headerCount switch
|
||||
{
|
||||
0 => HandleMissingHeader(context),
|
||||
> 0 => ProcessWithHeader(context, sequenceManager, context.Request.Headers[_options.AuthHeaderName].ToString()!),
|
||||
_ => HandleMissingHeader(context)
|
||||
});
|
||||
}
|
||||
|
||||
private Task HandleMissingHeader(HttpContext context)
|
||||
{
|
||||
context.Response.StatusCode = 401;
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
private async Task ProcessWithHeader(HttpContext context, SequenceManager sequenceManager, string sequenceId)
|
||||
{
|
||||
var result = await sequenceManager.ValidateAndRotateAsync(sequenceId);
|
||||
|
||||
await (result.Outcome switch
|
||||
{
|
||||
ValidationOutcome.Success => HandleSuccess(context, result.NextSequence, result.UserId, result.RequestsRemaining),
|
||||
_ => HandleFailure(context, result.Outcome)
|
||||
});
|
||||
}
|
||||
|
||||
private async Task HandleSuccess(HttpContext context, Option<string> nextSequenceOpt, Option<string> userIdOpt, Option<int> requestsRemainingOpt)
|
||||
{
|
||||
_ = nextSequenceOpt.State switch
|
||||
{
|
||||
OptionState.Some => AddHeader(context, nextSequenceOpt.Value!),
|
||||
OptionState.None => 0,
|
||||
_ => 0
|
||||
};
|
||||
|
||||
_ = userIdOpt.State switch
|
||||
{
|
||||
OptionState.Some => AddUserContext(context, userIdOpt.Value!),
|
||||
OptionState.None => 0,
|
||||
_ => 0
|
||||
};
|
||||
|
||||
_ = requestsRemainingOpt.State switch
|
||||
{
|
||||
OptionState.Some => AddRemainingHeader(context, requestsRemainingOpt.Value),
|
||||
OptionState.None => 0,
|
||||
_ => 0
|
||||
};
|
||||
|
||||
await next(context);
|
||||
}
|
||||
|
||||
private int AddRemainingHeader(HttpContext context, int remaining)
|
||||
{
|
||||
context.Response.Headers.Append(_options.RequestsRemainingHeaderName, remaining.ToString());
|
||||
return 1;
|
||||
}
|
||||
|
||||
private int AddHeader(HttpContext context, string value)
|
||||
{
|
||||
context.Response.Headers.Append(_options.NextHeaderName, value);
|
||||
return 1;
|
||||
}
|
||||
|
||||
private int AddUserContext(HttpContext context, string userId)
|
||||
{
|
||||
context.Items[_options.UserIdItemKey] = userId;
|
||||
return 1;
|
||||
}
|
||||
|
||||
private Task HandleFailure(HttpContext context, ValidationOutcome outcome)
|
||||
{
|
||||
context.Response.StatusCode = 401;
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
namespace SequenceAuth.Lib;
|
||||
|
||||
public class SequenceAuthOptions
|
||||
{
|
||||
public virtual string UserIdItemKey { get; set; } = "UserId";
|
||||
public virtual string AuthHeaderName { get; set; } = "X-Auth-Seq";
|
||||
public virtual string NextHeaderName { get; set; } = "X-Next-Seq";
|
||||
public virtual string RequestsRemainingHeaderName { get; set; } = "X-Requests-Remaining";
|
||||
|
||||
public virtual HashSet<string> IgnoredPaths { get; set; } = ["/scalar", "/openapi", "/favicon.ico", "/swagger"];
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
namespace SequenceAuth.Lib;
|
||||
|
||||
public record SequenceValidationResult(ValidationOutcome Outcome, Option<string> NextSequence, Option<string> UserId, Option<int> RequestsRemaining);
|
||||
|
||||
public class SequenceManager(ISequenceStore store)
|
||||
{
|
||||
public async Task<SequenceValidationResult> ValidateAndRotateAsync(string currentSequenceId)
|
||||
{
|
||||
var sequenceOpt = await store.GetSequenceAsync(currentSequenceId);
|
||||
|
||||
return sequenceOpt.State switch
|
||||
{
|
||||
OptionState.None => new SequenceValidationResult(ValidationOutcome.SequenceNotFound, Option<string>.None(), Option<string>.None(), Option<int>.None()),
|
||||
OptionState.Some => await ProcessSequenceAsync(currentSequenceId, sequenceOpt.Value!),
|
||||
_ => new SequenceValidationResult(ValidationOutcome.InternalError, Option<string>.None(), Option<string>.None(), Option<int>.None())
|
||||
};
|
||||
}
|
||||
|
||||
private async Task<SequenceValidationResult> ProcessSequenceAsync(string currentSequenceId, SequenceData data)
|
||||
{
|
||||
return data.State switch
|
||||
{
|
||||
SequenceState.Compromised => new SequenceValidationResult(ValidationOutcome.CompromisedSequenceDetected, Option<string>.None(), Option<string>.None(), Option<int>.None()),
|
||||
SequenceState.Rotated => await HandleRotatedSequenceAsync(data.UserId),
|
||||
SequenceState.Active or SequenceState.Initialized => await HandleActiveSequenceAsync(currentSequenceId, data),
|
||||
_ => new SequenceValidationResult(ValidationOutcome.InternalError, Option<string>.None(), Option<string>.None(), Option<int>.None())
|
||||
};
|
||||
}
|
||||
|
||||
private async Task<SequenceValidationResult> HandleRotatedSequenceAsync(string userId)
|
||||
{
|
||||
await store.InvalidateUserSessionsAsync(userId);
|
||||
return new SequenceValidationResult(ValidationOutcome.CompromisedSequenceDetected, Option<string>.None(), Option<string>.None(), Option<int>.None());
|
||||
}
|
||||
|
||||
private async Task<SequenceValidationResult> HandleActiveSequenceAsync(string currentSequenceId, SequenceData data)
|
||||
{
|
||||
var checkLimit = CheckLimit(data.RequestsRemaining);
|
||||
return checkLimit switch
|
||||
{
|
||||
ValidationOutcome.LimitExceeded => new SequenceValidationResult(ValidationOutcome.LimitExceeded, Option<string>.None(), Option<string>.None(), Option<int>.None()),
|
||||
ValidationOutcome.Success => await RotateSequenceAsync(currentSequenceId, data),
|
||||
_ => new SequenceValidationResult(ValidationOutcome.InternalError, Option<string>.None(), Option<string>.None(), Option<int>.None())
|
||||
};
|
||||
}
|
||||
|
||||
private ValidationOutcome CheckLimit(int requestsRemaining)
|
||||
{
|
||||
return requestsRemaining switch
|
||||
{
|
||||
<= 0 => ValidationOutcome.LimitExceeded,
|
||||
> 0 => ValidationOutcome.Success
|
||||
};
|
||||
}
|
||||
|
||||
private async Task<SequenceValidationResult> RotateSequenceAsync(string currentSequenceId, SequenceData data)
|
||||
{
|
||||
var futureSequenceId = Guid.NewGuid().ToString("N");
|
||||
var oldDataRotated = data with { State = SequenceState.Rotated };
|
||||
await store.SaveSequenceAsync(currentSequenceId, oldDataRotated);
|
||||
|
||||
var newData = new SequenceData(
|
||||
UserId: data.UserId,
|
||||
RequestsRemaining: data.RequestsRemaining - 1,
|
||||
State: SequenceState.Active,
|
||||
NextSequenceId: futureSequenceId);
|
||||
|
||||
await store.SaveSequenceAsync(futureSequenceId, newData);
|
||||
|
||||
return new SequenceValidationResult(ValidationOutcome.Success, Option<string>.Some(futureSequenceId), Option<string>.Some(data.UserId), Option<int>.Some(data.RequestsRemaining - 1));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
using Microsoft.AspNetCore.Hosting;
|
||||
using Microsoft.AspNetCore.Mvc.Testing;
|
||||
using Microsoft.AspNetCore.TestHost;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.DependencyInjection.Extensions;
|
||||
using SequenceAuth.Lib;
|
||||
|
||||
namespace SequenceAuth.Example.Tests;
|
||||
|
||||
public class CustomWebApplicationFactory : WebApplicationFactory<Program>
|
||||
{
|
||||
protected override void ConfigureWebHost(IWebHostBuilder builder)
|
||||
{
|
||||
builder.ConfigureTestServices(services =>
|
||||
{
|
||||
services.RemoveAll<ISequenceStore>();
|
||||
services.AddSingleton<ISequenceStore, InMemorySequenceStore>();
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
using System.Collections.Concurrent;
|
||||
using System.Linq;
|
||||
using System.Threading.Tasks;
|
||||
using SequenceAuth.Lib;
|
||||
|
||||
namespace SequenceAuth.Example.Tests;
|
||||
|
||||
public class InMemorySequenceStore : ISequenceStore
|
||||
{
|
||||
private readonly ConcurrentDictionary<string, SequenceData> _store = new();
|
||||
|
||||
public Task<Option<SequenceData>> GetSequenceAsync(string sequenceId)
|
||||
{
|
||||
if (_store.TryGetValue(sequenceId, out var data))
|
||||
{
|
||||
return Task.FromResult(Option<SequenceData>.Some(data));
|
||||
}
|
||||
return Task.FromResult(Option<SequenceData>.None());
|
||||
}
|
||||
|
||||
public Task<StoreOutcome> SaveSequenceAsync(string sequenceId, SequenceData data)
|
||||
{
|
||||
_store[sequenceId] = data;
|
||||
return Task.FromResult(StoreOutcome.Success);
|
||||
}
|
||||
|
||||
public Task<StoreOutcome> InvalidateUserSessionsAsync(string userId)
|
||||
{
|
||||
var keysToRemove = _store.Where(kvp => kvp.Value.UserId == userId).Select(kvp => kvp.Key).ToList();
|
||||
foreach (var key in keysToRemove)
|
||||
{
|
||||
_store.TryRemove(key, out _);
|
||||
}
|
||||
return Task.FromResult(StoreOutcome.Success);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net10.0</TargetFramework>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Nullable>enable</Nullable>
|
||||
<IsPackable>false</IsPackable>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="coverlet.collector" Version="6.0.4" />
|
||||
<PackageReference Include="FluentAssertions" Version="8.10.0" />
|
||||
<PackageReference Include="Microsoft.AspNetCore.Mvc.Testing" Version="10.0.9" />
|
||||
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.14.1" />
|
||||
<PackageReference Include="xunit" Version="2.9.3" />
|
||||
<PackageReference Include="xunit.runner.visualstudio" Version="3.1.4" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<Using Include="Xunit" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\..\example\SequenceAuth.Example.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
@@ -0,0 +1,117 @@
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Net.Http.Json;
|
||||
using System.Threading.Tasks;
|
||||
using FluentAssertions;
|
||||
using SequenceAuth.Lib;
|
||||
using Xunit;
|
||||
|
||||
namespace SequenceAuth.Example.Tests;
|
||||
|
||||
public class SequenceAuthE2ETests : IClassFixture<CustomWebApplicationFactory>
|
||||
{
|
||||
private readonly HttpClient _client;
|
||||
|
||||
public SequenceAuthE2ETests(CustomWebApplicationFactory factory)
|
||||
{
|
||||
_client = factory.CreateClient();
|
||||
}
|
||||
|
||||
private async Task<string> InitSessionAsync()
|
||||
{
|
||||
var loginResponse = await _client.PostAsJsonAsync("/auth/login", new { username = "testuser" });
|
||||
loginResponse.EnsureSuccessStatusCode();
|
||||
|
||||
var token = loginResponse.Headers.GetValues(new SequenceAuthOptions().NextHeaderName).FirstOrDefault();
|
||||
token.Should().NotBeNullOrWhiteSpace();
|
||||
return token!;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task RequestWithoutHeader_ReturnsUnauthorized()
|
||||
{
|
||||
var response = await _client.GetAsync("/secure/get-data");
|
||||
response.StatusCode.Should().Be(HttpStatusCode.Unauthorized);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ValidChain_FollowsSequenceAndSucceeds()
|
||||
{
|
||||
// 1. Init Session
|
||||
var token1 = await InitSessionAsync();
|
||||
|
||||
// 2. First Request
|
||||
var request1 = new HttpRequestMessage(HttpMethod.Get, "/secure/get-data");
|
||||
request1.Headers.Add(new SequenceAuthOptions().AuthHeaderName, token1);
|
||||
var response1 = await _client.SendAsync(request1);
|
||||
|
||||
response1.EnsureSuccessStatusCode();
|
||||
var token2 = response1.Headers.GetValues(new SequenceAuthOptions().NextHeaderName).First();
|
||||
token2.Should().NotBeNullOrWhiteSpace();
|
||||
|
||||
// 3. Second Request with New Token
|
||||
var request2 = new HttpRequestMessage(HttpMethod.Get, "/secure/get-data");
|
||||
request2.Headers.Add(new SequenceAuthOptions().AuthHeaderName, token2);
|
||||
var response2 = await _client.SendAsync(request2);
|
||||
|
||||
response2.EnsureSuccessStatusCode();
|
||||
var token3 = response2.Headers.GetValues(new SequenceAuthOptions().NextHeaderName).First();
|
||||
token3.Should().NotBeNullOrWhiteSpace();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AttackerReplaysToken_CompromisesSequence()
|
||||
{
|
||||
var token1 = await InitSessionAsync();
|
||||
System.Console.WriteLine($"Token 1: {token1}");
|
||||
|
||||
var userRequest1 = new HttpRequestMessage(HttpMethod.Get, "/secure/get-data");
|
||||
userRequest1.Headers.Add(new SequenceAuthOptions().AuthHeaderName, token1);
|
||||
var userResponse1 = await _client.SendAsync(userRequest1);
|
||||
userResponse1.EnsureSuccessStatusCode();
|
||||
var token2 = userResponse1.Headers.GetValues(new SequenceAuthOptions().NextHeaderName).First();
|
||||
System.Console.WriteLine($"Token 2: {token2}");
|
||||
|
||||
var attackerRequest = new HttpRequestMessage(HttpMethod.Get, "/secure/get-data");
|
||||
attackerRequest.Headers.Add(new SequenceAuthOptions().AuthHeaderName, token1);
|
||||
var attackerResponse = await _client.SendAsync(attackerRequest);
|
||||
System.Console.WriteLine($"Attacker Response: {attackerResponse.StatusCode}");
|
||||
var attackerBody = await attackerResponse.Content.ReadAsStringAsync();
|
||||
System.Console.WriteLine($"Attacker Body: {attackerBody}");
|
||||
|
||||
attackerResponse.StatusCode.Should().Be(HttpStatusCode.Unauthorized);
|
||||
|
||||
var userRequest2 = new HttpRequestMessage(HttpMethod.Get, "/secure/get-data");
|
||||
userRequest2.Headers.Add(new SequenceAuthOptions().AuthHeaderName, token2);
|
||||
var userResponse2 = await _client.SendAsync(userRequest2);
|
||||
|
||||
userResponse2.StatusCode.Should().Be(HttpStatusCode.Unauthorized);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AttackerStrikesFirst_CompromisesSequence()
|
||||
{
|
||||
var token1 = await InitSessionAsync();
|
||||
|
||||
var attackerRequest1 = new HttpRequestMessage(HttpMethod.Get, "/secure/get-data");
|
||||
attackerRequest1.Headers.Add(new SequenceAuthOptions().AuthHeaderName, token1);
|
||||
var attackerResponse1 = await _client.SendAsync(attackerRequest1);
|
||||
|
||||
attackerResponse1.EnsureSuccessStatusCode();
|
||||
var token2 = attackerResponse1.Headers.GetValues(new SequenceAuthOptions().NextHeaderName).First();
|
||||
|
||||
var userRequest1 = new HttpRequestMessage(HttpMethod.Get, "/secure/get-data");
|
||||
userRequest1.Headers.Add(new SequenceAuthOptions().AuthHeaderName, token1);
|
||||
var userResponse1 = await _client.SendAsync(userRequest1);
|
||||
|
||||
System.Console.WriteLine($"User Response 1: {userResponse1.StatusCode}");
|
||||
userResponse1.StatusCode.Should().Be(HttpStatusCode.Unauthorized);
|
||||
|
||||
var attackerRequest2 = new HttpRequestMessage(HttpMethod.Get, "/secure/get-data");
|
||||
attackerRequest2.Headers.Add(new SequenceAuthOptions().AuthHeaderName, token2);
|
||||
var attackerResponse2 = await _client.SendAsync(attackerRequest2);
|
||||
|
||||
attackerResponse2.StatusCode.Should().Be(HttpStatusCode.Unauthorized);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net10.0</TargetFramework>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Nullable>enable</Nullable>
|
||||
<IsPackable>false</IsPackable>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="coverlet.collector" Version="6.0.4" />
|
||||
<PackageReference Include="FluentAssertions" Version="8.10.0" />
|
||||
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.14.1" />
|
||||
<PackageReference Include="Moq" Version="4.20.72" />
|
||||
<PackageReference Include="xunit" Version="2.9.3" />
|
||||
<PackageReference Include="xunit.runner.visualstudio" Version="3.1.4" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<Using Include="Xunit" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\..\lib\SequenceAuth.Lib.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
@@ -0,0 +1,88 @@
|
||||
using FluentAssertions;
|
||||
using Moq;
|
||||
using SequenceAuth.Lib;
|
||||
using System.Threading.Tasks;
|
||||
using Xunit;
|
||||
|
||||
namespace SequenceAuth.Lib.Tests;
|
||||
|
||||
public class SequenceManagerTests
|
||||
{
|
||||
private readonly Mock<ISequenceStore> _mockStore;
|
||||
private readonly SequenceManager _manager;
|
||||
|
||||
public SequenceManagerTests()
|
||||
{
|
||||
_mockStore = new Mock<ISequenceStore>();
|
||||
_manager = new SequenceManager(_mockStore.Object);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ValidateAndRotateAsync_ValidToken_ReturnsSuccessAndGeneratesNewToken()
|
||||
{
|
||||
// Arrange
|
||||
var token = "valid-token";
|
||||
var nextToken = "pre-generated-next-token";
|
||||
var sequenceData = new SequenceData("user123", 100, SequenceState.Active, nextToken);
|
||||
|
||||
_mockStore.Setup(s => s.GetSequenceAsync(token))
|
||||
.ReturnsAsync(Option<SequenceData>.Some(sequenceData));
|
||||
|
||||
_mockStore.Setup(s => s.SaveSequenceAsync(It.IsAny<string>(), It.IsAny<SequenceData>()))
|
||||
.ReturnsAsync(StoreOutcome.Success);
|
||||
|
||||
// Act
|
||||
var result = await _manager.ValidateAndRotateAsync(token);
|
||||
|
||||
// Assert
|
||||
result.Outcome.Should().Be(ValidationOutcome.Success);
|
||||
result.NextSequence.State.Should().Be(OptionState.Some);
|
||||
result.NextSequence.Value.Should().Be(nextToken);
|
||||
|
||||
// Ensure the old sequence was marked as Rotated
|
||||
_mockStore.Verify(s => s.SaveSequenceAsync(token, It.Is<SequenceData>(d =>
|
||||
d.State == SequenceState.Rotated)), Times.Once);
|
||||
|
||||
// Ensure the new sequence was saved
|
||||
_mockStore.Verify(s => s.SaveSequenceAsync(nextToken, It.Is<SequenceData>(d =>
|
||||
d.State == SequenceState.Active)), Times.Once);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ValidateAndRotateAsync_RotatedToken_ReturnsCompromisedAndDestroysSession()
|
||||
{
|
||||
// Arrange
|
||||
var token = "compromised-token";
|
||||
var sequenceData = new SequenceData("user123", 100, SequenceState.Rotated, "some-next-token");
|
||||
|
||||
_mockStore.Setup(s => s.GetSequenceAsync(token))
|
||||
.ReturnsAsync(Option<SequenceData>.Some(sequenceData));
|
||||
|
||||
// Act
|
||||
var result = await _manager.ValidateAndRotateAsync(token);
|
||||
|
||||
// Assert
|
||||
result.Outcome.Should().Be(ValidationOutcome.CompromisedSequenceDetected);
|
||||
result.NextSequence.State.Should().Be(OptionState.None);
|
||||
|
||||
// Ensure InvalidateUserSessionsAsync was called for the user
|
||||
_mockStore.Verify(s => s.InvalidateUserSessionsAsync("user123"), Times.Once);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ValidateAndRotateAsync_MissingToken_ReturnsNotFound()
|
||||
{
|
||||
// Arrange
|
||||
var token = "invalid-token";
|
||||
|
||||
_mockStore.Setup(s => s.GetSequenceAsync(token))
|
||||
.ReturnsAsync(Option<SequenceData>.None());
|
||||
|
||||
// Act
|
||||
var result = await _manager.ValidateAndRotateAsync(token);
|
||||
|
||||
// Assert
|
||||
result.Outcome.Should().Be(ValidationOutcome.SequenceNotFound);
|
||||
result.NextSequence.State.Should().Be(OptionState.None);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user