public static Models.Token GetToken(int userId) { string token = Guid.NewGuid().ToString(); DateTime issuedOn = DateTime.Now; DateTime expiredOn = DateTime.Now.AddSeconds(Convert.ToDouble(600)); //DateTime expiredOn = DateTime.Now.AddSeconds(Convert.ToDouble(ConfigurationManager.AppSettings["AuthTokenExpiry"])); var tokendomain = new Models.Token { UserID = userId, Issued_On = issuedOn, Expires_On = expiredOn, AuthToken = token, }; //_unitOfWork.TokenRepository.Insert(tokendomain); //_unitOfWork.Save(); //var tokenModel = new TokenEntity() //{ // UserID = userId, // AuthToken = token, // Issued_On = issuedOn, // Expires_On = expiredOn //}; return(tokendomain); }
//Token üretecek metot. public MobileApp.Models.Token CreateAccessToken(TblUser user) { Models.Token tokenInstance = new Models.Token(); //Security Key'in simetriğini alıyoruz. SymmetricSecurityKey securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["Token:SecurityKey"])); //Şifrelenmiş kimliği oluşturuyoruz. SigningCredentials signingCredentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256); //Oluşturulacak token ayarlarını veriyoruz. tokenInstance.Expiration = DateTime.Now.AddDays(30); JwtSecurityToken securityToken = new JwtSecurityToken( issuer: Configuration["Token:Issuer"], audience: Configuration["Token:Audience"], expires: tokenInstance.Expiration, //Token süresini 5 dk olarak belirliyorum notBefore: DateTime.Now, //Token üretildikten ne kadar süre sonra devreye girsin ayarlıyouz. signingCredentials: signingCredentials ); //Token oluşturucu sınıfında bir örnek alıyoruz. JwtSecurityTokenHandler tokenHandler = new JwtSecurityTokenHandler(); //Token üretiyoruz. tokenInstance.AccessToken = tokenHandler.WriteToken(securityToken); //Refresh Token üretiyoruz. tokenInstance.RefreshToken = CreateRefreshToken(); return(tokenInstance); }
public async Task <TokenViewModel> GetToken(AuthenticationModel model) { var user = _context.Users.FirstOrDefault(x => x.Password == model.Password && x.Email == model.Email); if (user == null) { return(null); } var claims = new List <Claim> { new Claim(JwtRegisteredClaimNames.Sub, model.Email), new Claim(JwtRegisteredClaimNames.Jti, await _jwtAuthConfig.JtiGenerator()), new Claim(JwtRegisteredClaimNames.Iat, ToUnixEpochDate(_jwtAuthConfig.IssuedAt).ToString(), ClaimValueTypes.Integer64) }; var token = new Models.Token { AccessToken = GenerateToken(claims), RefreshToken = GenerateRefreshToken(), ExpiredIn = _jwtAuthConfig.Expiration, UserId = user.Id }; _context.Tokens.Add(token); var result = _context.SaveChanges(); return(new TokenViewModel { AccessToken = token.AccessToken, RefreshToken = token.RefreshToken, ExpiresIn = (int)_jwtAuthConfig.ValidFor.TotalSeconds }); }
private static void SaveToken(Models.Token token) { string tokenString = JsonConvert.SerializeObject(token); File.WriteAllText(TokenPath, tokenString); Console.WriteLine($"Token: {tokenString}"); }
//private static readonly IUserService UserService = ServiceProviderHelper.Current.GetService<IUserService>(); public static Models.Token CreateToken(Guid id, string displayName) { var claims = new List <Claim> { new Claim(ClaimTypes.Sid, id.ToString()), new Claim(ClaimTypes.Name, displayName) }; var token = new JwtSecurityToken( Const.Jwt.Issuer, Const.Jwt.Audience, claims, DateTime.UtcNow, DateTime.UtcNow + Const.Jwt.TokenLifetime, new SigningCredentials(SecretKey, SecurityAlgorithms.HmacSha256) ); string refreshToken = Guid.NewGuid().ToString().Replace("-", "") + "." + id; var accessToken = new Models.Token { AccessToken = Handler.WriteToken(token), Type = "bearer", RefreshToken = refreshToken, Expires = token.ValidTo }; return(accessToken); }
public override IViewModel GenerateToken(Account owner, string code) { Console.WriteLine($"SpotifyService(GenerateSpotifyToken): The user code is {code}"); var result = _spotifyWrapper.GenerateSpotifyToken(code); if (!result.Success) { Console.WriteLine("SpotifyService(GenerateSpotifyToken): Failed to get token"); return(new ErrorViewModel() { Error = (result as RequestFailedModel).Error }); } SpotifyTokenModel tokenModel = result as SpotifyTokenModel; var token = new Models.Token() { AccessToken = tokenModel.Access_Token, RefreshToken = tokenModel.Refresh_Token, ExpireIn = tokenModel.Expires_In, Type = ServiceTypeEnum.Spotify }; _context.Tokens.Add(token); owner.Tokens.Add(token); _context.Update(owner); _context.SaveChanges(); Console.WriteLine("SpotifyService(GenerateSpotifyToken): Token successfully saved"); return(new SuccessViewModel()); }
public static void SetToken(Models.Token token) { using (CycloidContext context = new CycloidContext()) { context.Token.Add(token); context.SaveChanges(); } }
public IActionResult Refresh(Models.Token token) { if (token is null) { return(BadRequest("Invalid client request")); } string accessToken = token.AccessToken; string refreshToken = token.RefreshToken; var principal = GetPrincipalFromExpiredToken(accessToken); var username = principal.Identity.Name; //this is mapped to the Name claim by default var ConnectionStringLocal = _configuration.GetValue <string>("ServidorAzure"); using (APIUsers.Library.Interfaces.IUser User = APIUsers.Library.Interfaces.Factorizador.CrearConexionServicio(APIUsers.Library.Models.ConnectionType.MSSQL, ConnectionStringLocal)) { APIUsers.Library.Models.User objusr = User.CheckRefreshToken(username); if (objusr == null || objusr.RefreshToken != refreshToken || objusr.RefreshTokenExpiryTime <= DateTime.Now) { return(BadRequest("Invalid client request")); } var secretKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration.GetValue <string>("SecretKey"))); var signinCredentials = new SigningCredentials(secretKey, SecurityAlgorithms.HmacSha256); var tokeOptions = new JwtSecurityToken( issuer: "https://api03mtw102.azurewebsites.net", audience: "https://api03mtw102.azurewebsites.net", claims: principal.Claims, expires: DateTime.Now.AddMinutes(120), signingCredentials: signinCredentials ); var tokenString = new JwtSecurityTokenHandler().WriteToken(tokeOptions); var refreshString = GenerateRefreshToken(); objusr.RefreshToken = refreshString; objusr.RefreshTokenExpiryTime = DateTime.Now.AddDays(7); using (APIUsers.Library.Interfaces.IUser User2 = APIUsers.Library.Interfaces.Factorizador.CrearConexionServicio(APIUsers.Library.Models.ConnectionType.MSSQL, ConnectionStringLocal)) { User2.UpdateUserRefreshToken(objusr); } return(new ObjectResult(new { Token = tokenString, RefreshToken = refreshString })); } }
public static string Registration(string jsonUser) { Models.User user = JsonConvert.DeserializeObject <Models.User>(jsonUser); DataAccess.User.Registration(user); string token = Guid.NewGuid().ToString(); Models.Token tkn = new Models.Token() { UserId = user.Id, Tkn = token }; DataAccess.Token.SetToken(tkn); return(token); }
private static Models.Token ReadTokenFromFile() { Models.Token token = null; string tokenString = ""; using (var fs = File.OpenRead(TokenPath)) using (var sr = new StreamReader(fs)) { tokenString = sr.ReadToEnd(); token = JsonConvert.DeserializeObject <Models.Token>(tokenString); } Console.WriteLine($"Token: {tokenString}"); return(token); }
//I know I am taking a bit of a leap with what a put is... public Token Put() { var token = new Models.Token(); token.Value = GenerateToken(); if (String.IsNullOrEmpty(token.Value)) { token.Success = false; } else { token.Success = true; } return(token); }
public override Task StoreAsync(string key, IdentityServer3.Core.Models.Token value) { var token = new Models.Token { TokenKey = key, SubjectId = value.SubjectId, ClientId = value.ClientId, JsonCode = ConvertToJson(value), TokenType = (int)_tokenType, Expiry = DateTimeOffset.UtcNow.AddSeconds(value.Lifetime), }; _repo.InsertToken(token); return(Task.FromResult(0)); }
public async Task <IActionResult> Refresh([FromBody] Models.AccessCred cred) { Models.Token token = null; if (cred.Grant_type == "refresh_token") { token = await repo.GetRefreshToken(cred); } if (token == null) { return(BadRequest(new { message = "Refresh token non valido." })); } else { return(Ok(token)); } }
public async Task <IActionResult> Login([FromBody] Models.AccessCred cred) { Models.Token token = null; if (cred.Grant_type == "password") { token = await repo.GetToken(cred); } if (token == null) { return(BadRequest(new { message = "Utente o password non corretti." })); } else { return(Ok(token)); } }
public static string Login(string login, string pass) { string token = ""; var user = DataAccess.User.Login(login, pass); if (user == null) { token = "Invalid login or password"; } else { token = Guid.NewGuid().ToString(); Models.Token tkn = new Models.Token() { UserId = user.Id, Tkn = token }; DataAccess.Token.SetToken(tkn); } return(token); }
/// <summary> /// 获取微信TOKEN /// </summary> /// <returns></returns> public static async Task <string> GetTokenAsync(IConfiguration configuration, IMemoryCache cache) { string access_token; if (!cache.TryGetValue("WeiXinToken", out access_token)) { string url = configuration["GetToken"]; Models.Token token = await HttpHelper.GetAsync <Models.Token>(url, null); var log = LogManager.GetLogger(Startup.loggerRepository.Name, "GetToken"); log.Error($"获取TOKEN:{Newtonsoft.Json.JsonConvert.SerializeObject(token)}"); if (token != null && !string.IsNullOrEmpty(token.access_token) && token.access_token != "null") { access_token = token.access_token; var cacheEntryOptions = new MemoryCacheEntryOptions().SetSlidingExpiration(TimeSpan.FromSeconds(token.expires_in > 0 ? token.expires_in : 60)); cache.Set("WeiXinToken", token.access_token, cacheEntryOptions); } } return(access_token); }
private void GravaLoja(Models.Token obj, string nome, string senha) { string strquery = "Select count(*) FROM loja where MasterID = " + obj.masterid; bool tem = Convert.ToInt32(Dados.ExecutaSQLScalar(strquery)) > 0; if (tem) { strquery = "UPDATE loja SET Nome=@nome,Senha=@senha,Token=@token,Expira=@expira WHERE MasterID=@masterID"; } else { strquery = "INSERT INTO loja (Nome,Senha,MasterID,Token,Expira)Values(@nome,@senha,@masterID,@token,@expira)"; } IDbDataParameter p1 = Dados.GetParameter("@nome", nome); IDbDataParameter p2 = Dados.GetParameter("@senha", senha); IDbDataParameter p3 = Dados.GetParameter("@masterID", obj.masterid); IDbDataParameter p4 = Dados.GetParameter("@token", obj.access_token); IDbDataParameter p5 = Dados.GetParameter("@expira", obj.DataExpira.ToString()); Dados.ExecutaSQLNonQuery(strquery, p1, p2, p3, p4, p5); }
public ViewModel.loginResponseVM Login(string nationalityCode, string password) { string hashed = hashPassword(password); Models.User user = _db.Users.FirstOrDefault(p => p.Password == hashed && p.NationalityCode == nationalityCode); if (user == null) { return(null); } var token = new Models.Token() { CreateDate = DateTime.Now, UserId = user.Id, Token1 = Guid.NewGuid(), ExpiredDate = DateTime.Now.AddDays(10) }; _db.Tokens.Add(token); _db.SaveChanges(); return(new ViewModel.loginResponseVM() { token = token.Token1, DisplayName = user.FirstName + " " + user.LastName }); }
public override Task StoreAsync(string key, RefreshToken value) { var token = _repo.GetToken(key, (int)_tokenType); if (token == null) { token = new Models.Token { TokenKey = key, SubjectId = value.SubjectId, ClientId = value.ClientId, JsonCode = ConvertToJson(value), TokenType = (int)_tokenType, Expiry = value.CreationTime.AddSeconds(value.LifeTime) }; _repo.InsertToken(token); return(Task.FromResult(0)); } token.Expiry = value.CreationTime.AddSeconds(value.LifeTime); _repo.UpdateTokenExpiry(key, token.Expiry); return(Task.FromResult(0)); }
private async Task <Models.Token> CreateToken(int userID, int roleId, string refTokenOld) { Models.Token token = null; // Creo il token Services.JwtHandler jwt = new Services.JwtHandler(); { token = jwt.CreateToken(userID, roleId); } // Pulizia token scaduti await ClearTokenExpired(userID); // Controllo se eliminare il token precedente if (refTokenOld.Length > 0) { await DeleteRefreshToken(refTokenOld); } // Memorizzo il refreshToken Models.RefreshToken refT = new Models.RefreshToken { DateIssued = DateTime.Now, DateExpires = DateTime.Now.AddDays(30), // 1 Mese Refresh_token = token.Refresh_token, UserId = userID }; await SaveRefreshToken(refT); // ----------------- return(token); }
/// <summary> /// Valida para ver se o e-mail e a senha digitada pelo lojista é valido /// </summary> /// <param name="usuario">E-mail de acesso do usuário master</param> /// <param name="senha">Senha</param> /// <returns>ID do usuário Master, se devolver zero indica que os dados não conferem</returns> public int checkStore(string usuario, string senha) { string token = GetToken(usuario, senha); bool erro = token.IndexOf("error") >= 0; if (erro) { return(0); } else { JavaScriptSerializer serializer = new JavaScriptSerializer(); Models.Token obj = serializer.Deserialize <Models.Token>(token); int masterID = Utils.Valida.LimpaString(obj.masterid); obj.DataExpira = DateTime.Now.AddSeconds(obj.expires_in); obj.masterid = masterID.ToString(); //Grava ou atualiza os dados no sqlite GravaLoja(obj, usuario, senha); return(masterID); } }
public override void OnActionExecuting(HttpActionContext actionContext) { var currentcontext = HttpContext.Current; var token = currentcontext.Request.Headers["Authorization"]; if (token != null) { string t = token.Replace("Bearer ", ""); token = t; } string ip = GetClientIpAddress(actionContext.Request); bool valid = false; if (token != null) { Models.Token Token = new Models.Token(); //============================================================= //-------------- Get Token From DataBase ----- #region Get Token From DataBase ConnectionString constr = new ConnectionString(); ConnectionString = constr.GetConnectionString(); // 1. Instantiate the connection SqlConnection conn = new SqlConnection(ConnectionString); SqlDataReader rdr = null; try { if (conn.State == ConnectionState.Closed) { conn.Open(); } SqlCommand cmd = new SqlCommand(@"select * from Token Where TokenCode like @TokenCode and Valid =1 ", conn); cmd.Parameters.Add(new SqlParameter("@TokenCode", SqlDbType.NVarChar)); cmd.Parameters["@TokenCode"].Value = token; //cmd.Parameters.Add(new SqlParameter("@IP", SqlDbType.NVarChar,50)); //cmd.Parameters["@IP"].Value = ip; rdr = cmd.ExecuteReader(); DataTable dataTable = new DataTable(); dataTable.Load(rdr); if (dataTable != null) { if (dataTable.Rows.Count > 0) { DataRow dr = dataTable.Rows[0]; Token.Date = dr["Date"].ToString() != "" ? DateTime.Parse(dr["Date"].ToString()) :(DateTime?)null; Token.id = Int64.Parse(dr["id"].ToString()); Token.TokenCode = dr["TokenCode"].ToString(); //================================================= //----------------- Check Token Is Valid -- #region Check Token Is Valid DateTime TokenDate = DateTime.Parse(Token.Date.ToString()); DateTime Tommorow = DateTime.Now; DateTime OneDayafterTokenDate = TokenDate.AddDays(1); if (OneDayafterTokenDate > Tommorow) { valid = true; } else { //----- token Expired cmd = new SqlCommand(@"update Token set Valid=0 where TokenCode like @TokenCode", conn); cmd.Parameters.Add(new SqlParameter("@TokenCode", SqlDbType.NVarChar)); cmd.Parameters["@TokenCode"].Value = token; cmd.ExecuteNonQuery(); } #endregion //----------------- Check Token Is Valid -- //================================================= } } if (rdr != null) { rdr.Close(); rdr = null; } if (conn.State != ConnectionState.Closed) { conn.Close(); } } catch (Exception ex) { if (rdr != null) { rdr.Close(); rdr = null; } if (conn.State != ConnectionState.Closed) { conn.Close(); } } #endregion //-------------- Get Token From DataBase ----- //============================================================= } if (!valid) { var msg = new HttpResponseMessage(HttpStatusCode.Unauthorized) { ReasonPhrase = "Request Is Not Valid!!!" }; throw new HttpResponseException(msg); } base.OnActionExecuting(actionContext); }
private void LoginButtonClicked(object sender, RoutedEventArgs routedEvent) { AccountActivate.IsRegister = false; CreateLoginFromInputData(); if (ValidateDataLogin()) { string passwordEncryption = Utils.Security.Encrypt(login.password); login.password = passwordEncryption; string urlBase = "http://127.0.0.1:5000/"; RestClient client = new RestClient(urlBase); client.Timeout = -1; var request = new RestRequest("logins", Method.POST); var json = JsonConvert.SerializeObject(login); request.AddParameter("application/json", json, ParameterType.RequestBody); System.Net.ServicePointManager.ServerCertificateValidationCallback = (senderX, certificate, chain, sslPolicyErrors) => { return(true); }; try { IRestResponse response = client.Execute(request); if (response.StatusCode == System.Net.HttpStatusCode.Created || response.StatusCode == System.Net.HttpStatusCode.OK) { Models.Token token = JsonConvert.DeserializeObject <Models.Token>(response.Content); cookies = response.Cookies; tokenAccount = token; loginAccount = login; if (token.memberATEType == Number.NumberValue(NumberValues.TWO)) { ChooseAccount chooseAccount = new ChooseAccount(); chooseAccount.InitializeHome(); chooseAccount.Show(); Close(); } else { if (token.memberATEType == Number.NumberValue(NumberValues.THREE)) { HomeManager home = new HomeManager(); home.Show(); Close(); } else { HomeClient home = new HomeClient(); home.InitializeMenu(); home.Show(); Close(); } } } else { Models.Error responseError = JsonConvert.DeserializeObject <Models.Error>(response.Content); MessageBox.Show(responseError.error, "Error", MessageBoxButton.OK, MessageBoxImage.Error); } } catch (Exception exception) { TelegramBot.SendToTelegram(exception); LogException.Log(this, exception); MessageBox.Show(exception.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error); } } else { MessageBox.Show("Por favor, Ingrese datos correctos en los campos marcados en rojo", "Datos Incorrectos", MessageBoxButton.OK, MessageBoxImage.Warning); } }
private static void Client_OnTokenUpdated(object sender, Models.Token e) { SaveToken(e); }
private static void Main(string[] args) { token = File.Exists(TokenPath) ? ReadTokenFromFile() : GenerateAndSaveToken(); //token = GenerateAndSaveToken(); proxy = GetProxy(); int option = 0; while (option != -1) { Console.WriteLine("0. Register Printer"); Console.WriteLine("1. Get Printer"); Console.WriteLine("2. Update Printers"); Console.WriteLine("3. Delete Printer"); Console.WriteLine("4. Fetch and download print job"); Console.WriteLine("5. Share Printer"); Console.WriteLine("6. Unshare Printer"); Console.WriteLine("7. Test Only"); Console.WriteLine("8. Xmpp Testing"); Console.Write("Select an operation: "); if (int.TryParse(Console.ReadLine(), out option)) { switch (option) { case 0: RegisterPrinter(); break; case 1: ListAndGetPrinter(); break; case 2: UpdatePrinter(); break; case 3: DeletePrinter(); break; case 4: FetchJob(); break; case 5: SharePrinter(); break; case 6: UnsharePrinter(); break; case 7: Test(); break; case 8: XmppTest(); break; } } else { Console.WriteLine("Please input a number!"); } Console.WriteLine("Press \"Enter\" to continue..."); Console.ReadLine(); Console.Clear(); } Console.ReadLine(); }
public static bool IsKeyword(this Models.Token token) => (token.tokenType == Models.TokenType.Keyword);
public static bool IsKeyword(this Models.Token token, string keyword) => (token.tokenType == Models.TokenType.Keyword && token.tokenValue == keyword);
public static bool IsSemicolon(this Models.Token token) => (token.tokenType == Models.TokenType.Operator && token.tokenValue == ";");
public static bool IsOperator(this Models.Token token, string symbol) => (token.tokenType == Models.TokenType.Operator && token.tokenValue == symbol);