builder.Services.AddAuthentication("Bearer").AddJwtBearer(options =>
{
string? audience = builder.Configuration["Jwt-Options:Audience"];
string? secretKey = builder.Configuration["Jwt-Options:SecretKey"];
if (audience == null || secretKey == null) throw new NullReferenceException("Jwt-Options required");
options.TokenValidationParameters = new TokenValidationParameters()
{
ClockSkew = TimeSpan.Zero,
RequireExpirationTime = true,
ValidateIssuer = false,
ValidateAudience = true,
ValidateLifetime = true,
ValidAudience = audience,
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(secretKey))
};
options.Events = new JwtBearerEvents()
{
OnMessageReceived = async (context) =>
{
context.Token = context.Request.Cookies["access-token"];
await Task.CompletedTask;
}
};
});
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<CodeSnippet>()
.HasMany(cs => cs.LikedByUsers)
.WithMany(u => u.LikedCodeSnippets);
modelBuilder.Entity<User>()
.HasMany(u => u.CodeSnippets)
.WithOne(u => u.User).HasForeignKey(cs => cs.UserId)
.OnDelete(DeleteBehavior.SetNull);
}
public class CodeSnippet
{
public int Id { get; set; }
public int? UserId { get; set; }
public User? User { get; set; }
public required string Title { get; set; }
public required string Description { get; set; }
public required string Content { get; set; }
public required string Tag { get; set; }
public List<User> LikedByUsers { get; set; } = new List<User>();
}