Azure Function V2中的JWT验证

时间:2019-12-16 22:19:34

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

我正在尝试使用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/

1 个答案:

答案 0 :(得分:1)

根据您的用例,您可能需要对App Services使用开箱即用的身份验证机制:

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