c# - 无法在启动类中注入(inject)IAntiforgery

需要使用IAntiforgery进行csrf保护。只是想注入(inject)服务。这样做时,我收到“在尝试激活‘API.Startup’时无法解析‘Microsoft.AspNetCore.Antiforgery.IAntiforgery’类型的服务”。错误。我在这里发布代码。希望社区能够在这里帮助我。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using APi.Models;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.EntityFrameworkCore;
using Microsoft.AspNetCore.Antiforgery;
using Microsoft.AspNetCore.Razor.TagHelpers;

 

namespace APi
{
    public class Startup
    {
        IAntiforgery _antiforgery;
        public Startup(IConfiguration configuration,IAntiforgery antiforgery)
        {
            Configuration = configuration;
            _antiforgery = antiforgery;
        }

 

        public IConfiguration Configuration { get; }

 

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllersWithViews();
            services.AddTransient<IAntiforgery>();
            services.AddDbContext<EmployeeContext>(options => 
            options.UseSqlServer(Configuration.GetConnectionString("SQLServerConnection")));
        }

 

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }
            app.UseHttpsRedirection();
            app.UseStaticFiles();

 

            app.UseRouting();

 

            app.UseAuthorization();

 

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

最佳答案

游戏晚了,但这是您在 6.0 中的做法。我已经确认这有效。好消息是,如果愿意,您仍然可以在 Startup 中使用 Configure 构造函数,插入 IAntiforgery 接口(interface)。与5.0不同的是,IAntiforgery接口(interface)不在DI中,需要从服务集合中获取。

注意:如果您使用的是 ControllersWithViews,则不需要

services.AddAntiforgery(options => { options.HeaderName = "X-XSRF-TOKEN"; options.Cookie.HttpOnly = false; });

因为它是自动添加的。但这允许我们控制 header 名称。他们需要匹配客户端和服务器端。

程序.cs

var services = builder.Services;
// Add services to the container.
services.AddAntiforgery(options => { options.HeaderName = "X-XSRF-TOKEN"; options.Cookie.HttpOnly = false; })
services.AddControllersWithViews();
var startup = new Startup(builder.Configuration);
var antiforgery = app.Services.GetRequiredService<IAntiforgery>();
startup.ConfigureServices(builder.Services);
builder.Services.AddAntiforgery(options => { options.HeaderName = "X-XSRF-TOKEN"; options.Cookie.HttpOnly = false; });
var app = builder.Build();
var antiforgery = app.Services.GetRequiredService<IAntiforgery>();
startup.Configure(app, app.Environment,antiforgery);
app.Run();

启动.cs

public void Configure(IApplicationBuilder app, IWebHostEnvironment env, 
   IAntiforgery antiforgery)
   {
     app.Use((context, next) =>
     {
         var requestPath = context.Request.Path.Value;

        if (string.Equals(requestPath, "/auth", StringComparison.OrdinalIgnoreCase))
        {
            var tokenSet = antiforgery.GetAndStoreTokens(context);        
            context.Response.Cookies.Append("XSRF-TOKEN", tokenSet.RequestToken!,
            new CookieOptions { HttpOnly = false });
        }

        return next(context);
      });

https://stackoverflow.com/questions/64373149/

相关文章:

asp.net-core - 我可以在 AspNetCore WebAPI 中将 Cancellat

javascript - 在输入焦点上移动/动画占位符

reactjs - 在 useEffect Hook 中使用 axios 取消 token 时如何修

reactjs - Chrome,Edge - 禁用字段的自动填充/自动完成

html - 使一个 div 填充具有未指定尺寸的表格单元格的整个宽度和高度

reactjs - typescript 错误对象的类型为 'unknown'

python - 'google-api-python-client' distribution 在

javascript - 错误 : Jmeter: Typed variable declarati

angular - 如何限制 NgSelect 下拉面板中显示的项目数?

python - 我试图将 python 文件转换为 exe 文件,但它不起作用