netcore 用户阻止重复登录 互踢
public class RestrictUserMiddleware { public readonly RequestDelegate _next; private ILogger _logger; public ICacheService cacheService; public RestrictUserMiddleware(RequestDelegate next, ILogger<GlobalExceptionCatchMiddleware> logger, IServiceProvider service) { _next = next; _logger = logger; cacheService = (MemoryCacheService)service.GetService(typeof(MemoryCacheService)); } public async Task Invoke(HttpContext context) { var user = context.User.Claims.Where(i => i.Type == ConfigHelper.Claim_UserName).FirstOrDefault(); var path = context.Request.Path.Value; //呼叫端用户互踢处理 if (user != null && path.Contains("xxxxService/CallingClient")) { var token = context.Request.Headers["Authorization"].ToString(); var username = user.Value; if (cacheService.Exists(username)) { var c_token = cacheService.GetValue(username); var exists = cacheService.Exists(token); if (exists) { context.Response.Clear(); context.Response.StatusCode = StatusCodes.Status200OK; var responseResult = ResponseResult<object>.Expire("Expire"); var responseStr = JsonConvert.SerializeObject(responseResult, Formatting.None, new JsonSerializerSettings { ContractResolver = new Newtonsoft.Json.Serialization.CamelCasePropertyNamesContractResolver() }); context.Response.ContentType = "application/json;charset=utf-8"; await context.Response.WriteAsync(responseStr); } else if (token != c_token) { cacheService.Add(c_token, 1); cacheService.Add(username, token); } } else { cacheService.Add(username, token); } } await _next(context); } }
public void Configure(IApplicationBuilder app, IWebHostEnvironment env) {//使用Token验证 app.UseAuthentication(); app.UseAuthorization(); app.UseRestrictUserMiddleware();
}
cache记录token,旧token,则阻止防护正确结果