public string GenerateKey(string userId, string username, bool isAdmin = false, string facebookToken = null) { int ttl = int.Parse(ConfigurationManager.AppSettings["TokenTTL"]); long exp = DateTimeOffset.UtcNow.ToUnixTimeSeconds() + 60 * ttl; long iat = DateTimeOffset.UtcNow.ToUnixTimeSeconds(); var payload = new Dictionary <string, object>() { { "sub", userId }, { "exp", exp }, { "iat", iat }, { "aud", "social network" }, { "username", username }, { "isAdmin", isAdmin } }; string key = ConfigurationManager.AppSettings["tokenSignKey"]; byte[] secretKey = Encoding.ASCII.GetBytes(key); string token = JWT.Encode(payload, secretKey, JwsAlgorithm.HS256); TokenHistory history = new TokenHistory() { Token = token, FacebookToken = facebookToken, UserId = userId, TimeStamp = iat }; _tokenReposirory.Add(history); return(token); }
//Private Methods private void AddToTokenHistory(string userId, string token) { TokenHistory tokenHistory = new TokenHistory() { UserId = userId, TimeStamp = (long)(DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalSeconds, Token = token }; try { _dynamo.Store(tokenHistory); } catch (Exception) { throw new FaildToConnectDbException(); } }
public async Task <dynamic> Login(object data) // username and password(MD5-ed) { return(await Task.Run(() => { dynamic inData = data.ToDynamicObject(); string username = inData.username; string password = inData.password; var user = _userAccountRepo.First(p => p.UserName.Equals(username) && p.Password.Equals(password)); if (user != null) { long now = DateTime.Now.Ticks; var token = _tokenHistory.Where(p => p.UserName.Equals(username) && p.ExpireDate > now).OrderByDescending(p => p.ExpireDate).FirstOrDefault(); if (token != null) { dynamic res = new ExpandoObject(); res.username = username; res.token = token.Token; return res; } else { TokenHistory th = new TokenHistory(); th.Id = Guid.NewGuid(); th.Token = Guid.NewGuid(); th.ExpireDate = DateTime.Now.AddDays(EXPIRE_DAY).Ticks; th.CreatedDate = DateTime.Now.Ticks; th.UserName = username; _tokenHistory.Insert(th); dynamic res = new ExpandoObject(); res.username = username; res.token = th.Token; return res; } } return null; })); }