【问题标题】:JWT Validation in Azure Function V2Azure Function V2 中的 JWT 验证
【发布时间】:2020-04-09 09:57:55
【问题描述】:

我正在尝试使用 azure AD 在 Azure Function V2 中实现 JWT 令牌验证。但是我在下面收到此错误

IDX10501:签名验证失败。无法匹配键: 孩子:'BB8CeFVqyaGrGNuehJIiL4dfjzw',

我不确定我在这里做错了什么

这是我的代码

public class AccessTokenProvider : IAccessTokenProvider
    {
        private const string AUTH_HEADER_NAME   = "Authorization";
        private const string BEARER_PREFIX      = "Bearer ";
        private readonly string _audience;
        private readonly string _issuer;
        private readonly bool _enabled;

        public AccessTokenProvider(bool enabled , string audience, string issuer)
        {
            _enabled        = enabled;
            _audience       = audience;
            _issuer         = issuer;
        }

        public AccessTokenResult ValidateToken(HttpRequest request)
        {
            try
            {
                if(!_enabled)
                {
                    return AccessTokenResult.Success(null);
                }
                // Get the token from the header
                if (request != null &&
                    request.Headers.ContainsKey(AUTH_HEADER_NAME) &&
                    request.Headers[AUTH_HEADER_NAME].ToString().StartsWith(BEARER_PREFIX))
                {
                     var sharedKey = new SymmetricSecurityKey(Convert.FromBase64String("PublicKey"));
                     var token = request.Headers[AUTH_HEADER_NAME].ToString().Substring(BEARER_PREFIX.Length);
                    // Create the parameters
                    var tokenParams = new TokenValidationParameters()
                    {
                        RequireSignedTokens         = true,
                        ValidAudience               = _audience,
                        ValidateAudience            = true,
                        ValidIssuer                 = _issuer,
                        ValidateIssuer              = true,
                        ValidateIssuerSigningKey    = true,
                        ValidateLifetime            = true,
                        IssuerSigningKey            = sharedKey
                    };

                    // Validate the token
                    var handler     = new JwtSecurityTokenHandler();

                    var result      = handler.ValidateToken(token, tokenParams, out var securityToken);
                    return AccessTokenResult.Success(result);
                }
                else
                {
                    return AccessTokenResult.NoToken();
                }
            }
            catch (SecurityTokenExpiredException)
            {
                return AccessTokenResult.Expired();
            }
            catch (Exception ex)
            {
                return AccessTokenResult.Error(ex);
            }
        }

我的 Startup.cs 中有这段代码

private static void RegisterJwtTokenValidation(IServiceCollection services)
        {
            // Get the configuration files for the OAuth token issuer
            var audience        = Environment.GetEnvironmentVariable("Authentication.Audiences");
            var issuer          = Environment.GetEnvironmentVariable("Authentication.Issuer");
            var authEnabled     = Environment.GetEnvironmentVariable("Authentication.Enabled");

            if (!bool.TryParse(authEnabled, out bool isAuthEnabled))
            {
                isAuthEnabled = false;
            }

            // Register the access token provider as a singleton
            services.AddSingleton<IAccessTokenProvider, AccessTokenProvider>(s => new AccessTokenProvider(isAuthEnabled, audience, issuer));
        }

注意:代码参考https://www.ben-morris.com/custom-token-authentication-in-azure-functions-using-bindings/

【问题讨论】:

  • 似乎是与您的共享密钥内容相关的加密问题。我希望你已经替换了 var sharedKey = new SymmetricSecurityKey(Convert.FromBase64String("PublicKey"));使用真正的公钥,否则就是问题所在。
  • 有一个开箱即用的解决方案:docs.microsoft.com/en-us/azure/app-service/…。这不适合您的情况吗?
  • @Thomas。谢谢..没有意识到有一个开箱即用的解决方案。它工作得很好。请将此添加为答案,我会接受。

标签: c# azure .net-core azure-active-directory azure-functions


【解决方案1】:

取决于您的用例,您可能希望对应用服务使用开箱即用的身份验证机制:

如果您需要访问用户声明,您也可以查看文档:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-11-05
    • 2022-10-06
    • 2022-08-03
    • 1970-01-01
    • 2015-11-15
    • 1970-01-01
    • 2020-10-29
    • 2017-03-31
    相关资源
    最近更新 更多