【发布时间】: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