public void AddNewUser() { var user = new User() { Email = "*****@*****.**", FirstName = "Erandika", IsActive = true, LastName = "Sandaruwan", MobileNo = "0702605650", Password = CustomPasswordHasher.GenerateHash("system"), Username = "******", }; user.UserRoles = new HashSet <UserRole>(); var userRole = new UserRole() { IsActive = true, RoleId = 1, StartedDate = DateTime.UtcNow }; user.UserRoles.Add(userRole); _db.SaveChanges(); }
public IActionResult Login([FromBody] LoginViewModel model) { if (model == null) { return(Unauthorized(new { ErrorMessage = "Login failed.Please enter your password and username." })); } var user = _userService.GetUserByUsername(model.Username); if (user == null) { return(Unauthorized(new { ErrorMessage = "Login failed.Invalid username has entered." })); } else { var passwordHash = CustomPasswordHasher.GenerateHash(model.Password); if (user.Password == passwordHash) { var test = _config["Tokens:Key"]; var secretKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config["Tokens:Key"])); //var secretKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(comapny.SecretKey.ToString())); var signinCredentials = new SigningCredentials(secretKey, SecurityAlgorithms.HmacSha256); string userRole = string.Empty; string roles = string.Join(",", user.UserRoles.Select(t => t.Role.Name).ToList()); var now = DateTime.UtcNow; DateTime nowDate = DateTime.UtcNow; var claims = new[] { new Claim(JwtRegisteredClaimNames.Sub, user.Username), new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()), new Claim(JwtRegisteredClaimNames.Iat, now.ToUniversalTime().ToString(), ClaimValueTypes.Integer64), new Claim(JwtRegisteredClaimNames.Aud, "admin"), new Claim(ClaimTypes.Role, roles) }; var tokenOptions = new JwtSecurityToken( issuer: _config["Tokens:Issuer"], claims: claims, notBefore: nowDate, expires: nowDate.AddDays(100), signingCredentials: signinCredentials ); var tokenString = new JwtSecurityTokenHandler().WriteToken(tokenOptions); return(Ok(new { Token = tokenString, FirstName = user.FirstName, Email = user.Email, ProfilePic = "", Role = user.UserRoles.FirstOrDefault().Role.Name })); } else { return(Unauthorized(new { ErrorMessage = "Login failed.Invalid password has entered." })); } } }