Quantcast
Channel: Active questions tagged blazor - Stack Overflow
Viewing all articles
Browse latest Browse all 4839

Can't disable antiforgery for endpoints

$
0
0

I have a trusted server that should be able to send a post request with HMAC and an id of the user to my server (both servers have the same db with same users), so that user doesn't have to log in again. I have antiforgery middleware (it is extremely needed for security), that should work in the Blazor part of the application but not the API and Controllers. I have tried many solutions, none worked.

Solutions that I have tried:

Disabling antiforgery via program.cs:

app.MapControllers().DisableAntiforgery();services.AddAntiforgery(options =>    {        options.HeaderName = "X-CSRF-TOKEN";    });app.Use(async (context, next) =>            {                var path = context.Request.Path.Value?.ToLowerInvariant() ?? "";                if (path.Contains("/account/loginviatrustedserver"))                {                    await next();                    return;                }                var antiforgery = context.RequestServices.GetRequiredService<IAntiforgery>();                if (HttpMethods.IsPost(context.Request.Method) ||                    HttpMethods.IsPut(context.Request.Method) ||                    HttpMethods.IsDelete(context.Request.Method) ||                    HttpMethods.IsPatch(context.Request.Method))                {                    await antiforgery.ValidateRequestAsync(context);                }                await next();            });

Disabling antiforgery in Minimal API endpoints:

endpoints.MapPost(logic)..DisableAntiforgery()            .WithMetadata(new IgnoreAntiforgeryTokenAttribute());

Rewriting this particular endpoint to a controller and adding attributes:

[ApiController][Route("Account/[action]")][IgnoreAntiforgeryToken][AllowAnonymous]public partial class AccountController(){    [IgnoreAntiforgeryToken]    public async Task<IActionResult> LoginViaTrustedServer()    { }}

None of these approaches worked and I still get the error:

A valid antiforgery token was not provided with the request. Add an antiforgery token, or disable antiforgery validation for this endpoint.

My program.cs:

var builder = WebApplication.CreateBuilder(args);builder.Services    .AddBlazorComponents()    .AddUiLibraries()    .AddDatabase(builder.Configuration)    .AddAuth(builder.Configuration)    .AddApplicationServices()    .AddRadzenConfiguration();var app = builder.Build();app.ConfigurePipeline();app.Run();
public static class WebApplicationExtensions{    public static WebApplication ConfigurePipeline(this WebApplication app)    {        var forwardingOptions = new ForwardedHeadersOptions()        {            ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto        };        forwardingOptions.KnownIPNetworks.Clear();        forwardingOptions.KnownProxies.Clear();        app.UseForwardedHeaders(forwardingOptions);        // 2. Exception Handling и HSTS        if (!app.Environment.IsDevelopment())        {            app.UseExceptionHandler("/Error", createScopeForErrors: true);            app.UseHsts();        }        app.UseStatusCodePagesWithReExecute("/not-found");        app.UseHttpsRedirection();        app.MapStaticAssets();        app.UseRouting();        // 6. Localization (после routing, до authentication)        app.UseRequestLocalization(options =>             options.AddSupportedCultures("ky", "ru")                .AddSupportedUICultures("ky", "ru")                .SetDefaultCulture("ky")        );        // 7. Authentication & Authorization        app.UseAuthentication();        app.UseAuthorization();        app.UseAntiforgery();        // 9. Endpoints        app.MapRiaLoginEndpoint();        app.MapRazorComponents<App>().AddInteractiveServerRenderMode();        app.MapControllers();        return app;    }}
public static class ServiceExtensions{        public static IServiceCollection AddBlazorComponents(this IServiceCollection services)        {            services.AddRazorComponents()                    .AddInteractiveServerComponents()                    .AddHubOptions(options => options.MaximumReceiveMessageSize = 10 * 1024 * 1024);            services.AddCascadingAuthenticationState();            return services;        }        public static IServiceCollection AddDatabase(this IServiceCollection services, IConfiguration configuration)        {            services.Configure<DatabaseSettings>(configuration.GetSection("DatabaseSettings"));            var dbSettings = configuration.GetSection("DatabaseSettings").Get<DatabaseSettings>();            var connectionStringKey = dbSettings?.UseTestDb == true                 ? "TestConnection"                 : "ProductionConnection";            services.AddDbContextFactory<calimContext>(options =>                 options.UseSqlServer(configuration.GetConnectionString(connectionStringKey)));            return services;        }        public static IServiceCollection AddAuth(this IServiceCollection services, IConfiguration config)        {            services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme).AddCookie(options =>            {                options.LoginPath =  "/login";                options.LogoutPath = "/logout";                options.ExpireTimeSpan = TimeSpan.FromDays(1);                options.AccessDeniedPath = "/access-denied";                options.SlidingExpiration = true;                options.Cookie.HttpOnly = true;                options.Cookie.SecurePolicy = CookieSecurePolicy.Always;                options.Cookie.SameSite = SameSiteMode.Lax;            });            services.AddOptions<AuthSettings>()                .BindConfiguration("AuthSettings")                .Validate(x => !string.IsNullOrWhiteSpace(x.SharedSecretBase64), "SharedSecretBase64 is required")                .Validate(x =>                {                    try                    {                        x.SharedSecret = Convert.FromBase64String(x.SharedSecretBase64);                        return true;                    }                    catch                    {                        return false;                    }                }, "SharedSecretBase64 must be valid Base64")                .ValidateOnStart();            services.AddAuthorization();            services.AddHttpContextAccessor();            services.AddScoped<AuthService>();            return services;        }        public static IServiceCollection AddApplicationServices(this IServiceCollection services)        {            services.AddControllers(options =>            {                options.Filters.Clear();            });            services.AddHttpClient();            services.AddLocalization();            services.AddScoped<calimService>();            return services;        }        public static IServiceCollection AddRadzenConfiguration(this IServiceCollection services)        {            services.AddRadzenComponents();            services.AddRadzenCookieThemeService(options =>            {                options.Name = "gg";                options.Duration = TimeSpan.FromDays(365);            });            return services;        }        public static IServiceCollection AddUiLibraries(this IServiceCollection services)        {            services.AddMudServices();            return services;        }}

Viewing all articles
Browse latest Browse all 4839

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>