在.NET Core自带的Angular模板项目中,我想要做一个简单的登录认证。
所以想填写用户名密码,使用guid作为key,存储登录信息,每次页面刷新的时候check它。
思路觉得没有问题,但是一直失效,修改前代码:
1 public class AuthController : Controller 2 { 3 private readonly IMemoryCache _cache; 4 public AuthController(IMemoryCache cache) 5 { 6 _cache = cache; 7 } 8 [HttpPost] 9 public IActionResult Post([FromBody]LoginModel model) 10 { 11 if (model != null && model.UserName == "xxxxx" && model.Password == "yyyyyyy") 12 { 13 var token = Guid.NewGuid(); 14 var cacheEntryOptions = new MemoryCacheEntryOptions() 15 .SetPriority(CacheItemPriority.NeverRemove) 16 .SetSlidingExpiration(TimeSpan.FromDays(7)); 17 _cache.Set(token, model, cacheEntryOptions); 18 return Ok(new { success = true, token = token, model= _cache.Get<LoginModel>(token) }); 19 } 20 return Ok(new { success = false, error = "UserName or Password error." }); 21 } 22 [HttpGet("check/{token}")] 23 public IActionResult Check(string token) 24 { 25 var model = _cache.Get<LoginModel>(token); 26 if (model != null && model.UserName == "xxxxx" && model.Password == "yyyyyyy") 27 { 28 return Ok(new { success = true, model }); 29 } 30 return Ok(new { success = false, model }); 31 } 32 33 public class LoginModel 34 { 35 public string UserName { get; set; } 36 public string Password { get; set; } 37 } 38 }
但是在调用check的api时,就是找不到。
后来发现在set的地方,guid没有ToString,所以导致两次使用过的key不一样。
修改后:
1 [Route("api/auth")] 2 public class AuthController : Controller 3 { 4 private readonly IMemoryCache _cache; 5 public AuthController(IMemoryCache cache) 6 { 7 _cache = cache; 8 } 9 [HttpPost] 10 public IActionResult Post([FromBody]LoginModel model) 11 { 12 if (!model.IsValidUserInfo()) 13 return Ok(new { success = false, error = "UserName or Password error." }); 14 var token = Guid.NewGuid().ToString(); 15 var cacheEntryOptions = new MemoryCacheEntryOptions() 16 .SetPriority(CacheItemPriority.NeverRemove) 17 .SetSlidingExpiration(TimeSpan.FromDays(7)); 18 _cache.Set(token, model, cacheEntryOptions); 19 return Ok(new { success = true, token = token }); 20 } 21 [HttpGet("check/{token}")] 22 public IActionResult Check(string token) 23 { 24 var model = _cache.Get<LoginModel>(token); 25 return Ok(new { success = model.IsValidUserInfo() }); 26 } 27 28 public class LoginModel 29 { 30 public string UserName { get; set; } 31 public string Password { get; set; } 32 } 33 } 34 35 public static class extController 36 { 37 public static bool IsValidUserInfo(this AuthController.LoginModel me) 38 => me != null && me.UserName == "xxxx" && me.Password == "yyyy"; 39 }
注:多加了一个扩展方法,验证登录信息。