User.Identity 空指针异常与 SPA(Angular) visual studio angular 模板
User.Identity null pointer exception with SPA(Angular) visual studio angular template
我正在使用 visual studio angular 模板创建项目,尝试访问用户声明 User.Identity.Name
。由于用户为null,所以得到空指针异常。
我已按照此处的说明进行操作 https://docs.microsoft.com/en-us/aspnet/core/security/authentication/identity-api-authorization?view=aspnetcore-3.1
它使用 AddApiAuthorization、AddIdentityServerJwt、OidcConfigurationController
Startup.cs
services.AddIdentityServer()
.AddApiAuthorization<ApplicationUser, ApplicationDbContext>()
.AddProfileService<ProfileService>();
services.AddAuthentication()
.AddIdentityServerJwt();
app.UseAuthentication();
app.UseIdentityServer();
app.UseAuthorization();
app.UseSpa(spa =>
{
spa.Options.SourcePath = "ClientApp";
if (env.IsDevelopment())
{
spa.UseAngularCliServer(npmScript: "start");
}
});
在基本控制器中,我正在尝试访问用户声明
[Authorize]
public abstract class BaseController : ControllerBase
{
private readonly UserManager<ApplicationUser> _userManager;
public BaseController()
{
var identity = HttpContext.User.Identity as ClaimsIdentity;
var user = _userManager.FindByNameAsync(User.Identity.Name).Result;
}
}
从身份服务器登录成功后,用户为空。 basecontroller装饰有[Authorize]
授权后断点生效
不是 User 为空,而是 HttpContext 为空。
在构造函数中调用了 HttpContext,然后还没有实例化 HttpContext,因为当客户端连接到此控制器时会发生这种情况。将您的代码移到控制器内的方法中,您会发现已设置 HttpContext。
我正在使用 visual studio angular 模板创建项目,尝试访问用户声明 User.Identity.Name
。由于用户为null,所以得到空指针异常。
我已按照此处的说明进行操作 https://docs.microsoft.com/en-us/aspnet/core/security/authentication/identity-api-authorization?view=aspnetcore-3.1
它使用 AddApiAuthorization、AddIdentityServerJwt、OidcConfigurationController
Startup.cs
services.AddIdentityServer()
.AddApiAuthorization<ApplicationUser, ApplicationDbContext>()
.AddProfileService<ProfileService>();
services.AddAuthentication()
.AddIdentityServerJwt();
app.UseAuthentication();
app.UseIdentityServer();
app.UseAuthorization();
app.UseSpa(spa =>
{
spa.Options.SourcePath = "ClientApp";
if (env.IsDevelopment())
{
spa.UseAngularCliServer(npmScript: "start");
}
});
在基本控制器中,我正在尝试访问用户声明
[Authorize]
public abstract class BaseController : ControllerBase
{
private readonly UserManager<ApplicationUser> _userManager;
public BaseController()
{
var identity = HttpContext.User.Identity as ClaimsIdentity;
var user = _userManager.FindByNameAsync(User.Identity.Name).Result;
}
}
从身份服务器登录成功后,用户为空。 basecontroller装饰有[Authorize]
授权后断点生效
不是 User 为空,而是 HttpContext 为空。
在构造函数中调用了 HttpContext,然后还没有实例化 HttpContext,因为当客户端连接到此控制器时会发生这种情况。将您的代码移到控制器内的方法中,您会发现已设置 HttpContext。