c# - .net core 2.0 JWT token 过期问题

标签 c# azure asp.net-core jwt azure-web-app-service

我遇到了一个非常奇怪的问题,它简直让我发疯,而且对我来说没有任何意义。

让我解释一下: 我有一个 .NET Core 2.0 Web API,由 Angular 5 客户端使用。 Web API 托管在 Azure AppService 中。使用 AspnetCore.Authentication.JWTBearer 通过 JWT Bearer token 进行身份验证(当前版本为 2.0.1) 应用程序在身份验证/登录端点中创建 JWT token 。然后客户端就可以在接下来的调用中进行身份验证。

但是,即使我指定 token 的时间跨度为 1080 分钟(一周),但在大约 8 小时后,我们会说 token 不再有效。我可以离开这个,(实际上我开始指定 token 在几个小时内有效)但是一旦 token 过期......这就是奇怪的东西出现的地方,应用程序在用户之后发出一个新 token 再次登录,但是新的token没有认证,说token已经过期了!刚刚创建的怎么会过期呢。 (我进行了双重检查,新收到的 token 正在发送到服务器,而不是旧的 token )。

此外,如果我只是在 Azure 中重新启动应用程序服务,那么一切都会再次恢复正常,并且会接受新发行的 jwt token 。我认为这可能是 Azure 服务器和其他服务器之间的时钟问题,因此我删除了 ClockSkew 属性并将其保留为 5 分钟(这是其默认值),但没有成功。

我不知道是什么导致了这种奇怪的行为,但导致我的应用程序在一天中的某个时刻毫无用处,除非我进入 Azure 并重新启动应用程序服务。

我的代码如下,但我开始认为它可能是与 .net core 和 Azure 相关的错误?

你看出什么问题了吗? 感谢您的帮助!

这是我的startup.cs类

public class Startup
    {
        private string connectionString;
        private const string SecretKey = "iNivDmHLpUA223sqsfhqGbMRdRj1PVkH"; 
        // todo: get this from somewhere secure
        private readonly SymmetricSecurityKey _signingKey = new 
              SymmetricSecurityKey(Encoding.ASCII.GetBytes(SecretKey));
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            connectionString = Configuration.GetSection("ConnectionString:Value").Value;
            Console.WriteLine("Connection String: " + connectionString);
            services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(connectionString));

            //Initialize the UserManager instance and configuration
            services.AddIdentity<AppUser, IdentityRole>()
            .AddEntityFrameworkStores<ApplicationDbContext>()
            .AddDefaultTokenProviders();

            services.TryAddTransient<IHttpContextAccessor, HttpContextAccessor>();


            // add identity
            var builder = services.AddIdentityCore<AppUser>(o =>
            {
                // configure identity options
                o.Password.RequireDigit = true;
                o.Password.RequireLowercase = true;
                o.Password.RequireUppercase = true;
                o.Password.RequireNonAlphanumeric = true;
                o.Password.RequiredLength = 6;
            });

            builder = new IdentityBuilder(builder.UserType, typeof(IdentityRole), builder.Services);
            builder.AddEntityFrameworkStores<ApplicationDbContext>().AddDefaultTokenProviders();

            //START JWT CONFIGURATION
            services.AddSingleton<IJwtFactory, JwtFactory>();

            // Get options from app settings
            var jwtAppSettingOptions = Configuration.GetSection(nameof(JwtIssuerOptions));

            // Configure JwtIssuerOptions
            services.Configure<JwtIssuerOptions>(options =>
            {
                options.Issuer = jwtAppSettingOptions[nameof(JwtIssuerOptions.Issuer)];
                options.Audience = jwtAppSettingOptions[nameof(JwtIssuerOptions.Audience)];
                options.SigningCredentials = new SigningCredentials(_signingKey, SecurityAlgorithms.HmacSha256);
            });

            var tokenValidationParameters = new TokenValidationParameters
            {
                ValidateIssuer = true,
                ValidIssuer = jwtAppSettingOptions[nameof(JwtIssuerOptions.Issuer)],
                ValidateIssuerSigningKey = true,
                IssuerSigningKey = _signingKey,

                ValidateAudience = true,
                ValidAudience = jwtAppSettingOptions[nameof(JwtIssuerOptions.Audience)],

                RequireExpirationTime = false,
                // ValidateLifetime = true,
                // ClockSkew = TimeSpan.Zero //default son 5 minutos
            };

            services.AddAuthentication(options =>
            {
                options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
            }).AddJwtBearer(configureOptions =>
            {
                configureOptions.ClaimsIssuer = jwtAppSettingOptions[nameof(JwtIssuerOptions.Issuer)];
                configureOptions.TokenValidationParameters = tokenValidationParameters;
                configureOptions.SaveToken = true;
            });

            // api user claim policy
            // Enables [Authorize] decorator on controllers.
            //more information here: https://learn.microsoft.com/en-us/aspnet/core/security/authorization/policies?view=aspnetcore-2.1
            services.AddAuthorization(options =>
            {
                options.AddPolicy("ApiUser", policy => policy.RequireClaim(Constants.Strings.JwtClaimIdentifiers.Rol, Constants.Strings.JwtClaims.ApiAccess));
            });
            //END JWT CONFIGURATION

            // Register the Swagger generator, defining one or more Swagger documents
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new Info
                {
                    Title = Configuration.GetSection("Swagger:Title").Value,
                    Version = "v1"
                });
            });


            //Initialize auto mapper
            services.AddAutoMapper();

            services.AddCors();

            //Initialize MVC
            services.AddMvc();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env,
        UserManager<AppUser> userManager, RoleManager<IdentityRole> roleManager)
        {
            var cultureInfo = new CultureInfo("es-AR");
            //cultureInfo.NumberFormat.CurrencySymbol = "€";

            CultureInfo.DefaultThreadCurrentCulture = cultureInfo;
            CultureInfo.DefaultThreadCurrentUICulture = cultureInfo;


            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseExceptionHandler(
          builder =>
          {
              builder.Run(
                        async context =>
                        {
                            context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
                            context.Response.Headers.Add("Access-Control-Allow-Origin", "*");

                            var error = context.Features.Get<IExceptionHandlerFeature>();
                            if (error != null)
                            {
                                context.Response.AddApplicationError(error.Error.Message);
                                await context.Response.WriteAsync(error.Error.Message).ConfigureAwait(false);
                            }
                        });
          });

            // Enable middleware to serve generated Swagger as a JSON endpoint.
            app.UseSwagger();

            // Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.), specifying the Swagger JSON endpoint.
            app.UseSwaggerUI(c =>
            {
                c.SwaggerEndpoint(
                    Configuration.GetSection("Swagger:Endpoint").Value,
                    Configuration.GetSection("Swagger:Title").Value);
            });

            app.UseAuthentication();

            //Loads initial users and roles.
            if (Configuration["seed"] == "true")
            {
                Console.WriteLine("Seeding database with connection string: " + connectionString);
                Console.WriteLine();
                IdentityDataInitializer.SeedData(userManager, roleManager);
                Console.WriteLine("Finished seeding");
            }
            else
            {
                Console.WriteLine("seeding not configured");

            }

            app.UseDefaultFiles();
            app.UseStaticFiles();

            // Shows UseCors with CorsPolicyBuilder.
            app.UseCors(builder =>
               builder.WithOrigins(Configuration.GetSection("AllowedOrigins:Origin1").Value,
                                    Configuration.GetSection("AllowedOrigins:Origin2").Value)
                 .AllowAnyHeader()
                 .AllowAnyMethod() //Permite también PREFLIGHTS / OPTIONS REQUEST!
               );

            Console.WriteLine("Allowed origin: " + Configuration.GetSection("AllowedOrigins:Origin1").Value);
            Console.WriteLine("Allowed origin: " + Configuration.GetSection("AllowedOrigins:Origin2").Value);

            app.UseMvc();
        }

    }

这是我的 JwtIssuerOptions.cs

public class JwtIssuerOptions
    {
        /// <summary>
        /// 4.1.1.  "iss" (Issuer) Claim - The "iss" (issuer) claim identifies the principal that issued the JWT.
        /// </summary>
        public string Issuer { get; set; }

        /// <summary>
        /// 4.1.2.  "sub" (Subject) Claim - The "sub" (subject) claim identifies the principal that is the subject of the JWT.
        /// </summary>
        public string Subject { get; set; }

        /// <summary>
        /// 4.1.3.  "aud" (Audience) Claim - The "aud" (audience) claim identifies the recipients that the JWT is intended for.
        /// </summary>
        public string Audience { get; set; }

        /// <summary>
        /// 4.1.4.  "exp" (Expiration Time) Claim - The "exp" (expiration time) claim identifies the expiration time on or after which the JWT MUST NOT be accepted for processing.
        /// </summary>
        public DateTime Expiration => IssuedAt.Add(ValidFor);

        /// <summary>
        /// 4.1.5.  "nbf" (Not Before) Claim - The "nbf" (not before) claim identifies the time before which the JWT MUST NOT be accepted for processing.
        /// </summary>
        public DateTime NotBefore { get; set; } = DateTime.UtcNow;

        /// <summary>
        /// 4.1.6.  "iat" (Issued At) Claim - The "iat" (issued at) claim identifies the time at which the JWT was issued.
        /// </summary>
        public DateTime IssuedAt { get; set; } = DateTime.UtcNow;

        /// <summary>
        /// Set the timespan the token will be valid for (default is 120 min)
        /// </summary>
        public TimeSpan ValidFor { get; set; } = TimeSpan.FromMinutes(1080);//una semana



        /// <summary>
        /// "jti" (JWT ID) Claim (default ID is a GUID)
        /// </summary>
        public Func<Task<string>> JtiGenerator =>
          () => Task.FromResult(Guid.NewGuid().ToString());

        /// <summary>
        /// The signing key to use when generating tokens.
        /// </summary>
        public SigningCredentials SigningCredentials { get; set; }
    }

Token.cs 类,将带有 token 的 json 发送到客户端

public class Tokens
    {
        public static async Task<object> GenerateJwt(ClaimsIdentity identity, IJwtFactory jwtFactory, string userName, JwtIssuerOptions jwtOptions, JsonSerializerSettings serializerSettings)
        {
            var response = new
            {
                id = identity.Claims.Single(c => c.Type == "id").Value,
                auth_token = await jwtFactory.GenerateEncodedToken(userName, identity),
                expires_in = (int)jwtOptions.ValidFor.TotalSeconds
            };

            return response;
            //return JsonConvert.SerializeObject(response, serializerSettings);
        }
    }

AuthController.cs

[Produces("application/json")]
    [Route("api/[controller]")]
    public class AuthController : Controller
    {
        private readonly UserManager<AppUser> _userManager;
        private readonly IJwtFactory _jwtFactory;
        private readonly JwtIssuerOptions _jwtOptions;
        private readonly ILogger _logger;

        public AuthController(UserManager<AppUser> userManager,
            IJwtFactory jwtFactory,
            IOptions<JwtIssuerOptions> jwtOptions,
            ILogger<AuthController> logger)
        {
            _userManager = userManager;
            _jwtFactory = jwtFactory;
            _jwtOptions = jwtOptions.Value;
            _logger = logger;
        }

        // POST api/auth/login
        [HttpPost("login")]
        public async Task<IActionResult> Post([FromBody]CredentialsViewModel credentials)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    return BadRequest(ModelState);
                }

                var identity = await GetClaimsIdentity(credentials.UserName, credentials.Password);
                if (identity == null)
                {
                    // Credentials are invalid, or account doesn't exist
                    _logger.LogInformation(LoggingEvents.InvalidCredentials, "Invalid Credentials");
                    return BadRequest(Errors.AddErrorToModelState("login_failure", "Invalid username or password.", ModelState));
                }

                var jwt = await Tokens.GenerateJwt(identity, _jwtFactory, credentials.UserName, _jwtOptions, new JsonSerializerSettings { Formatting = Formatting.Indented });
                CurrentUser cu = Utils.GetCurrentUserInformation(identity.Claims.Single(c => c.Type == "id").Value, _userManager).Result;
                if (cu != null)
                {
                    cu.Jwt = jwt;
                    return new OkObjectResult(cu);
                }

                return StatusCode(500);
            }
            catch (System.Exception ex)
            {
                _logger.LogError(LoggingEvents.GenericError, ex.Message);
                return StatusCode(500, ex);
            }
        }

        private async Task<ClaimsIdentity> GetClaimsIdentity(string userName, string password)
        {
            try
            {
                if (string.IsNullOrEmpty(userName) || string.IsNullOrEmpty(password))
                    return await Task.FromResult<ClaimsIdentity>(null);

                // get the user to verifty
                ILogicUsers lusers = Business.UsersLogic(_userManager);
                AppUser userToVerify = await lusers.FindByNameAsync(userName);

                if (userToVerify == null)
                    return await Task.FromResult<ClaimsIdentity>(null);

                // check the credentials
                if (await lusers.CheckPasswordAsync(userToVerify, password))
                {
                    return await Task.FromResult(_jwtFactory.GenerateClaimsIdentity(userName, userToVerify.Id));
                }

                // Credentials are invalid, or account doesn't exist
                _logger.LogInformation(LoggingEvents.InvalidCredentials, "Invalid Credentials");
                return await Task.FromResult<ClaimsIdentity>(null);
            }
            catch
            {
                throw;
            }
        }
    }

最佳答案

好吧,我想我已经解决了这个问题。

IssuedAt 属性是静态的,并且采用第一次生成的 token 值。当 token 过期时,会生成一个新的 token ,但会采用第一个 token 的 IssuedAt 日期,这就是所有新生成的 token 都过期的原因。在 Azure 中重新启动 AppService 会导致静态值被清除,并正确创建第一个新 token 。

这是正确的行。

public DateTime IssuedAt => DateTime.UtcNow; 

感谢您的帮助!

关于c# - .net core 2.0 JWT token 过期问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50054131/

相关文章:

c# - LINQ to SQL 和 SQL 中的字段连接

azure - 从模板在 ARM 模式下自动扩展 IaaS VM

azure - 我无法从不同的 VS2012 发布 - 错误指向服务运行时不存在?

c# - 使用基于属性的路由时 ASP.NET Core 中的路由冲突

c# - ASP.NET Core 中的 ConfigureServices() 和 Configure() 有什么区别?

c# - 如何在静态方法中引用非静态对象

c# - 使用 C# 测试 REST 日志记录 Web 服务

c# - Azure 服务总线将消息添加到队列的速度太快

asp.net-core - 如何将字符串渲染到 Layout.cshtml 文件?

c# - 如何在控制台应用程序中使文本为 "typed out"?