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

时间:2016-07-31 14:13:28

标签: c# azure jwt bearer-token azure-active-directory

您可以找到大量示例,了解如何使用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();
}

这些例子没有任何问题,所有Token-Validation-Magic都在幕后发生,你不必关心它。但实际上我想知道如何验证除ASP.Net之外的Azure AD Bearer Token,例如在控制台应用程序中。

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

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;
    }
}

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

1 个答案:

答案 0 :(得分:3)

找到一个解决方案 - 基于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缓存一段时间)。