【问题标题】:How to add a custom HttpContextAccessor to service ASP.NET Core如何添加自定义 HttpContextAccessor 以服务 ASP.NET Core
【发布时间】:2021-04-01 15:19:02
【问题描述】:

我想在 asp.net core 中添加自定义 HttpContextAccessor 服务,

这是正确的方法吗:

在 ConfigureService 方法中:

var env = services.BuildServiceProvider().GetRequiredService<Microsoft.AspNetCore.Hosting.IHostingEnvironment>();

然后添加海关声明(这些将由 anther 类提取)。

 if(env.IsDevelopment())
 {
   var claims = new List<Claim>();
   claims.Add(new Claim(ClaimTypes.Name, "test"));
   claims.Add(new Claim(ClaimTypes.Role, "Operator"));
   claims.Add(new Claim("http://schemas.microsoft.com/identity/claims/objectidentifier", "af4ab79d-f75c-44be-b8dd-test"));
   claims.Add(new Claim("CompanyName", "test"));

  services.AddSingleton<IHttpContextAccessor>(sp => new DefaultHttpContext()
  {
    User = new ClaimsPrincipal(new ClaimsIdentity(claims)),
  });

 }

这样,IHttpContextAccessorDefaultHttpContext 的类型不匹配,有没有办法解决这个问题或如何正确解决?

【问题讨论】:

  • 你的场景是什么?其实我认为你需要在中间件中添加对 httpcontext 用户的声明。
  • 我该怎么做?好吧,我的情况是我有一个 API 通过 Azure AD 进行授权,对于开发环境,我喜欢有一个硬编码的用户,因为我在其他类中使用 IHttpContextAccessor 来提取用户声明/

标签: c# asp.net-core httpcontext


【解决方案1】:

你能试试这个方法吗?我在集成测试中使用它来通过身份验证,因此我认为它可能适用于您的场景。

public class TestAuthenticationHandler : AuthenticationHandler<AuthenticationSchemeOptions>
{
    public TestAuthenticationHandler(
        IOptionsMonitor<AuthenticationSchemeOptions> options,
        ILoggerFactory logger, UrlEncoder encoder, ISystemClock clock)
        : base(options, logger, encoder, clock)
    {
    }

    protected override Task<AuthenticateResult> HandleAuthenticateAsync()
    {
        var claims = new[]
        {
            new Claim(JwtClaimTypes.Subject, MasterData.CurrentUserId),
            new Claim(JwtClaimTypes.Name, "test@gmail.com"),
            new Claim(JwtClaimTypes.Email, "test@gmail.com"),
            new Claim(JwtClaimTypes.Role, "Admin"),
        };
        var identity = new ClaimsIdentity(claims, "Test");
        var principal = new ClaimsPrincipal(identity);
        var ticket = new AuthenticationTicket(principal, "Test");

        var result = AuthenticateResult.Success(ticket);

        return Task.FromResult(result);
    }
}

在 StartUp 中注册 Handler。

services.AddAuthentication("Test")
                            .AddScheme<AuthenticationSchemeOptions, TestAuthenticationHandler>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-20
    • 1970-01-01
    相关资源
    最近更新 更多