【问题标题】:AddOpenIdConnect with local UserManagerAddOpenIdConnect 与本地 UserManager
【发布时间】:2020-08-27 11:37:29
【问题描述】:

我在我的 .net 核心应用程序中使用 OpenIdConnect 中间件。

这一切都与我的身份服务器一起工作,但是,我想跟踪我网站中的用户活动,而不仅仅是对他们进行身份验证。

在验证令牌后这样做,我有一个OnTokenValidated 的自定义事件

services.AddIdentity<IdentityUser, IdentityRole>()
    .AddEntityFrameworkStores<ApplicationDbContext>()
    .AddUserManager<UserManager<IdentityUser>>()
    .AddDefaultTokenProviders();

services.AddAuthentication(options =>
{
    options.DefaultScheme = "Cookies";
    options.DefaultChallengeScheme = "oidc";
})
    .AddCookie("Cookies")
    .AddOpenIdConnect("oidc", options =>
    {
        options.Authority = "https://localhost:5000";

        options.ClientId = "mvc";
        options.ClientSecret = "49C1A7E1-0C79-4A89-A3D6-A37998FB86B0";
        options.ResponseType = "code";

        options.GetClaimsFromUserInfoEndpoint = true;
        options.SaveTokens = true;
        options.CallbackPath = "/Home/Login/";
        options.Events = new OpenIdConnectEvents()
        {
            OnTokenValidated = ctx =>
            {
                var userId = ctx.Principal.Claims.FirstOrDefault(e => e.Type == ClaimTypes.NameIdentifier)?.Value ?? null;
                if (!string.IsNullOrEmpty(userId))
                {
                    //NEED HELP HERE
                }

                return Task.CompletedTask;
            }
        };

        options.Scope.Add("api1");
        options.Scope.Add("offline_access");

        options.ClaimActions.Add(new Microsoft.AspNetCore.Authentication.OAuth.Claims.JsonKeyClaimAction("role", null, "role"));

        options.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters
        {
            NameClaimType = "name",
            RoleClaimType = "role"
        };
    });

我计划在我的 MVC 应用程序上使用 AspNetIdentity,它将检查刚刚通过身份验证的用户是否存在于我的本地数据库中。

问题:

如何在我的AddAuthentication 中使用来自 AspNetIdentity 的 UserManager?

我想我可以创建一个 DbContext 并直接访问它,但我更喜欢使用 UserManage 来保持一致性。

【问题讨论】:

    标签: entity-framework asp.net-core single-sign-on openid-connect


    【解决方案1】:

    您可以像这样使用 UserManage 查询数据库:

    options.Events = new OpenIdConnectEvents
    {
        OnTokenValidated = async ctx =>
        {
    
            var _userManager = ctx.HttpContext.RequestServices.GetRequiredService<UserManager<IdentityUser>>();
            var users =await  _userManager.Users.ToListAsync();
    
            ...
        },
    
    };
    

    【讨论】:

      猜你喜欢
      • 2020-05-14
      • 2018-08-23
      • 2020-06-18
      • 1970-01-01
      • 2016-08-06
      • 2018-10-01
      • 2020-05-03
      • 2021-03-29
      • 2018-10-13
      相关资源
      最近更新 更多