ASP.NET Core MVC如何验证指定AuthenticationScheme的用户是否已认证
解决方案
在未添加[Authorize]特性的控制器中,ASP.NET Core默认不会自动触发认证流程,因此User.Identity.IsAuthenticated会返回false。针对你的Umbraco v10项目,可通过以下方式手动获取指定认证方案的登录用户信息:
1. 手动触发指定认证方案的认证
在控制器中手动调用认证方法,获取指定方案的用户主体并赋值给当前上下文:
方法一:直接使用HttpContext.AuthenticateAsync
public async Task<IActionResult> YourAction() { // 替换为你的自定义认证方案名称 var customAuthScheme = "YourCustomAuthScheme"; var authResult = await HttpContext.AuthenticateAsync(customAuthScheme); if (authResult.Succeeded && authResult.Principal != null) { // 将认证后的用户主体绑定到当前上下文 HttpContext.User = authResult.Principal; // 此时可正常获取用户状态与信息 bool isAuthenticated = User.Identity.IsAuthenticated; // 返回true string userName = User.Identity.Name; } // 后续业务逻辑 return View(); }
方法二:使用Umbraco封装的IAuthenticationService
Umbraco提供了标准化的认证服务,适合项目内统一调用:
private readonly IAuthenticationService _authService; // 构造函数注入服务 public YourController(IAuthenticationService authService) { _authService = authService; } public async Task<IActionResult> YourAction() { var customAuthScheme = "YourCustomAuthScheme"; var authResult = await _authService.AuthenticateAsync(HttpContext, customAuthScheme); if (authResult.Succeeded && authResult.Principal != null) { HttpContext.User = authResult.Principal; string userName = User.Identity.Name; } return View(); }
2. 确认自定义认证方案的配置
确保你的自定义认证方案已在Program.cs中正确注册(Umbraco v10使用Program.cs进行配置):
builder.Services.AddAuthentication() .AddScheme<YourCustomAuthOptions, YourCustomAuthHandler>( "YourCustomAuthScheme", options => { // 配置自定义方案的参数,如验证逻辑、Cookie名称等 });
3. Umbraco自带认证方案的影响说明
Umbraco v10自带的认证方案(如UmbracoBackOffice)与自定义方案是独立的认证上下文,不会互相干扰。只要明确指定自定义方案的名称,就能单独获取该方案下的用户信息。
内容的提问来源于stack exchange,提问作者Myster
相关产品推荐
相关产品推荐

