如何为 Azure 移动应用程序身份验证获取和使用正确的签名密钥?

How to get and use proper signingKey for Azure Mobile Apps Authentication?

我正在使用更新后的 Azure Mobile Apps 和 Google、Microsoft、Twitter 和 Facebook 等身份验证提供商来对访问我网站的用户进行身份验证。所有这一切都运行良好,并且在使用我的 Azure Mobile App 实例进行身份验证后,我取回了一个代表经过身份验证的用户的有效 JWT 令牌。这个令牌我正在转向并作为 Authentication Bearer 令牌发送到服务器以验证对另一个 ASP.NET Core API 服务的请求。所有这些都运行良好。

问题是使用正确的 signing key 值在服务器上验证 JWT。对于测试 - 如果我将我的 JWT 令牌带到 https://jwt.io/ 使用正确的算法 HS256Azure 粘贴我的密钥] 我仍然无法克服 "Invalid Signature" 错误。在同一区域,如果我调用我的 ASP.NET Core API 服务,该服务配置了 Microsoft.AspNetCore.Authentication.JwtBearer 中的 app.UseJwtBearerAuthentication,我会从端点返回相同的 401 错误,说明如下:

401 Unauthorized: Bearer error="invalid_token", error_description="The signature is invalid"

根据 and some other sites I'm supposed to use the WEBSITE_AUTH_SIGNING_KEY from https://[Azure-Mobile-Site-Here].scm.azurewebsites.net/Env.cshtml 的说法,我已经得到了这个值,并尝试从星期日开始使用它作为服务器上的 IssuerSigningKey 的 10 种方式,但没有成功。我总是得到同样的错误。

这是我在服务器上的配置。我试图尽可能地缩小它的范围,反编译代码并只打开最少的标志来验证。我什么也打不通。

private void ConfigureAuth(IApplicationBuilder app)
{
    //Didn't work attempt #1
    //byte[] keyBytes = Encoding.UTF8.GetBytes("975BE84E150ABlahBlahBlahA2527E1AAC80606");
    //if (keyBytes.Length < 64)
    //{
    //    Array.Resize(ref keyBytes, 64);
    //}

    //Didn't work attempt #2
    //byte[] keyBytes = _UTF8Encoder.GetBytes("975BE84E150ABlahBlahBlahA2527E1AAC80606");

    //Didn't work attempt #3
    //var keyAsBytes = Convert.FromBase64String("975BE84E150ABlahBlahBlahA2527E1AAC80606");

    //Didn't work attempt #4
    //var signingKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes("975BE84E150ABlahBlahBlahA2527E1AAC80606"));

    var signingKey = new SymmetricSecurityKey(keyBytes);

    var tokenValidationParameters = new TokenValidationParameters
    {

        RequireExpirationTime = false,
        RequireSignedTokens = false,
        SaveSigninToken = false,
        ValidateActor = false,
        ValidateAudience = false,
        ValidateIssuer = false,
        ValidateLifetime = false,

        //The signing key must match!
        ValidateIssuerSigningKey = true,
        IssuerSigningKey = signingKey,
};

    app.UseJwtBearerAuthentication(new JwtBearerOptions
    {
        AutomaticAuthenticate = true,
        AutomaticChallenge = true,
        TokenValidationParameters = tokenValidationParameters
    });

}

如上文所述,我已经尝试制作 ValidateIssuerSigningKey = false 来尝试绕过这一切,但没有成功。我仍然遇到同样的错误;好像这个位对结果没有影响。

此时我感到迷茫和猜测,因为我什至不确定 WEBSITE_AUTH_SIGNING_KEY 是否正确 signingKey,如果不是,我将白白浪费时间。

什么是正确的 secret / signing key 用于为 Azure Mobile App 实例生成 JWT 令牌以及如何将它正确地合并到服务器上的中间件配置中以验证令牌?

WEBSITE_AUTH_SIGNING_KEY 是适当的环境变量/应用程序设置。但是,它被编码为十六进制字符串。您需要在使用前对其进行解码。在Node SDK中,实现的代码如下:

function hexStringToBuffer(hexString) {
    var bytes = [];
    for (var i = 0; i < hexString.length; i += 2)
        bytes.push(parseInt(hexString.substr(i, 2), 16));
    return new Buffer(bytes);
}

您只需将其转换为 C#。