【问题标题】:Where to set custom ClaimsPrincipal for all HttpRequests在哪里为所有 HttpRequests 设置自定义 ClaimsPrincipal
【发布时间】:2019-03-25 11:43:23
【问题描述】:

我正在将旧应用程序移植到 ASP.NET Core,它使用 Windows 身份验证(在 IIS 中配置,resp.launchsetting.json)。

在开发模式下运行时,我想覆盖身份验证以使用自定义硬编码 ClaimsPrincipal。

public class Startup
{
   public void Configure(IApplicationBuilder app, IHostingEnvironment env)
   {

       if (env.IsDevelopment())
       {
           app.UseDeveloperExceptionPage();
       }
       app.UseMvc();    
   }
}

我不确定设置身份和服务/中间件配置以使用的正确位置...

【问题讨论】:

  • 看看现有的thread
  • 我应该只使用 ClaimsTranformer 即使我有未经身份验证的请求并且我想让它们经过身份验证?我认为 ClaimsTransformer 旨在从现有身份中添加/删除声明

标签: c# authentication asp.net-core


【解决方案1】:

创建中间件集HttpContext.User 到硬编码ClaimsPrincipal

public class WindowsUserMiddleware
{
    private readonly RequestDelegate _next;

    public WindowsUserMiddleware(RequestDelegate next)
    {
        _next = next;
    }

    public async Task InvokeAsync(HttpContext httpContext)
    {
        var claims = new List<Claim> { /* add claims */ };
        var userIdentity = new ClaimsIdentity(claims, "NonEmptyAuthType");

        httpContext.User = new ClaimsPrincipal(userIdentity);

        await _next(httpContext);
    }
}

public static class WindowsUserMiddlewareExtensions
{
    public static IApplicationBuilder UseWindowsUser(this IApplicationBuilder applicationBuilder)
    {
        return applicationBuilder.UseMiddleware<WindowsUserMiddleware>();
    }

}

并且只在开发模式下使用它

if (env.IsDevelopment())
{
    app.UseWindowsUser();
    app.UseDeveloperExceptionPage();
}
app.UseMvc();   

【讨论】:

    猜你喜欢
    • 2013-11-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-26
    • 2015-07-25
    • 1970-01-01
    • 1970-01-01
    • 2013-08-23
    相关资源
    最近更新 更多