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

K7浮标

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

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

问题与疑问-我正尝试填充一个自定义索赔属性“ Id”,并通过ClaimsPrincipal在全球范围内使用该属性。迄今为止,我研究了ClaimsTransformation并没有取得太大的成功。在其他文章中,我读到您必须在登录之前添加声明,但这真的是真的吗?那将意味着完全依靠AD来完成所有索赔,真的是这样吗?

下面是此时我在HomeController中的简单代码。我正在访问数据库,然后尝试填充ClaimsPrincipal,但随后返回域用户模型。我认为这可能是我的问题所在,但是我对.net中的Authorization还是陌生的,并且一直在努力争取索赔。

非常感谢您提供的所有帮助

当前代码:

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:尽管先前已返回域模型,但对象引用未设置为对象错误的实例。

使用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?}");
            });
        }
    }
}
酷卡格琳

您需要IClaimsTransformer与依赖项注入一起使用

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

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

而且需要注入DbContextClaimsTransformer

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章

来自分类Dev

如何使用Angular个人用户帐户身份验证自定义ASP.NET Core Web应用程序的登录页面?

来自分类Dev

使用声明原则访问Asp.NET Web核心应用程序中以前通过身份验证的用户

来自分类Dev

NET Core中如何使用自定义策略架构实现jwt令牌库身份验证以进行授权?

来自分类Dev

如何使用WebListener和Windows身份验证将ASP.NET Core应用程序托管在IIS下?

来自分类Dev

如何使用WebListener和Windows身份验证将ASP.NET Core应用程序托管在IIS下?

来自分类Dev

在ASP.NET Core中使用Authorize属性和自定义Cookie身份验证

来自分类Dev

在.NET Core Web API中使用自定义属性进行JWT身份验证

来自分类Dev

使用 Active Directory 身份验证在 ASP.NET Core Web 应用程序中创建用户

来自分类Dev

使用Windows身份验证将Power BI嵌入到本地ASP.NET Web应用程序中

来自分类Dev

在ASP.NET MVC 4应用程序中的身份验证中使用会话变量

来自分类Dev

在ASP.NET MVC 4应用程序中的身份验证中使用会话变量

来自分类Dev

ASP.NET CORE 中的自定义身份验证和更新声明

来自分类Dev

使用mod_auth_openidc对自定义Web应用程序进行身份验证

来自分类Dev

使用Azure移动应用程序进行自定义身份验证

来自分类Dev

在ASP.NET MVC5中使用自定义登录进行表单身份验证

来自分类Dev

在ASP.NET MVC5中使用自定义登录进行表单身份验证

来自分类Dev

Firebase 3:使用.net和C#创建自定义身份验证令牌

来自分类Dev

使用身份验证时,TFS WorkItemStore在ASP.NET MVC应用程序中引发COMException

来自分类Dev

使用ldap进行身份验证的C#ASP.NET应用程序

来自分类Dev

使用身份验证令牌从 Xamarin 登录到 ASP.Net 应用程序

来自分类Dev

.Net Core 3.1自定义身份验证

来自分类Dev

使用Jwt Bearer身份验证的自定义声明

来自分类Dev

使用HttpPost的Android应用程序自定义Web服务身份验证不起作用

来自分类Dev

ASP.NET Core 3.1的自定义身份验证处理程序的授权失败?

来自分类Dev

在Blazor应用程序中使用Azure Active Directory时如何自定义ASP Net Core 3.1中的注销页面

来自分类Dev

.NET MVC中Elmah的自定义身份验证

来自分类Dev

Azure AD身份验证redirect_uri在Linux托管的(Cloud Foundry)ASP.NET Core 2.2应用程序上未使用https

来自分类Dev

当用户未分配给客户端应用程序时,使用 ASP.Net Core 的 OKTA 身份验证会引发未处理的异常

来自分类Dev

如何使用自定义身份验证和内存托管进行ASP.NET Web API集成测试

Related 相关文章

  1. 1

    如何使用Angular个人用户帐户身份验证自定义ASP.NET Core Web应用程序的登录页面?

  2. 2

    使用声明原则访问Asp.NET Web核心应用程序中以前通过身份验证的用户

  3. 3

    NET Core中如何使用自定义策略架构实现jwt令牌库身份验证以进行授权?

  4. 4

    如何使用WebListener和Windows身份验证将ASP.NET Core应用程序托管在IIS下?

  5. 5

    如何使用WebListener和Windows身份验证将ASP.NET Core应用程序托管在IIS下?

  6. 6

    在ASP.NET Core中使用Authorize属性和自定义Cookie身份验证

  7. 7

    在.NET Core Web API中使用自定义属性进行JWT身份验证

  8. 8

    使用 Active Directory 身份验证在 ASP.NET Core Web 应用程序中创建用户

  9. 9

    使用Windows身份验证将Power BI嵌入到本地ASP.NET Web应用程序中

  10. 10

    在ASP.NET MVC 4应用程序中的身份验证中使用会话变量

  11. 11

    在ASP.NET MVC 4应用程序中的身份验证中使用会话变量

  12. 12

    ASP.NET CORE 中的自定义身份验证和更新声明

  13. 13

    使用mod_auth_openidc对自定义Web应用程序进行身份验证

  14. 14

    使用Azure移动应用程序进行自定义身份验证

  15. 15

    在ASP.NET MVC5中使用自定义登录进行表单身份验证

  16. 16

    在ASP.NET MVC5中使用自定义登录进行表单身份验证

  17. 17

    Firebase 3:使用.net和C#创建自定义身份验证令牌

  18. 18

    使用身份验证时,TFS WorkItemStore在ASP.NET MVC应用程序中引发COMException

  19. 19

    使用ldap进行身份验证的C#ASP.NET应用程序

  20. 20

    使用身份验证令牌从 Xamarin 登录到 ASP.Net 应用程序

  21. 21

    .Net Core 3.1自定义身份验证

  22. 22

    使用Jwt Bearer身份验证的自定义声明

  23. 23

    使用HttpPost的Android应用程序自定义Web服务身份验证不起作用

  24. 24

    ASP.NET Core 3.1的自定义身份验证处理程序的授权失败?

  25. 25

    在Blazor应用程序中使用Azure Active Directory时如何自定义ASP Net Core 3.1中的注销页面

  26. 26

    .NET MVC中Elmah的自定义身份验证

  27. 27

    Azure AD身份验证redirect_uri在Linux托管的(Cloud Foundry)ASP.NET Core 2.2应用程序上未使用https

  28. 28

    当用户未分配给客户端应用程序时,使用 ASP.Net Core 的 OKTA 身份验证会引发未处理的异常

  29. 29

    如何使用自定义身份验证和内存托管进行ASP.NET Web API集成测试

热门标签

归档