You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

.NET 6中ASP.NET API如何获取请求使用的身份验证方案?

获取JWT令牌对应认证方案的简便方法

1. 直接读取ClaimsPrincipal.AuthenticationType

单个认证方案验证通过后,HttpContext.User的AuthenticationType属性会直接返回对应的认证方案名称(如MyDefaultScheme或SomeSecondaryScheme)。在控制器中可直接使用:

[ApiController]
[Authorize(AuthenticationSchemes = "MyDefaultScheme,SomeSecondaryScheme")]
public class SomeApiController : ControllerBase
{
    [HttpGet]
    public IActionResult Get()
    {
        string authScheme = User.AuthenticationType;
        
        // 根据认证方案分支处理声明
        string userName = authScheme switch
        {
            "MyDefaultScheme" => User.FindFirstValue("sub"),
            "SomeSecondaryScheme" => User.FindFirstValue("preferred_username"),
            _ => throw new UnauthorizedAccessException("未知认证方案")
        };
        
        return Ok(new { UserName = userName, AuthScheme = authScheme });
    }
}

2. 处理多认证方案同时通过的场景

若请求同时通过多个认证方案验证(少见但存在可能),可遍历User.Identities集合,每个ClaimsIdentity的AuthenticationType对应一个成功的认证方案:

var successfulSchemes = User.Identities
    .Where(id => id.IsAuthenticated)
    .Select(id => id.AuthenticationType)
    .ToList();

3. 封装扩展方法复用逻辑

给ClaimsPrincipal编写扩展方法,能在项目中统一快速获取认证方案及对应声明:

public static class ClaimsPrincipalExtensions
{
    public static string GetAuthenticationScheme(this ClaimsPrincipal principal)
    {
        var identity = principal.Identity as ClaimsIdentity;
        return identity?.AuthenticationType ?? principal.AuthenticationType;
    }
    
    public static string GetUserName(this ClaimsPrincipal principal)
    {
        var scheme = principal.GetAuthenticationScheme();
        return scheme switch
        {
            "MyDefaultScheme" => principal.FindFirstValue("sub"),
            "SomeSecondaryScheme" => principal.FindFirstValue("preferred_username"),
            _ => null
        };
    }
}

使用时代码更简洁:

string userName = User.GetUserName();
string authScheme = User.GetAuthenticationScheme();

优势说明

AuthenticationType是ASP.NET Core认证框架验证成功后自动赋值的,无需手动解析iss再映射方案名,避免维护额外的映射关系,代码更直观且不易出错。


内容的提问来源于stack exchange,提问作者Mats Magnem

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.08 17:20:26