using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Security.Cryptography; using System.Text; using System.Web.Http; using AIAHTML5.WebAPI.Models; using AIAHTML5.WebAPI.ViewModels; using JWT; using System.Web.Http.Cors; using Newtonsoft.Json.Linq; using System.Web.Script.Serialization; using AIAHTML5.WebAPI.Util; namespace AIAHTML5.WebAPI.Controllers { [EnableCors(origins: "http://localhost/AIA/API/", headers: "accept,content-type,origin,x-my-header", methods: "*")] public class AccountController : ApiController { [AllowAnonymous] //[Route("signin")] [HttpPost] public string Login(string userName, string password) { logging obj = new logging(); obj.logData("called api"); var loginSuccess = false; User userObj = new User(); userObj.userName = "amrita.vishnoi@ebix.com"; userObj.password = "education"; userObj.Id = 1; if (userName == userObj.userName && password ==userObj.password) { loginSuccess = true; } else { loginSuccess = false; } if (loginSuccess) { object dbUser; string token = CreateToken(userObj, out dbUser); return token; } else { string msg = "token is not created"; return msg; //var jsonString = Json(new JavaScriptSerializer().Serialize(new { msg })); //return JObject.Parse(jsonString.Content); } //return response; } /// /// Create a Jwt with user information /// /// /// /// private static string CreateToken(User user, out object dbUser) { var unixEpoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); var expiry = Math.Round((DateTime.UtcNow.AddHours(2) - unixEpoch).TotalSeconds); var issuedAt = Math.Round((DateTime.UtcNow - unixEpoch).TotalSeconds); var notBefore = Math.Round((DateTime.UtcNow.AddMonths(6) - unixEpoch).TotalSeconds); var payload = new Dictionary { {"userName", user.userName}, {"userId", user.Id}, {"role", "Admin" }, {"sub", user.Id}, {"nbf", notBefore}, {"iat", issuedAt}, {"exp", expiry} }; //var secret = ConfigurationManager.AppSettings.Get("jwtKey"); const string apikey = "secretKey"; var token = JsonWebToken.Encode(payload, apikey, JwtHashAlgorithm.HS256); dbUser = new { user.userName, user.Id }; return token; } /// /// Creates a random salt to be used for encrypting a password /// /// public static string CreateSalt() { var data = new byte[0x10]; using (var cryptoServiceProvider = new RNGCryptoServiceProvider()) { cryptoServiceProvider.GetBytes(data); return Convert.ToBase64String(data); } } /// /// Encrypts a password using the given salt /// /// /// /// public static string EncryptPassword(string password, string salt) { using (var sha256 = SHA256.Create()) { var saltedPassword = string.Format("{0}{1}", salt, password); var saltedPasswordAsBytes = Encoding.UTF8.GetBytes(saltedPassword); return Convert.ToBase64String(sha256.ComputeHash(saltedPasswordAsBytes)); } } } }