控制台应用程序中Azure AD承载令牌的验证

本文关键字:令牌 验证 AD 应用程序 Azure 控制台 | 更新日期: 2023-09-27 17:59:26

您可以找到大量如何使用JWT承载身份验证通过Azure AD保护ASP.Net应用程序的示例。这就像在你的启动中添加一些关于你的AAD的信息一样简单,比如:

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
    app.UseJwtBearerAuthentication(new JwtBearerOptions
    {
        Authority = "https://login.windows.net/...",
        Audience = "...",
    });
    app.UseMvc();
}

这些例子没有错,所有的令牌验证魔术都是在幕后发生的,你不必在意它。但实际上,我想知道如何验证ASP.Net之外的Azure AD承载令牌,例如在控制台应用程序中。

在控制台应用程序中,我期望如下所示:

public static void Main(string[] args)
{
   string token = "...";
   JwtSecurityToken validatedJwtToken = validateJwtToken(token);
}
private static JwtSecurityToken validateJwtToken(string token)
{
    JwtSecurityToken jwtToken = new JwtSecurityToken(token)
    //
    // how to validate the AAD token?!
    //
    if(/* is valid */)
    {
        return jwtToken;
    }
    else
    {
        return null;
    }
}

不幸的是,我还没有找到一个可行的例子,但我无法想象这个问题没有简单的解决方案。非常感谢您的任何建议!

控制台应用程序中Azure AD承载令牌的验证

找到了一个基于https://github.com/Azure-Samples/active-directory-dotnet-webapi-manual-jwt-validation:

private const string AUDIENCE = "<GUID of your Audience>";
private const string TENANT = "<GUID of your Tenant>";
private static async Task<SecurityToken> validateJwtTokenAsync(string token)
{
    // Build URL based on your AAD-TenantId
    var stsDiscoveryEndpoint = String.Format(CultureInfo.InvariantCulture, "https://login.microsoftonline.com/{0}/.well-known/openid-configuration", TENANT);
    // Get tenant information that's used to validate incoming jwt tokens
    var configManager = new ConfigurationManager<OpenIdConnectConfiguration>(stsDiscoveryEndpoint);
    // Get Config from AAD:
    var config = await configManager.GetConfigurationAsync();
    // Validate token:
    var tokenHandler = new JwtSecurityTokenHandler();
    var validationParameters = new TokenValidationParameters
    {
        ValidAudience = AUDIENCE,
        ValidIssuer = config.Issuer,
        IssuerSigningTokens = config.SigningTokens,
        CertificateValidator = X509CertificateValidator.ChainTrust,
    };
    var validatedToken = (SecurityToken)new JwtSecurityToken();
    // Throws an Exception as the token is invalid (expired, invalid-formatted, etc.)
    tokenHandler.ValidateToken(token, validationParameters, out validatedToken);
    return validatedToken;
}

这只是原始的基础知识,仅使用net452进行了测试。请查看上面的链接以了解进一步的用法(例如缓存SigningTokens一段时间)。