[英].net core 2.0 JWT token expired issue
我遇到一個非常奇怪的問題,這確實使我發瘋,對我沒有任何意義。
讓我解釋一下:我有一個Angular 5客戶端正在使用的.NET Core 2.0 Web API。 Web API托管在Azure AppService中。 通過使用AspnetCore.Authentication.JWTBearer的JWT Bearer令牌進行身份驗證(當前版本為2.0.1),該應用程序在auth / login端點中創建JWT令牌。 這樣客戶端就可以在以下調用中進行身份驗證了。
但是,即使我指定了令牌的時間跨度為1080分鍾(一周),但在大約8小時后,我們還是可以說該令牌不再有效。 我可以不說了(實際上我開始指定令牌可以使用幾個小時),但是一旦令牌過期……這就是奇怪的地方,應用程序在用戶使用后發出了一個新令牌。再次登錄,但是新令牌不進行身份驗證,說明令牌已過期!如果剛剛創建了令牌,如何將其過期。 (我將檢查加倍,並且將新接收到的令牌發送到服務器,而不是舊令牌)。
此外,如果我只是在Azure中重新啟動應用程序服務,那么一切將再次恢復正常,並且將接受新發行的jwt令牌。 我認為這可能是有關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://docs.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類,它將帶有令牌的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屬性是靜態的,並且是第一次使用生成的令牌值。 當令牌過期時,會生成一個新令牌,但會采用第一個令牌的issueAtAt日期,這就是為什么所有新生成的令牌都已過期的原因。 在Azure中重新啟動AppService導致清除了靜態值,並正確創建了第一個新令牌。
這是正確的行。
public DateTime IssuedAt => DateTime.UtcNow;
謝謝你的幫助!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.