Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/295.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# JwtSecurityToken到期时间无效.NET Core 3.1_C#_Asp.net Core_Authentication_Jwt_Asp.net Authorization - Fatal编程技术网

C# JwtSecurityToken到期时间无效.NET Core 3.1

C# JwtSecurityToken到期时间无效.NET Core 3.1,c#,asp.net-core,authentication,jwt,asp.net-authorization,C#,Asp.net Core,Authentication,Jwt,Asp.net Authorization,我将我的应用程序从.NET Core 2.2升级到.NET Core 3.1。当我试图用邮递员测试我的端点时,我注意到我得到了401未经验证的错误。当我查看标题时,我发现到期时间无效: 我拿了以下不记名代币: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJodHRwOi8vc2NoZW1hcy54bWxzb2FwLm9yZy93cy8yMDA1LzA1L2lkZW50aXR5L2NsYWltcy9uYW1lIjoiQm9iIiwibmJmIjoiMTYxNzk

我将我的应用程序从.NET Core 2.2升级到.NET Core 3.1。当我试图用邮递员测试我的端点时,我注意到我得到了401未经验证的错误。当我查看标题时,我发现到期时间无效:

我拿了以下不记名代币:

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJodHRwOi8vc2NoZW1hcy54bWxzb2FwLm9yZy93cy8yMDA1LzA1L2lkZW50aXR5L2NsYWltcy9uYW1lIjoiQm9iIiwibmJmIjoiMTYxNzk3Nzg1MSIsImV4cCI6IjE2MjMxNjE4NTYiLCJodHRwOi8vc2NoZW1hcy5taWNyb3NvZnQuY29tL3dzLzIwMDgvMDYvaWRlbnRpdHkvY2xhaW1zL3JvbGUiOlsiQmFza2V0YmFsbCIsIlJ1Z2J5IiwiRm9vdGJhbGwiXX0.QRLuXFeopf7QZ1NUzWcctuSfnNXiPgc2UH7NxAuHYvw
我在我的generate token端点上进行解码,exp字段是“1623161856”。 我将其转换为Javascript中的日期对象,它在未来相当于60天。

所以令牌肯定没有过期。不确定在升级到.NET Core 3.1的过程中是否遗漏了任何内容,但以下是相关代码:

Startup.cs
中,我有

   public void ConfigureServices(IServiceCollection services)
    {


        // Initial Setup
        services.AddMvc();
        services.AddSingleton<IConfiguration>(Configuration);
        // Call this in case you need aspnet-user-authtype/aspnet-user-identity
        services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
        // Register the Swagger generator, defining one or more Swagger documents 
        services.AddSwaggerGen(c =>
        {
            c.SwaggerDoc(Configuration["v1"], new OpenApiInfo { Title = Configuration["Sports"], Version = Configuration["v1] });
        });

        services.AddDataProtection();
        
        //Authentication Setup
        services.AddAuthentication(options =>
        {
            options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
            options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
        }).AddJwtBearer(options =>
        {
            options.TokenValidationParameters = new TokenValidationParameters
            {
                ValidateAudience = false,
                ValidateIssuer = false,
                ValidateIssuerSigningKey = true,
                IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("AnythingYouWant")),
                ValidateLifetime = true,
                ClockSkew = TimeSpan.FromMinutes(5)
            };
            options.SaveToken = true;
            options.Events = new JwtBearerEvents()
            {
                OnTokenValidated = context =>
                {
                    var accessToken = context.SecurityToken as JwtSecurityToken;
                    if (accessToken != null)
                    {
                        ClaimsIdentity identity = context.Principal.Identity as ClaimsIdentity;
                        if (identity != null)
                        {
                            identity.AddClaim(new Claim("access_token", accessToken.RawData));
                        }
                    }

                    return Task.CompletedTask;
                }
            };
        });
        services.AddAuthorization();
    }

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILoggerFactory loggerFactory)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
            app.UseBrowserLink();
        }
        else
        {
            app.UseExceptionHandler("/Home/Error");
        }

        app.UseSwagger();

        app.UseSwaggerUI(c =>
        {
            c.SwaggerEndpoint("/swagger/" + Configuration["v1"] + "/swagger.json", Configuration["Sports"]);
        });
        
        app.UseStaticFiles();
        app.UseRouting();
        app.UseCors();

        app.UseAuthentication();
        app.UseAuthorization();
        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllerRoute("default", "{controller=Home}/{action=Index}/{id?}");
            endpoints.MapControllerRoute("swagger", "swagger/");
        });

        app.UseWelcomePage("/swagger");
    }
public void配置服务(IServiceCollection服务)
{
//初始设置
services.AddMvc();
services.AddSingleton(配置);
//如果需要aspnet user authtype/aspnet user identity,请调用此函数
services.AddSingleton();
//注册招摇过市生成器,定义一个或多个招摇过市文档
services.AddSwaggerGen(c=>
{
c、 SwaggerDoc(配置[“v1”],新OpenApiInfo{Title=Configuration[“Sports”],Version=Configuration[“v1]});
});
services.AddDataProtection();
//身份验证设置
services.AddAuthentication(选项=>
{
options.DefaultAuthenticateScheme=JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme=JwtBearerDefaults.AuthenticationScheme;
}).AddJwtBearer(选项=>
{
options.TokenValidationParameters=新的TokenValidationParameters
{
ValidateAudience=false,
validateisuer=false,
ValidateSuersigningKey=true,
IssuerSigningKey=new-SymmetricSecurityKey(Encoding.UTF8.GetBytes(“AnythingYouWant”),
ValidateLifetime=true,
ClockSkew=时间跨度从分钟(5)
};
options.SaveToken=true;
options.Events=newjwtbearerevents()
{
OnTokenValidated=上下文=>
{
var accessToken=context.SecurityToken作为JwtSecurityToken;
if(accessToken!=null)
{
ClaimsIdentity identity=context.Principal.identity作为ClaimsIdentity;
如果(标识!=null)
{
AddClaim(新声明(“access_token”,accessToken.RawData));
}
}
返回Task.CompletedTask;
}
};
});
services.AddAuthorization();
}
public void配置(IApplicationBuilder应用程序、IWebHostEnvironment环境、iLogger工厂)
{
if(env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseBrowserLink();
}
其他的
{
app.UseExceptionHandler(“/Home/Error”);
}
app.UseSwagger();
app.UseSwaggerUI(c=>
{
c、 SwaggerEndpoint(“/swagger/”+Configuration[“v1”]+“/swagger.json”,Configuration[“Sports”]);
});
app.UseStaticFiles();
app.UseRouting();
app.UseCors();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(端点=>
{
MapControllerOute(“默认值”,“{controller=Home}/{action=Index}/{id?}”);
端点.MapControllerRoute(“swagger”、“swagger/”);
});
app.UseWelcomePage(“/swagger”);
}
令牌由我的一个api端点生成。该代码如下所示:

 [HttpPost("SportApi/Token")]
    [ServiceFilter(typeof(SportResourceFilter))]
    public IActionResult Create(string key)
    {
       return new ObjectResult(GenerateToken(key));
    }
 private string GenerateToken(string someKey)
    {
        JwtSecurityToken token = new JwtSecurityToken();
        List<SportAPIKey> ro = new List<SportAPIKey>();

        if (!string.IsNullOrEmpty(someKey))
        {

            using (StreamReader r = new StreamReader("keys.json"))
            {
                string json = r.ReadToEnd();
                ro = JsonConvert.DeserializeObject<List<SportAPIKey>>(json);
            }
            
            if (ro.Exists(sak => sak.SportAPIKeyValue.Equals(someKey)))
            {
                SportAPIKey sportapikey = ro.Find(sak => sak.SportAPIKeyValue.Equals(someKey));
                List<Claim> lc = new List<Claim>();
                Claim claimClient = new Claim(ClaimTypes.Name, sportapikey.Client);
                lc.Add(claimClient);
                foreach (string team in sportapikey.Teams)
                    {
                        lc.Add(new Claim(ClaimTypes.System, team.Trim()));
                    }
                Claim claimEffDate = new Claim(JwtRegisteredClaimNames.Nbf, new DateTimeOffset(DateTime.Now).ToUnixTimeSeconds().ToString());
                lc.Add(claimEffDate);
                int tokenLifespan = 60;
                Claim claimExpDate = new Claim(JwtRegisteredClaimNames.Exp, new DateTimeOffset(DateTime.Now.AddDays(tokenLifespan)).ToUnixTimeSeconds().ToString());
                lc.Add(claimExpDate);

                foreach (string sport in sportapikey.Sports.Split(","))
                {
                    lc.Add(new Claim(ClaimTypes.Role, sport.Trim()));
                }

                var claims = lc.ToArray();
                
                token = new JwtSecurityToken(
                    new JwtHeader(new SigningCredentials(
                        new SymmetricSecurityKey(Encoding.UTF8.GetBytes("AnythingYouWant")),
                                                 SecurityAlgorithms.HmacSha256)),
                    new JwtPayload(claims));
            }
        }

        return new JwtSecurityTokenHandler().WriteToken(token);
    }
[HttpPost(“SportApi/Token”)]
[ServiceFilter(类型(SportResourceFilter))]
公共IActionResult创建(字符串键)
{
返回新的ObjectResult(GenerateToken(key));
}
私有字符串GenerateToken(字符串someKey)
{
JwtSecurityToken=新的JwtSecurityToken();
List ro=新列表();
如果(!string.IsNullOrEmpty(someKey))
{
使用(StreamReader r=newstreamreader(“keys.json”))
{
字符串json=r.ReadToEnd();
ro=JsonConvert.DeserializeObject(json);
}
如果(ro.Exists(sak=>sak.SportAPIKeyValue.Equals(someKey)))
{
SportAPIKey SportAPIKey=ro.Find(sak=>sak.SportAPIKeyValue.Equals(someKey));
列表lc=新列表();
Claim claimClient=新索赔(ClaimTypes.Name,sportapikey.Client);
立法会:增补(客户要求);;
foreach(sportapikey.Teams中的字符串团队)
{
lc.Add(新索赔(ClaimTypes.System,team.Trim());
}
Claim claimEffDate=new Claim(JwtRegisteredClaimNames.Nbf,new DateTimeOffset(DateTime.Now).ToUnixTimeSeconds().ToString());
立法会增补(claimEffDate);
寿命=60;
Claim claimExpDate=new Claim(JwtRegisteredClaimNames.Exp,new DateTimeOffset(DateTime.Now.AddDays(tokenLifespan)).ToUnixTimeSeconds().ToString());
立法会增补(claimExpDate);
foreach(sportapikey.Sports.Split(“,”)中的字符串运动)
{
lc.Add(新索赔(ClaimTypes.Role,sport.Trim());
}
var索赔=lc.ToArray();
令牌=新的JwtSecurityToken(
新JwtHeader(新签名凭证(
新的SymmetricSecurityKey(Encoding.UTF8.GetBytes(“AnythingYouWant”),
SecurityAlgorithms.HmacSha256)),
新的JWT有效载荷(索赔);
}
}
返回新的JwtSecurityTokenHandler
  "nbf": "1617977851",
  "exp": "1623161856",
new Claim(JwtRegisteredClaimNames.Exp, 
          new DateTimeOffset(DateTime.Now.AddDays(tokenLifespan)).ToUnixTimeSeconds().ToString(), 
          ClaimValueTypes.Integer64)
public JwtSecurityToken (string issuer = default, string audience = default, System.Collections.Generic.IEnumerable<System.Security.Claims.Claim> claims = default, DateTime? notBefore = default, DateTime? expires = default, Microsoft.IdentityModel.Tokens.SigningCredentials signingCredentials = default);