.Net 8.0 всегда возвращает 403C#

Место общения программистов C#
Ответить
Anonymous
 .Net 8.0 всегда возвращает 403

Сообщение Anonymous »

Я разрабатываю веб -сайт на .net 8.0. В моей Visual Studio IIS нет проблем (я имею в виду свою местную среду разработки), но когда я публикую свой веб-сайт (чтобы опубликовать свой веб-сайт, я следую по этому пути: Publish-> Folder-> Framework-зависимый и X64-> публиковать) на хостинг-сервере нет проблем. Через некоторое время (10-20 секунд) мой веб-сайт выходит за меня (он возвращает 403). Я не могу понять проблему. Я также добавил ключи защиты данных (вы можете проверить мой предыдущий вопрос: ASP.NET CORE Identity Cookie Issuee) Это работало для моего предыдущего веб -сайта, но на этот раз он не работает. Я всегда получаю HTTP 403, когда развертываю свой веб -сайт на хостинг -сервере. Не могли бы вы мне помочь?
my программа.using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using ORCA_Product.Data;
using ORCA_Product.Services;
using Microsoft.AspNetCore.Identity.UI.Services;
using Microsoft.AspNetCore.DataProtection;
using Microsoft.AspNetCore.DataProtection.Repositories;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddScoped();

builder.Services.AddDataProtection()
.AddKeyManagementOptions(options =>
{
options.XmlRepository = builder.Services.BuildServiceProvider()
.GetRequiredService();
})
.SetApplicationName("ORCA_Product");

// Register Data Protection Repository separately
builder.Services.AddScoped();

// Logging configuration - ensure all log levels are visible
builder.Logging.ClearProviders();
builder.Logging.AddConsole();
builder.Logging.AddDebug();
builder.Logging.SetMinimumLevel(LogLevel.Information);

// Add services to the container.
var connectionString = builder.Configuration.GetConnectionString("DefaultConnection") ?? throw new InvalidOperationException("Connection string 'DefaultConnection' not found.");
builder.Services.AddDbContext(options =>
options.UseSqlServer(connectionString, sqlServerOptionsAction: sqlOptions =>
{
sqlOptions.CommandTimeout(300); // 5 minutes timeout
}));
builder.Services.AddDatabaseDeveloperPageExceptionFilter();

builder.Services.AddDefaultIdentity(options =>
{
options.SignIn.RequireConfirmedAccount = true;
options.SignIn.RequireConfirmedEmail = true;

// 2FA settings - Email based
options.Tokens.ProviderMap.Add("Email", new TokenProviderDescriptor(typeof(IUserTwoFactorTokenProvider)));
options.Tokens.AuthenticatorTokenProvider = "Email";

// Password settings
options.Password.RequireDigit = true;
options.Password.RequireLowercase = true;
options.Password.RequireNonAlphanumeric = true;
options.Password.RequireUppercase = true;
options.Password.RequiredLength = 6;
options.Password.RequiredUniqueChars = 1;
})
.AddRoles()
.AddEntityFrameworkStores();

builder.Services.AddControllersWithViews();

// For email service
builder.Services.AddTransient();

// Form options limit settings
builder.Services.Configure(options =>
{
options.MultipartBodyLengthLimit = 500 * 1024 * 1024; // 500MB
options.ValueLengthLimit = int.MaxValue;
options.MultipartHeadersLengthLimit = int.MaxValue;
});

builder.Services.AddSignalR();
builder.Services.ConfigureApplicationCookie(options =>
{
options.Cookie.HttpOnly = true;
options.Cookie.SecurePolicy = CookieSecurePolicy.Always; // HTTPS only
options.Cookie.SameSite = SameSiteMode.Strict; // CSRF protection
options.SlidingExpiration = false; // Don't extend session automatically
options.ExpireTimeSpan = TimeSpan.FromMinutes(10); // 10 minutes max session
options.Events.OnRedirectToLogin = (context) =>
{
context.Response.StatusCode = 401;
return Task.CompletedTask;
};
});

var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseMigrationsEndPoint();
}
else
{
app.UseExceptionHandler("/Home/Error");
app.UseHsts();
}

app.UseHttpsRedirection();
app.UseStaticFiles();

app.UseRouting();

app.UseAuthentication(); // This line is also required
app.UseAuthorization();

app.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
app.MapRazorPages();

app.MapHub("/progressHub");

// Rolleri ve ilk admin kullan c s n olu tur
using (var scope = app.Services.CreateScope())
{
var services = scope.ServiceProvider;
var roleManager = services.GetRequiredService();
var userManager = services.GetRequiredService();

string[] roles = new[] { "Admin", "Customer" };

foreach (var role in roles)
{
if (!await roleManager.RoleExistsAsync(role))
{
await roleManager.CreateAsync(new IdentityRole(role));
}
}

// lk admin kullan c
var adminEmail = "extremlysecretemail@secret.com"; // New admin email
var adminPassword = "extremlysecretpassword";

if (await userManager.FindByEmailAsync(adminEmail) == null)
{
var adminUser = new IdentityUser { UserName = adminEmail, Email = adminEmail, EmailConfirmed = true };
var result = await userManager.CreateAsync(adminUser, adminPassword);
if (result.Succeeded)
{
await userManager.AddToRoleAsync(adminUser, "Admin");

// Enable 2FA
await userManager.SetTwoFactorEnabledAsync(adminUser, true);
}
}
}

app.Run();

my dbdataprotectionrepository.cs :
using Microsoft.AspNetCore.DataProtection.Repositories;
using ORCA_Product.Data;
using ORCA_Product.Models;
using System.Xml.Linq;

namespace ORCA_Product.Services
{
public class DbDataProtectionRepository : IXmlRepository
{
private readonly ApplicationDbContext _context;

public DbDataProtectionRepository(ApplicationDbContext context)
{
_context = context;
}

public IReadOnlyCollection GetAllElements()
{
try
{
var keys = _context.DataProtectionKeys
.Where(k => k.ExpirationDate == null || k.ExpirationDate > DateTime.UtcNow)
.ToList();
return keys.Select(k => XElement.Parse(k.XmlData)).ToList();
}
catch (Exception ex)
{
// Log hatası ve boş liste döndür
Console.WriteLine($"Data Protection Key okuma hatası: {ex.Message}");
return new List();
}
}

public void StoreElement(XElement element, string friendlyName)
{
try
{
// Mevcut key'i kontrol et ve güncelle
var existingKey = _context.DataProtectionKeys.FirstOrDefault(k => k.Id == friendlyName);

if (existingKey != null)
{
existingKey.XmlData = element.ToString();
existingKey.ActivationDate = DateTime.UtcNow;
existingKey.ExpirationDate = DateTime.UtcNow.AddDays(90);
}
else
{
var key = new DataProtectionKey
{
Id = friendlyName,
XmlData = element.ToString(),
CreationDate = DateTime.UtcNow,
ActivationDate = DateTime.UtcNow,
ExpirationDate = DateTime.UtcNow.AddDays(90)
};
_context.DataProtectionKeys.Add(key);
}

_context.SaveChanges();
}
catch (Exception ex)
{
// Log hatası
Console.WriteLine($"Data Protection Key kaydetme hatası: {ex.Message}");
throw; // Hatayı yukarı fırlat
}
}
}
}

my DataProtectionKey.cs :
using System.ComponentModel.DataAnnotations;

namespace ORCA_Product.Models
{
public class DataProtectionKey
{
[Key]
public string Id { get; set; } = string.Empty;
public string XmlData { get; set; } = string.Empty;
public DateTime CreationDate { get; set; }
public DateTime? ActivationDate { get; set; }
public DateTime? ExpirationDate { get; set; }
}
}

my applicationdbcontext.cs :
using ORCA_Product.Models;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;

namespace ORCA_Product.Data
{
public class ApplicationDbContext : IdentityDbContext
{
public ApplicationDbContext(DbContextOptions options)
: base(options)
{
}

public DbSet LeakDatas { get; set; }
public DbSet RequestedDomains { get; set; }
public DbSet UserDomainAccesses { get; set; }
public DbSet CorporateEmails { get; set; }
public DbSet UserCorporateEmailAccesses { get; set; }
public DbSet DataProtectionKeys { get; set; }

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);

modelBuilder.Entity(entity =>
{
entity.HasKey(e => e.Id);
entity.Property(e => e.XmlData).IsRequired();
});
}
}
}


Подробнее здесь: https://stackoverflow.com/questions/797 ... eturns-403
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «C#»