【问题标题】:IdentityServer4 User.Identity.Name is emptyIdentityServer4 User.Identity.Name 为空
【发布时间】:2021-04-13 09:05:03
【问题描述】:

当我想在 mvc 客户端中获取当前用户名时,它返回空。 我的 config.cs 代码:

    public static IEnumerable<Client> GetClients()
    {
        return new List<Client>
        {
            new Client
            {
                ClientName="Desktop",
                 ClientId = "Desktop",

                AllowedGrantTypes = GrantTypes.Code,
                AllowOfflineAccess = true,
                ClientSecrets = { new Secret("secret".Sha256()) },

                RedirectUris =           { "https://localhost:5001/signin-oidc" },
                PostLogoutRedirectUris = { "https://localhost:5001/" },
                FrontChannelLogoutUri =    "https://localhost:5001/signout-oidc",

                AllowedScopes =
                {
                    IdentityServerConstants.StandardScopes.OpenId,
                    IdentityServerConstants.StandardScopes.Profile,
                    "sms",

                    "mail.send",
                    "mail.search"
                },
                RequireConsent = false
            }
        };
    }

我的 MVC 客户端 Startup.cs 文件:

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddMvc();

        services.AddHttpContextAccessor();

        services.AddAuthentication(options=> {
            options.DefaultScheme = "Cookies";
            options.DefaultChallengeScheme = "oidc";
        })
            .AddCookie("Cookies",options=> {
                options.Cookie.Name = this.Configuration["Cookies:IDS"];                    
            })
            .AddOpenIdConnect("oidc",options=> {
                options.Authority = this.Configuration["IDS"];
                options.RequireHttpsMetadata = true;
                options.ClientId = "Desktop";
                options.ClientSecret = "secret";
                options.ResponseType = "code";
                options.SaveTokens = true;
                options.GetClaimsFromUserInfoEndpoint = true;

                options.Scope.Clear();
                options.Scope.Add("openid");
                options.Scope.Add("profile");
                options.Scope.Add("sms");
                options.Scope.Add("mail.send");
                options.Scope.Add("mail.search");
            });
    }

我的登录代码:

    [HttpPost]
    [Route("/Home/LoginPost")]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> LoginPostAsync(LoginInputModel model)
    {
        var context = await Interaction.GetAuthorizationContextAsync(model.ReturnUrl);
        if (ModelState.IsValid)
        {
            //await this.signInManager.SignInAsync(new RWongAccountUser()
            //{
            //    PhoneNumber = model.Identity
            //},isPersistent:false);

            var signInResult = await this.signInManager.PasswordSignInAsync(model.Identity, model.Password, isPersistent: false, lockoutOnFailure: false);
                            

            if (signInResult.Succeeded)
            {
                var user = await this.userManager.FindByNameAsync(model.Identity);
                //await this.Events.RaiseAsync(new UserLoginSuccessEvent(user.UserName, user.Id, user.UserName, clientId: context?.Client.ClientId));
                await this.Events.RaiseAsync(new UserLoginSuccessEvent(user.UserName, user.Id, user.UserName, "Desktop"));
                return Content("Succeeded");
            }
            if (signInResult.IsLockedOut)
            {
                return Content("IsLockedOut");
            }
            if (signInResult.IsNotAllowed)
            {
                return Content("IsNotAllowed");
            }
        }
        return Content("Failed");
    }

当我想像这样获取当前用户名:User.Identity.Name 时,它​​返回空。 但我可以从用户声明中获取名称。

如何直接通过 [User.Identity.Name] 获取当前用户名? 谢谢!

【问题讨论】:

    标签: .net asp.net-core identityserver4


    【解决方案1】:

    那么微软和IdentityServer对声明的名称应该是什么意见不同,所以需要指出,哪个声明是名称声明,通过使用:

        .AddJwtBearer(opt =>
        {
            opt.TokenValidationParameters.RoleClaimType = "roles";
            opt.TokenValidationParameters.NameClaimType = "name";
    
            ...
    

    要调试声明问题,实际查看访问令牌实际包含什么会非常好?使用像 https://jwt.io/ 这样的工具来做到这一点。

    【讨论】:

    • 或者更好opt.TokenValidationParameters.NameClaimType = System.Security.Claims.ClaimTypes.Name
    • 感谢您的帮助!我已经解决了问题!
    • 如果我的回答解决了您的问题,请随时将我的回答标记为可以接受
    猜你喜欢
    • 2015-11-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-18
    • 1970-01-01
    相关资源
    最近更新 更多