如何为使用 Swagger 创建的不记名令牌设置 expiresIn 值

问题描述 投票:0回答:1

我目前正在从头开始编写我的第一个 Web API。多年来我修改了大量其他 API,但这是我第一次必须构建一个 API(除了修改教程之外)。我正在使用 ASP.Net Core 8。

按照 https://www.youtube.com/watch?v=8J3nuUegtL4 上的精彩教程,我很快就设置了身份验证。令人兴奋!

但是,这种方法总是给我一个

expiresIn
值 3600。有没有办法改变这个值?我在网上看到很多关于设置 JWT 过期的信息,但这似乎需要我删除我在教程中所做的很多内容并重试。

这是我的 Program.cs 中的代码:

public static void Main(string[] args)
{
    var builder = WebApplication.CreateBuilder(args);
    builder.Logging.ClearProviders();
    builder.Logging.AddLog4Net();

    // Add services to the container.

    builder.Services.AddControllers();
    // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
    builder.Services.AddEndpointsApiExplorer();
    builder.Services.AddSwaggerGen(options =>
    {
        options.AddSecurityDefinition("oauth2", new OpenApiSecurityScheme
        {
            In = ParameterLocation.Header,
            Name = "Authorization",
            Type = SecuritySchemeType.ApiKey
        });

        options.OperationFilter<SecurityRequirementsOperationFilter>();
    });

    builder.Services.AddDbContext<DataContext>(options =>
        options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")));

    builder.Services.AddAuthorization();

     builder.Services.AddIdentityApiEndpoints<IdentityUser>()
        .AddEntityFrameworkStores<DataContext>();

    var app = builder.Build();

    // Configure the HTTP request pipeline.
    if (app.Environment.IsDevelopment() || app.Environment.IsProduction())
    {
        app.UseSwagger();
        app.UseSwaggerUI();
    }

    app.MapIdentityApi<IdentityUser>();

    // We enforce HTTPS on WAF.  Enforcing it here as well causes a redirect loop.
    //app.UseHttpsRedirection();

    app.UseAuthorization();


    app.MapControllers();

    app.Run();
}

谢谢!

asp.net-core asp.net-core-webapi bearer-token swagger-codegen
1个回答
0
投票

好吧,经过六个小时的苦心钻研,我想我终于找到了答案——与实现这一目标所付出的努力相比,这个解决方案是相当小的。

builder.Services.ConfigureAll<BearerTokenOptions>(option =>
{
    option.BearerTokenExpiration = TimeSpan.FromDays(1);
});

这是

builder.Services.AddIdentityApiEndpoints<IdentityUser>().AddEntityFrameworkStores<DataContext>();
之后。

现在我可以使用

TimeSpan
设置我喜欢的任何时间长度(至少长达一年,这是我尝试过的最长的时间)。

© www.soinside.com 2019 - 2024. All rights reserved.