public JWTService(IAuthContainerModel model) { if (model is null) { throw new ArgumentException($"'{nameof(model)}' cannot be null", nameof(model)); } Model = model; }
public JWTService(IAuthContainerModel model) { if (model is null || model.Claims is null || model.Claims.Length == 0) { throw new ArgumentException($"'{nameof(model)}' cannot be null or empty", nameof(model)); } Model = model; }
public static string GetToken(string name, string phone) { IAuthContainerModel model = getJWTContainerModel(name, phone); IAuthService authService = new JWTService(model.SecretKey); string token = authService.GenerateToken(model); return(token); }
private string _generateRefreshToken(string id, string deviceNumber) { IAuthContainerModel jwtModel = JwtTokenService.GetAuthModel(id, deviceNumber); jwtModel.SecretKey = _secretKeyRefreshToken; jwtModel.ExpireMinutes = 13; IAuthService authService = new JWTService(jwtModel.SecretKey); return(authService.GenerateToken(jwtModel)); }
public HomeController( ILogger <HomeController> logger, IAuthService authService, IConfiguration configuration, IAuthContainerModel authContainerModel) { _logger = logger; _authService = authService; _configuration = configuration; _authContainerModel = authContainerModel; }
public ActionResult <string> LogIn([FromBody] User user) { User tempUser = userProcessor.LogInUser(user.UserName, user.Password); if (tempUser != null) { IAuthContainerModel model = GetJWTContainerModel(tempUser.UserName, tempUser.EmailAddress, tempUser.UserRole); IAuthService authService = new JWTService(clientSettings.Value.SecretKey); return(authService.GenerateToken(model)); } return(BadRequest("Invalid login information was given")); }
private string GenerateToken(IAuthContainerModel model) { SecurityTokenDescriptor securityTokenDescriptor = new SecurityTokenDescriptor { Subject = new ClaimsIdentity(model.Claims), Expires = DateTime.UtcNow.AddMinutes(Convert.ToInt32(model.ExpireMinutes)), SigningCredentials = new SigningCredentials(GetSymmetricSecurityKey(), model.SecurityAlgorithm) }; JwtSecurityTokenHandler jwtSecurityTokenHandler = new JwtSecurityTokenHandler(); SecurityToken securityToken = jwtSecurityTokenHandler.CreateToken(securityTokenDescriptor); return(jwtSecurityTokenHandler.WriteToken(securityToken)); }
public static string CreateJwtToken(string name, string value) { string _value = value; IAuthService authService = new JWTService(); IAuthContainerModel model = GetJWTContainerModel(name, value); string token = authService.GenerateToken(model); if (!string.IsNullOrEmpty(token)) { _value = token; } return(_value); }
public JwtToken(IAuthContainerModel model, string secretKey = "TW9zaGVFcmV6UHJpdmF0ZUtleQ==") { if (model == null) { throw new ArgumentNullException(nameof(model)); } if (model.Claims == null || model.Claims.Length == 0) { throw new ArgumentException("Invalid model"); } this.secretKey = secretKey ?? throw new ArgumentNullException(nameof(secretKey)); token = GenerateToken(model); }
public List <SIS.Entity.Entities.Admin.ApplicationServer> get_List_ApplicationServer_UserCode(GetValue _GetValue) { using (var _db = new SIS.DataAccess.Admin.AdminListContext(_GetValue.ConStr)) { string _sql = Helper.get_sql_ApplicationServer(_GetValue.Id.Value, _GetValue.IdStr, _GetValue.IdStr2); List <ApplicationServer> _return = _db.Database.SqlQuery <ApplicationServer>(_sql).ToList(); IAuthService authService = new JWTService(); foreach (ApplicationServer _ApplicationServer in _return) { _ApplicationServer.Password = get_SqlPassword_Local(_ApplicationServer.Password); _sql = $"Select * from ApplicationDatabase with (nolock) Where ApplicationId = { _GetValue.Id} And ServerId = {_ApplicationServer.Id} "; _ApplicationServer.ApplicationDatabase = _db.Database.SqlQuery <ApplicationDatabase>(_sql).ToList(); foreach (ApplicationDatabase _ApplicationDatabase in _ApplicationServer.ApplicationDatabase) { string connection = ""; string invoiceConnection = ""; if (_ApplicationServer.ServerCloude.Value) { connection = $"Server = tcp:{_ApplicationServer.Server},1433; Initial Catalog = {_ApplicationDatabase.DatabaseName}; Persist Security Info = False; User ID = {_ApplicationServer.Username}; Password = {_ApplicationServer.Password}; MultipleActiveResultSets = True; Encrypt = True; TrustServerCertificate = False; Connection Timeout = 30;"; invoiceConnection = $"Server = tcp:{_ApplicationServer.Server},1433; Initial Catalog = SednaEInvoice; Persist Security Info = False; User ID = {_ApplicationServer.Username}; Password = {_ApplicationServer.Password}; MultipleActiveResultSets = True; Encrypt = True; TrustServerCertificate = False; Connection Timeout = 30;"; } else { connection = $"data source= {_ApplicationServer.Server};initial catalog={_ApplicationDatabase.DatabaseName};persist security info=True;user id={_ApplicationServer.Username};password={_ApplicationServer.Password};MultipleActiveResultSets=True;App=EntityFramework"; invoiceConnection = $"data source= {_ApplicationServer.Server};initial catalog=SednaEInvoice;persist security info=True;user id={_ApplicationServer.Username};password={_ApplicationServer.Password};MultipleActiveResultSets=True;App=EntityFramework"; } #region Token IAuthContainerModel model = GetJWTContainerModel("connection", connection); string token = authService.GenerateToken(model); string token2 = authService.GenerateToken(GetJWTContainerModel("connection", invoiceConnection)); connection = token; invoiceConnection = token2; #endregion _ApplicationDatabase.ConnectionString = connection; } } return(_return); } }
public HomeController() { IAuthContainerModel model = GetJwtContainerModel("Nhat", "*****@*****.**"); IAuthService authService = new JwtService(model.SecretKey); string token = authService.GenerateToken(model); if (!authService.IsTokenValid(token)) { throw new UnauthorizedAccessException(); } else { List <Claim> claims = authService.GetTokenClaims(token).ToList(); string name = claims.FirstOrDefault(e => e.Type.Equals(ClaimTypes.Name)).Value; string email = claims.FirstOrDefault(e => e.Type.Equals(ClaimTypes.Email)).Value; } }
public string GenerateToken(IAuthContainerModel model) { SecurityTokenDescriptor securityTokenDescriptor = new SecurityTokenDescriptor { Issuer = "petro.com", Audience = "petro.com", Subject = new ClaimsIdentity(model.Claims), Expires = DateTime.UtcNow.AddSeconds(model.ExpireInterval), SigningCredentials = new SigningCredentials(GetSymmetricSecurityKey(), model.SecurityAlgorithm), }; JwtSecurityTokenHandler jwtSecurityTokenHandler = new JwtSecurityTokenHandler(); SecurityToken securityToken = jwtSecurityTokenHandler.CreateToken(securityTokenDescriptor); string token = jwtSecurityTokenHandler.WriteToken(securityToken); return(token); }
public string GenerateToken(IAuthContainerModel model) { if (model == null || model.Claims == null || model.Claims.Length == 0) throw new ArgumentException("Arguments to create token are not valid."); SecurityTokenDescriptor securityTokenDescriptor = new SecurityTokenDescriptor { Subject = new ClaimsIdentity(model.Claims), Expires = DateTime.UtcNow.AddMinutes(Convert.ToInt32(model.ExpireMinutes)), SigningCredentials = new SigningCredentials(GetSymmetricSecurityKey(), model.SecurityAlgorithm) }; JwtSecurityTokenHandler jwtSecurityTokenHandler = new JwtSecurityTokenHandler(); SecurityToken securityToken = jwtSecurityTokenHandler.CreateToken(securityTokenDescriptor); string token = jwtSecurityTokenHandler.WriteToken(securityToken); return token; }
public string GenerateToken(IAuthContainerModel model) { if (model == null || model.Claims == null || model.Claims.Length == 0) { throw new ArgumentException("Arguments to create token are not valid."); } _securityKey = new SymmetricSecurityKey(_signKey); _credentials = new SigningCredentials(_securityKey, model.SecurityAlgorithm); SecurityTokenDescriptor securityTokenDescriptor = new SecurityTokenDescriptor() { Subject = new ClaimsIdentity(model.Claims), Expires = DateTime.UtcNow.AddMinutes(Convert.ToInt32(model.ExpireMinutes)), SigningCredentials = _credentials }; _securityToken = _handler.CreateToken(securityTokenDescriptor); return(_handler.WriteToken(_securityToken)); }
// [AllowAnonymous] public IHttpActionResult GetToken(string username) { var people = _reader.Value.ReadUserData(); var person = people.Where(x => x.Username.Equals(username, StringComparison.InvariantCultureIgnoreCase)).FirstOrDefault(); if (person == null) { return(NotFound()); } ; IAuthContainerModel model = GetJWTContainerModel(username.ToLower(), person.ID.ToString()); //might remove case sensitivity // IAuthContainerModel model = GetJWTContainerModel("a", "test"); //might remove case sensitivity IAuthService authService = new JWTService(model.SecretKey); string token = authService.GenerateToken(model); return(Ok(token)); }
/// <summary> /// Создает токен для модели. /// Шифрует и возвращает. /// </summary> /// <param name="model"></param> /// <returns></returns> public string GenerateToken(IAuthContainerModel model) { if (model == null || model.Claims == null || model.Claims.Length == 0) { throw new ArgumentException("Недопустимые аргументы для создания токена."); } SecurityTokenDescriptor securityTokenDescriptor = new SecurityTokenDescriptor { Subject = new ClaimsIdentity(model.Claims), Expires = DateTime.UtcNow.AddMinutes(Convert.ToUInt32(model.ExpireMinutes)), SigningCredentials = new SigningCredentials(GetSymmetricSecurityKey(), model.SecurityAlgorithm) }; JwtSecurityTokenHandler jwtSecurityTokenHandler = new JwtSecurityTokenHandler(); SecurityToken securityToken = jwtSecurityTokenHandler.CreateToken(securityTokenDescriptor); string token = jwtSecurityTokenHandler.WriteToken(securityToken); return(token); }
static void Main(string[] args) { IAuthContainerModel model = GetJWTContainerModel("Moshe Binieli", "*****@*****.**"); IAuthService authService = new JWTService(model.SecretKey); string token = authService.GenerateToken(model); if (!authService.IsTokenValid(token)) { throw new UnauthorizedAccessException(); } else { List <Claim> claims = authService.GetTokenClaims(token).ToList(); Console.WriteLine(claims.FirstOrDefault(e => e.Type.Equals(ClaimTypes.Name)).Value); Console.WriteLine(claims.FirstOrDefault(e => e.Type.Equals(ClaimTypes.Email)).Value); } }
public string GenerateToken(IAuthContainerModel model) { if (model == null || model.Claims == null || model.Claims.Length == 0) { throw new Exception("Argumentos da model não são válidos para geração do token."); } var securityTokenDescriptor = new SecurityTokenDescriptor() { Subject = new ClaimsIdentity(model.Claims), Expires = DateTime.UtcNow.AddMinutes((int)model.ExpireMinutes), SigningCredentials = new SigningCredentials(GetSimmetricSecurityKey(), model.SecurityAlgorithm) }; var jwtSecurityTokenHandler = new JwtSecurityTokenHandler(); var securityToken = jwtSecurityTokenHandler.CreateToken(securityTokenDescriptor); var token = jwtSecurityTokenHandler.WriteToken(securityToken); return(token); }
static void Main(string[] args) { IAuthContainerModel model = GetJwtContainerModel("Ilya Gomel", "*****@*****.**"); model.Expires = 8; IAuthService service = new JWTService(model.SecretKey); string token = service.GenerateToken(model); if (!service.IsValid(token)) { throw new UnauthorizedAccessException(); } else { List <Claim> claims = service.GetTokenClaims(token).ToList(); Console.WriteLine(claims.FirstOrDefault(c => c.Type.Equals(ClaimTypes.Name))?.Value); Console.WriteLine(claims.FirstOrDefault(c => c.Type.Equals(ClaimTypes.Email))?.Value); } }
public string GenerateJWTtoken(string name, long cardNumber, string salt) { IAuthContainerModel model = GetJWTContainerModel(name, cardNumber, salt); IAuthService authService = new JWTService(model.SecretKey); string token = authService.GenerateToken(model); if (!authService.IsTokenValid(token)) { throw new UnauthorizedAccessException(); } else { List <Claim> claims = authService.GetTokenClaims(token).ToList(); //Console.WriteLine(claims.FirstOrDefault(e => e.Type.Equals(ClaimTypes.Name)).Value); //Console.WriteLine(claims.FirstOrDefault(e => e.Type.Equals(ClaimTypes.Email)).Value); Console.WriteLine(token); } return(token); }
static void Main(string[] args) { IAuthContainerModel model = GetJWTContainerModel("Harsimran Singh", "*****@*****.**"); IAuthService authService = new JWTService(model.SecretKey); string token = authService.GenerateToken(model); if (!authService.IsTokenValid(token)) { throw new UnauthorizedAccessException(); } else { Console.WriteLine("JSON :\n" + token); Console.WriteLine(); List <Claim> claims = authService.GetTokenClaims(token).ToList(); Console.WriteLine(claims.FirstOrDefault(e => e.Type.Equals(ClaimTypes.GivenName)).Value); Console.WriteLine(claims.FirstOrDefault(e => e.Type.Equals(ClaimTypes.Email)).Value); Console.ReadLine(); } }
public IHttpActionResult GetToken(Login login) { try { if (DatabaseAction.LoginAttempt(login.userName, login.password, out Employee user) == "Successfull") { var roles = "user"; if (user.isAdmin == true) { roles = "admin"; } IAuthContainerModel model = GetJWTContainerModel(user.UserName, roles); IAuthService authService = new JWTService(model.SecretKey); string token = authService.GenerateToken(model); if (!authService.IsTokenValid(token)) { throw new UnauthorizedAccessException(); } else { List <Claim> claims = authService.GetTokenClaims(token).ToList(); } LogFile.LoginLog(user.FirstName, user.Employee_id); return(Ok(token)); } else { return(BadRequest("Invalid Credentials")); } } catch (Exception ex) { LogFile.WriteLog(ex); return(BadRequest()); } }
public string GenerateToken(IAuthContainerModel model) { if (model == null || model.Claims == null || model.Claims.Count == 0) { throw new ArgumentNullException(nameof(model)); } var securityTokenDescriptor = new SecurityTokenDescriptor { Subject = new ClaimsIdentity(model.Claims), Expires = DateTime.UtcNow.AddMinutes(Convert.ToInt32(model.ExpiryInMinutes)), Audience = _authModel.Audience, Issuer = _authModel.Issuer, SigningCredentials = new SigningCredentials(GetSymmetricSiginingKey(), model.SigningAlgorithm), EncryptingCredentials = new EncryptingCredentials(GetSymmetricEncryptionKey(), model.EncryptionAlgorithm, model.EncryptionEncoding) }; var jwtSecurityTokenHandler = new JwtSecurityTokenHandler(); var securityToken = jwtSecurityTokenHandler.CreateToken(securityTokenDescriptor); var token = jwtSecurityTokenHandler.WriteToken(securityToken); return(token); }
/// <summary> /// Generates token by given model. /// Validates whether the given model is valid, then gets the symmetric key. /// Encrypt the token and returns it. /// </summary> /// <param name="model"></param> /// <returns>Generated token.</returns> public string GenerateToken(IAuthContainerModel model) { if (model == null || model.Claims == null || model.Claims.Length == 0) { throw new ArgumentException("Arguments to create token are not valid."); } SecurityTokenDescriptor securityTokenDescriptor = new SecurityTokenDescriptor { Subject = new ClaimsIdentity(model.Claims), Expires = DateTime.UtcNow.AddMinutes(Convert.ToInt32(model.ExpireMinutes)), SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(Encoding.ASCII.GetBytes(AppConfigs.Instance.Secret)), model.SecurityAlgorithm), //IssuedAt = DateTime.Now, //Issuer = AppConfigs.Instance["Auth0:Issuer"], //NotBefore = new DateTimeOffset(DateTime.Now).DateTime }; var jwtSecurityTokenHandler = new JwtSecurityTokenHandler(); SecurityToken securityToken = jwtSecurityTokenHandler.CreateToken(securityTokenDescriptor); string token = jwtSecurityTokenHandler.WriteToken(securityToken); return(token); }
public async Task <object> Login([FromBody] UserLoginInfo info) { try { StringValues token; Request.Headers.TryGetValue("token", out token); string _token = token.FirstOrDefault(); if (Utilities.IsValidToken(_token)) { return(Ok(Responder.Success("Already logined"))); } Result result = await userService.LoginAsync(info.username, info.password); if (result.status != 200) { return(StatusCode(result.status, Responder.Fail(result.data))); } node1: HeplerTokenUser user = (HeplerTokenUser)result.data; IAuthContainerModel model = JwtHelper.GetJWTContainerModel(user.userId, user.username, user.email, _jwtConfig); IAuthService authService = new JWTService(model.SecretKey); string accessToken = authService.GenerateToken(model); if (!authService.IsTokenValid(accessToken)) { goto node1; } return(Ok(Responder.Success(new { token = accessToken, user = result.data }))); } catch (Exception error) { return(BadRequest(Responder.Fail(error.Message))); } }
public async Task <IActionResult> GetTokenAsync([Required][FromBody] LoginModel body) { try { if (string.IsNullOrEmpty(body.Email) || string.IsNullOrEmpty(body.Password)) { throw new UnauthorizedAccessException(); } var user = _context.Users.FirstOrDefault(x => x.Email == body.Email); if (user == null) { throw new UnauthorizedAccessException(); } if (SecurePasswordHasher.Verify(body.Password, user.Password)) { IAuthContainerModel model = JwtFunctions.GetJwtContainerModel(user.Id, user.Email); IAuthService authService = new JwtService(model.SecretKey); var token = authService.GenerateToken(model); return(new OkObjectResult(new { token, expiresIn = model.ExpireMinutes, user = _mapper.Map <DTOUserModel>(user) })); } return(new UnauthorizedResult()); } catch (UnauthorizedAccessException) { return(new UnauthorizedResult()); } catch (Exception ex) { return(new BadRequestObjectResult(new { error = ex })); } }
private void set_DbAdmin_Database() { if (SIS.Client.blvalue.AppMain.AppValue.CloudLicense) { string _DbAdminDatabase = get_DbKodAdmin_Database(SIS.Client.blvalue.AppMain.AppValue.CustomerGuidId); if (_DbAdminDatabase == null) { _DbAdminDatabase = ""; } if (_DbAdminDatabase != "") { SIS.Client.blvalue.AppMain.AppValue.DbAdminConnectionDTO.Database = _DbAdminDatabase; string connection = SIS.Client.blvalue.AppMain.AppValue.DbAdminConnectionDTO.Connection(blvalue.Cloude); #region Token IAuthService authService = new JWTService(); IAuthContainerModel model = GetJWTContainerModel("connection", connection); string token = authService.GenerateToken(model); if (!string.IsNullOrEmpty(token)) { connection = token; } #endregion SIS.Client.blvalue.AppMain.AppValue.ConAdmin = connection; SIS.Data.App.GetValue _GetValue = SIS.Client.Admin.bl.get_GetValue(); _GetValue.ConStr = SIS.Client.blvalue.AppMain.AppValue.ConAdmin; //var result = bl.blcAdmin.Run<Service.Admin.Service.AdminService, SIS.Data.ReturnProcess>(r => r.UpdateSqlDatabase(_GetValue)); } else { string connection = SIS.Client.blvalue.AppMain.AppValue.AdminConnectionDTO.Connection(blvalue.Cloude); SIS.Client.blvalue.AppMain.AppValue.ConAdmin = SIS.Client.blvalue.AppMain.CreateJwtToken("connection", connection); } } }
public void Setup() { model = JWTContainerModel.GetJWTContainerModel("Dmitry Ershov", "*****@*****.**"); service = new JWTAuthService(model.SecretKey); }
public JwtService(IAuthContainerModel authModel) { _authModel = authModel; }
public async Task <Response <MemberResult> > Login(string id, string pw) { string apiName = "LOGIN"; #region Anonymous Method LoginBadResponse memberBadResponse = delegate(ConTextColor preColor, int status, ConTextColor setColor, string msg) { UserModel tempModel = new UserModel(); string tempToken = ""; string tempRefreshToken = ""; ServiceManager.ShowRequestResult(apiName, preColor, status, setColor); return(new Response <MemberResult> { data = new MemberResult { token = tempToken, refreshToken = tempRefreshToken, member = tempModel }, status = status, message = msg }); }; #endregion var loginArgs = ComUtil.GetStringLengths(id, pw); if (id != null && pw != null && loginArgs[0] > 0 && loginArgs[1] > 0) { try { UserModel user = new UserModel(); using (IDbConnection db = GetConnection()) { db.Open(); string selectSql = $@" SELECT name, email FROM member_tb WHERE id = '{id}' AND pw = '{pw}' ;"; var response = await userDBManager.GetSingleDataAsync(db, selectSql, id); if (response != null) { user.id = id; user.name = response.name; user.email = response.email; IAuthContainerModel model = JWTService.GetJWTContainerModel(user.name, user.email); IAuthService authService = new JWTService(model.SecretKey); string token = authService.GenerateToken(model); // TODO : RefreshToken 발급. => 현재 임시로 빈 값 보냄 if (!authService.IsTokenValid(token)) { throw new UnauthorizedAccessException(); } else { List <Claim> claims = authService.GetTokenClaims(token).ToList(); Console.WriteLine("Login UserName : "******"Login Eamil : " + claims.FirstOrDefault(x => x.Type.Equals(ClaimTypes.Email)).Value); ServiceManager.ShowRequestResult("LOGIN", ConTextColor.LIGHT_GREEN, ResponseStatus.OK, ConTextColor.WHITE); return(new Response <MemberResult> { data = new MemberResult { token = token, refreshToken = "", member = user }, message = ResponseMessage.OK, status = ResponseStatus.OK }); } } else { return(memberBadResponse(ConTextColor.RED, ResponseStatus.UNAUTHORIZED, ConTextColor.WHITE, ResponseMessage.UNAUTHORIZED)); } } } catch (Exception e) { Console.WriteLine(apiName + " ERROR : " + e.Message); return(memberBadResponse(ConTextColor.PURPLE, ResponseStatus.INTERNAL_SERVER_ERROR, ConTextColor.WHITE, ResponseMessage.INTERNAL_SERVER_ERROR)); } } else { return(memberBadResponse(ConTextColor.RED, ResponseStatus.BAD_REQUEST, ConTextColor.WHITE, ResponseMessage.BAD_REQUEST)); } }