gpt4 book ai didi

asp.net-core - 使用 .Net Core 中经过 Windows 身份验证的应用程序从 SQL 填充自定义声明

转载 作者:行者123 更新时间:2023-12-02 20:56:02 26 4
gpt4 key购买 nike

场景 - Active Directory 中的 .Net Core Intranet 应用程序使用 SQL Server 管理应用程序特定权限和扩展用户身份。

迄今为止的成功 - 用户已通过身份验证并且 Windows 声明可用(名称和组)。 Identity.Name 可用于从具有扩展属性的数据库中返回域用户模型。

问题和疑问 - 然后我尝试填充一个自定义声明属性“Id”,并通过 ClaimsPrincipal 使其在全局范围内可用。迄今为止,我已经研究过 ClaimsTransformation,但没有取得多大成功。在我读到的其他文章中,您必须在登录之前添加声明,但这真的是真的吗?这意味着完全依赖 AD 来履行所有 claim ,真的是这样吗?

下面是我此时在 HomeController 中的简单代码。我正在访问数据库,然后尝试填充 ClaimsPrincipal,然后返回域用户模型。我认为这可能是我的问题所在,但我是 .net 中授权的新手,并且正在努力解决 claim 问题。

非常感谢收到的所有帮助

当前代码:

public IActionResult Index()
{
var user = GetExtendedUserDetails();
User.Claims.ToList();
return View(user);
}

private Models.User GetExtendedUserDetails()
{
var user = _context.User.SingleOrDefault(m => m.Username == User.Identity.Name.Remove(0, 6));
var claims = new List<Claim>();

claims.Add(new Claim("Id", Convert.ToString(user.Id), ClaimValueTypes.String));
var userIdentity = new ClaimsIdentity("Intranet");
userIdentity.AddClaims(claims);
var userPrincipal = new ClaimsPrincipal(userIdentity);

return user;
}

更新:

我已经注册了ClaimsTransformation

app.UseClaimsTransformation(o => new ClaimsTransformer().TransformAsync(o));

并根据此 github 查询构建如下所示的 ClaimsTransformer

https://github.com/aspnet/Security/issues/863

public class ClaimsTransformer : IClaimsTransformer
{
private readonly TimesheetContext _context;
public async Task<ClaimsPrincipal> TransformAsync(ClaimsTransformationContext context)
{

System.Security.Principal.WindowsIdentity windowsIdentity = null;

foreach (var i in context.Principal.Identities)
{
//windows token
if (i.GetType() == typeof(System.Security.Principal.WindowsIdentity))
{
windowsIdentity = (System.Security.Principal.WindowsIdentity)i;
}
}

if (windowsIdentity != null)
{
//find user in database
var username = windowsIdentity.Name.Remove(0, 6);
var appUser = _context.User.FirstOrDefaultAsync(m => m.Username == username);

if (appUser != null)
{

((ClaimsIdentity)context.Principal.Identity).AddClaim(new Claim("Id", Convert.ToString(appUser.Id)));

/*//add all claims from security profile
foreach (var p in appUser.Id)
{
((ClaimsIdentity)context.Principal.Identity).AddClaim(new Claim(p.Permission, "true"));
}*/

}

}
return await System.Threading.Tasks.Task.FromResult(context.Principal);
}
}

但是我得到 NullReferenceException: Object reference not set to an instance of an object 错误,尽管之前已经返回了域模型。

使用 STARTUP.CS

using System;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Birch.Intranet.Models;
using Microsoft.EntityFrameworkCore;

namespace Birch.Intranet
{
public class Startup
{
public Startup(IHostingEnvironment env)
{
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
.AddEnvironmentVariables();
Configuration = builder.Build();
}

public IConfigurationRoot Configuration { get; }

// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddAuthorization();

// Add framework services.
services.AddMvc();
// Add database
var connection = @"Data Source=****;Initial Catalog=Timesheet;Integrated Security=True;Encrypt=False;TrustServerCertificate=True;ApplicationIntent=ReadWrite;MultiSubnetFailover=False";
services.AddDbContext<TimesheetContext>(options => options.UseSqlServer(connection));

// Add session
services.AddSession(options => {
options.IdleTimeout = TimeSpan.FromMinutes(60);
options.CookieName = ".Intranet";
});
}

// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();

if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseBrowserLink();
}
else
{
app.UseExceptionHandler("/Home/Error");
}

app.UseClaimsTransformation(o => new ClaimsTransformer().TransformAsync(o));

app.UseSession();
app.UseDefaultFiles();
app.UseStaticFiles();

app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
}
}

最佳答案

您需要使用带有依赖注入(inject)的IClaimsTransformer

    app.UseClaimsTransformation(async (context) =>
{
IClaimsTransformer transformer = context.Context.RequestServices.GetRequiredService<IClaimsTransformer>();
return await transformer.TransformAsync(context);
});

// Register
services.AddScoped<IClaimsTransformer, ClaimsTransformer>();

并且需要在ClaimsTransformer中注入(inject)DbContext

public class ClaimsTransformer : IClaimsTransformer
{
private readonly TimesheetContext _context;
public ClaimsTransformer(TimesheetContext dbContext)
{
_context = dbContext;
}
// ....
}

关于asp.net-core - 使用 .Net Core 中经过 Windows 身份验证的应用程序从 SQL 填充自定义声明,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40305299/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com