asp.net core mvc中jwt过期后重新定向到登陆界面

1.asp.net core mvc中jwt过期后重新定向到登陆界面时,提示重定向次数过多
2.Login是个分部视图

 builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
    .AddJwtBearer(options =>
    {
        options.TokenValidationParameters = new TokenValidationParameters
        {
            //JWT有一些默认的属性,就是给鉴权时就可以筛选了
            ValidateIssuer = true,//是否验证Issuer
            ValidateAudience = true,//是否验证Audience
            ValidateLifetime = true,//是否验证失效时间
            ValidateIssuerSigningKey = true,//是否验证SecurityKey
            ValidAudience = tokenOptions.Audience,//
            ValidIssuer = tokenOptions.Issuer,//Issuer,这两项和前面签发jwt的设置一致
            ClockSkew = TimeSpan.FromSeconds(0),//JWT立即失效
            IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(tokenOptions.SecurityKey))
        };
        #region Events
        options.Events = new JwtBearerEvents()
        {
          
            OnAuthenticationFailed = context =>
            {
                if(context.Exception.GetType() == typeof(SecurityTokenExpiredException))
                {
                    context.Response.Redirect("http://localhost:8080/Login");   //提示重定向次数过多                  
                }
                return Task.CompletedTask;
            },                
        };
        #endregion
    });

【以下回答由 GPT 生成】

问题标题: 在 ASP.NET Core MVC 中,当 JWT 过期后重新定向到登陆界面时,提示 "重定向次数过多" ,请问正确的方法应该怎样写呢?

问题内容: 在 ASP.NET Core MVC 中,我使用 JWT 进行身份验证。我希望在 JWT 过期后自动将用户重定向到登陆界面。但是,我目前的代码在 JWT 过期后执行重定向操作时会出现“重定向次数过多”的错误提示。

以下是目前的代码:

builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
    .AddJwtBearer(options =>
    {
        options.TokenValidationParameters = new TokenValidationParameters
        {
            // JWT 有一些默认的属性,可以用于鉴权时的筛选
            ValidateIssuer = true,    // 是否验证 Issuer
            ValidateAudience = true,  // 是否验证 Audience
            ValidateLifetime = true,  // 是否验证失效时间
            ValidateIssuerSigningKey = true,  // 是否验证 SecurityKey
            ValidAudience = tokenOptions.Audience,
            ValidIssuer = tokenOptions.Issuer,
            ClockSkew = TimeSpan.FromSeconds(0),  // JWT 立即失效
            IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(tokenOptions.SecurityKey))
        };

        // 以下是处理 JWT 过期后的事件
        options.Events = new JwtBearerEvents()
        {
            OnAuthenticationFailed = context =>
            {
                if(context.Exception.GetType() == typeof(SecurityTokenExpiredException))
                {
                    context.Response.Redirect("http://localhost:8080/Login");   // 此处会提示 "重定向次数过多"
                }
                return Task.CompletedTask;
            },
        };
    });

请优化以上的问题描述和代码片段,并提供解决方案。



【相关推荐】



如果你已经解决了该问题, 非常希望你能够分享一下解决方案, 写成博客, 将相关链接放在评论区, 以帮助更多的人 ^-^