//POST: /auth/signin/ public async Task <IActionResult> SignIn([Bind("Username,Password")] LoginRequestModel login) { //Find a user with a matching email as entered var foundUser = await _context.Users .FirstOrDefaultAsync(m => m.Username == login.Username); //If no user was found, exit with error if (foundUser == null) { return(Unauthorized(new { error = "User not found" })); } //Otherwise, check the DB hash against our user's entered password's hash string loginPassHash = UserHelper.GeneratePasswordHash(login.Password, foundUser.Salt); bool authed = (foundUser.HashedPassword == loginPassHash); //If they failed to hash to the same value, return an error if (!authed) { return(Unauthorized(new { error = "Password entered is incorrect" })); } IAuthContainerModel model = new JWTContainerModel() { Claims = new Claim[] { new Claim("UserName", foundUser.Username), new Claim("IsAdmin", foundUser.IsAdmin.ToString()) }, }; //Generate a JWT token for further authentication IAuthService jwt = new JWTService(model.SecretKey); string jwtToken = jwt.GenerateToken(model); //Add it as a cookie to the response Response.Cookies.Append("t", jwt.GenerateToken(model)); //Return our JWT access token and the authenticated user's information // Make a temporary user to strip out private info out of the user model (like passwords) UserModel returnUser = new UserModel { _id = foundUser._id, Username = foundUser.Username, FName = foundUser.FName, LName = foundUser.LName, Email = foundUser.Email, }; return(Ok(new { JWTAccessToken = jwtToken, User = returnUser })); }
public IHttpActionResult Login([FromBody] LoginModel data) { ClaimsIdentity claimsIdentity = IdentityService.ClaimIdentity(data); if (claimsIdentity != null) { String token = JWTService.GenerateToken(claimsIdentity); return(Json(token)); } else { return(BadRequest()); } }
public Response GetToken([FromForm] string userName, [FromForm] string password) { var user = userService.Authenticate(userName, password); if (user == null) { return(new Response { StatusCode = 401, Message = "Unauthorize" }); } IAuthContainerModel authContainerModel = new JWTContainerModel(user) { }; IAuthService authService = new JWTService(authContainerModel.Secretkey); return(new Response { StatusCode = 200, Message = "OK", AccessToken = authService.GenerateToken(authContainerModel) }); }
public void KO_IssuerNotMatch() { //ARRANGER var Id = Guid.NewGuid(); var secretKey = "that's a single secret key used to not be hacked"; var claimsRequest = new Dictionary <string, string>(); claimsRequest.Add(eClaims.Name.ToString(), "Luca Fenu"); claimsRequest.Add(eClaims.Id.ToString(), Id.ToString()); claimsRequest.Add(eClaims.Mail.ToString(), "*****@*****.**"); //ACT IAuthContainerModel model = new JWTContainerModel(secretKey, 1, "http://localhost:123", claimsRequest); IAuthService authService = new JWTService(model); string token = authService.GenerateToken(); IAuthContainerModel modelResponse = new JWTContainerModel(secretKey, 1, "http://localhost:312", null); IAuthService authServiceResponse = new JWTService(modelResponse); var tokenResponse = authServiceResponse.GenerateToken(); //ASSERT Assert.IsFalse(authService.IsTokenValid(tokenResponse)); }
public IHttpActionResult GetToken(Login login) { if (DBOperations.LoginAttempt(login.userName, login.password, out UserInfo 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(); } return(Ok(token)); } else { return(BadRequest("Invalid Credentials")); } }
public string Post(ReleaseManagementModel userLogin) { try { string token = null; bool value = bl.checkinguserlogin(userLogin.Username, userLogin.Password); if (value) { IAuthContainerModel model = GetJWTContainerModel(userLogin.Username, userLogin.Role); IAuthService authService = new JWTService(model.SecretKey); token = authService.GenerateToken(model); var message = Request.CreateResponse(HttpStatusCode.OK, "Authentication successfull"); message.Headers.Add("JWT_TOKEN", token); return(token); } else { return(token); } } catch (Exception e) { return(null); } }
private string _generateToken(Guid id, string deviceNumber) { string token = null; IAuthContainerModel jwtModel = JwtTokenService.GetAuthModel(id.ToString(), deviceNumber); IAuthService authService = new JWTService(jwtModel.SecretKey); token = authService.GenerateToken(jwtModel); UserToken userTokenIsValid = _db.UserTokens.Where(e => e.DeviceNumber == deviceNumber).FirstOrDefault(); if (userTokenIsValid == null) { UserToken userToken = _db.UserTokens.Create(); userToken.Token = token; userToken.UserId = id; userToken.DeviceNumber = deviceNumber; _db.UserTokens.Add(userToken); _db.SaveChanges(); } else { userTokenIsValid.Token = token; userTokenIsValid.UpdatedAt = DateTime.UtcNow; _db.SaveChanges(); } return(token); }
public static string Login(UserAuthDTO value) { using (var dbContext = new FiszkiContext()) { var user = dbContext.Users.FirstOrDefault(x => x.Login == value.Login); if (user == null) { return(null); } if (user.Password != value.Password) { dbContext.UsersLogs.Add(new Repositories.UserLogs { UserId = user.Id, LoginDate = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), LoginStatus = "Nieprawidłowe hasło" }); dbContext.SaveChanges(); return(null); } dbContext.UsersLogs.Add(new Repositories.UserLogs { UserId = user.Id, LoginDate = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), LoginStatus = "Zalogowano" }); dbContext.SaveChanges(); return(JWTService.GenerateToken(user.Id)); } }
public string GenerateJWT(string userId) { IAuthContainerModel model = this.GetJWTContainerModel(userId); IAuthService authService = new JWTService(model.SecretKey); return(authService.GenerateToken(model)); }
public static string Login(CredentialsModel value) { using (var dbContext = new FiszkiContext()) { var user = dbContext.Users.FirstOrDefault(x => x.Login == value.Login); if (user == null) { return(null); } if (user.Password != value.Password) { dbContext.UsersLogs.Add(new Repositories.UserLogs //Dodanie informacji o logowaniu + złe hasło { UserId = user.Id, LoginDate = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), // Data rejestracji LoginStatus = "Nieprawidłowe hasło" //var x = UserLogsRepository.AddUserLogsList(user.Id, ) }); dbContext.SaveChanges(); return(null); } dbContext.UsersLogs.Add(new Repositories.UserLogs //Dodanie informacji o logowaniu + złe hasło { UserId = user.Id, LoginDate = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), // Data rejestracji LoginStatus = "Zalogowano" }); dbContext.SaveChanges(); return(JWTService.GenerateToken(user.Id)); } }
static void Main(string[] args) { IniFileParser iniParser = new IniFileParser("config.ini"); string user = iniParser.Read("username"); string pass = iniParser.Read("password"); Console.WriteLine(user + " - " + pass); HttpService.LoginAsync(user, pass, JWTService.GetComputerSid().Value, (response) => { Debug.WriteLine(response); var token = response.Split(':').Last(); Console.WriteLine("Login Successful"); var generatedToken = JWTService.GenerateToken(token, JWTService.GetComputerSid().Value); Console.WriteLine(generatedToken); Console.WriteLine("jwt token created"); Constants.AccessToken = generatedToken; RunMethodInSeparateThread(StartServer); Console.WriteLine("Press Ctrl + C to Exit"); }).Wait(); }
public void TestAuth() { JWTContainerModel JWT = new JWTContainerModel() { Claims = new Claim[] { new Claim(ClaimTypes.Name, "Kent Utterback"), new Claim(ClaimTypes.Email, "*****@*****.**") } }; JWTService authService = new JWTService(JWT.SecretKey); string token = authService.GenerateToken(JWT); if (!authService.IsTokenValid(token)) { Assert.Fail(); } List <Claim> claims = authService.GetTokenClaims(token).ToList(); Assert.Equals(claims.FirstOrDefault(claim => claim.Type.Equals(ClaimTypes.Name)).Value, "Kent Utterback"); Assert.Equals(claims.FirstOrDefault(claim => claim.Type.Equals(ClaimTypes.Email)).Value, "*****@*****.**"); }
static void Main(string[] args) { IAuthContainerModel authContainerModel = GetJWTContainerModel("Vamsi Kalidindi", "*****@*****.**", "Admin", "+91 9666358224"); IAuthService authService = new JWTService(authContainerModel.SecretKey); //string token = authService.GenerateToken(authContainerModel); string token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJuYW1lIjoiVmFtc2kgS2FsaWRpbmRpIiwiZW1haWwiOiJrYWxpZGluZGl2YW1zaWtyaXNobmFAZ21haWwuY29tIiwicm9sZSI6IkFkbWluIiwiaHR0cDovL3NjaGVtYXMueG1sc29hcC5vcmcvd3MvMjAwNS8wNS9pZGVudGl0eS9jbGFpbXMvbW9iaWxlcGhvbmUiOiI5NjY2MzU4MjQ0IiwibmJmIjoxNjE1OTgyMjIyLCJleHAiOjE2MTY1ODcwMjIsImlhdCI6MTYxNTk4MjIyMn0.yElOPO7iPFMRtnilFIXgtykIdUd_6lyUgAq1Fxr0HYk"; if (!authService.IsTokenValid(token)) { token = authService.GenerateToken(authContainerModel); Console.WriteLine("Invalid Token"); Console.WriteLine("New token is : " + token); } else { List <Claim> claims = authService.GetTokenClaims(token).ToList(); Console.WriteLine(claims.FirstOrDefault(a => a.Type.Equals(ClaimTypes.Name)).Value); Console.WriteLine(claims.FirstOrDefault(a => a.Type.Equals(ClaimTypes.Email)).Value); Console.WriteLine(claims.FirstOrDefault(a => a.Type.Equals(ClaimTypes.Role)).Value); Console.WriteLine(claims.FirstOrDefault(a => a.Type.Equals(ClaimTypes.MobilePhone)).Value); Console.WriteLine("Current Token is : " + token); } }
public JsonResult <JsonUserModel> AuthenticateUser([FromBody] UserPresentationModel userPresentationModelObject) { UserBussinessEntity userBussinessEntityObject = MapperFromPresenationtoBL.Mapping <UserPresentationModel, UserBussinessEntity>(userPresentationModelObject); bool isAuthenticated = userBussinessServiceObject.RequestAuthentication(userBussinessEntityObject); if (isAuthenticated) { IAuthContainerModel model = GetJWTContainerModel(userPresentationModelObject.Username, "admin"); IAuthService authService = new JWTService(model.SecretKey); string token = authService.GenerateToken(model); int refreshToken = RandomNumber(0, 256); if (!authService.IsTokenValid(token)) { throw new UnauthorizedAccessException(); } else { ClaimsPrincipal claims = authService.GetTokenClaims(token); refreshTokens[refreshToken] = userPresentationModelObject.Username; } JsonUserModel jsonUserModelObject = new JsonUserModel(); jsonUserModelObject.RefreshToken = userPresentationModelObject.Username; jsonUserModelObject.JWTToken = token; return(Json(jsonUserModelObject)); } return(null); }
public JObject FunctionHandler(JObject input) { string status; string data; try { // You should reference any logic or functions which authenticate your user here and then pass any data as claims to GetJWTContainerModel string UserName = "******"; IAuthContainerModel model = JWTService.GetJWTContainerModel(UserName); IAuthService authService = new JWTService(model.SecretKey); string jwt = authService.GenerateToken(model); status = "SUCCESS"; data = jwt; } catch (Exception e) { status = "ERROR"; // Should really handle errors better than this data = e.Message; LambdaLogger.Log(e.Message); } JObject result = new JObject(); result.Add("status", status); result.Add("data", data); return(result); }
public string GenerateToken(Guid ID) { IAuthContainerModel containerModel = GetJWTContainerModel(ID); IAuthService authService = new JWTService(containerModel.SecretKey); return(authService.GenerateToken(containerModel)); }
public AuthenticeResponse Authenticate(AuthenticateCR req) { AuthenticeResponse resp = new AuthenticeResponse(); try { if (ValidateRequest.Authenticate(req)) { UserCRUD userCRUD = new UserCRUD(); string statusMessage = string.Empty; if (IsUserValid(req.EmailID, req.Password, out statusMessage)) { resp.Token = JWTService.GenerateToken(req.EmailID); resp.StatusCode = HttpStatusCode.OK; resp.StatusMessage = HttpStatusCode.OK.ToString(); } else { resp.StatusCode = HttpStatusCode.Unauthorized; resp.StatusMessage = statusMessage; } } else { resp.StatusCode = HttpStatusCode.BadRequest; resp.StatusMessage = HttpStatusCode.BadRequest.ToString(); } } catch (Exception es) { resp.StatusCode = HttpStatusCode.InternalServerError; resp.StatusMessage = HttpStatusCode.InternalServerError.ToString(); } return(resp); }
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 string TokenGenerator(string email, string instrumentalKey) { IAuthContainerModel model = JWTModelGenerator.GetJWTContainerModel("Admin", email, instrumentalKey); IAuthService authService = new JWTService(model.SecretKey); string token = authService.GenerateToken(model); return(token); }
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); }
public IHttpActionResult Authenticate([FromBody] AuthenticateRequest model) { var jwtToken = _JWTService.GenerateToken(new LoginModel() { Username = "******", FBid = "1", Photo = "hi" }); var refreshToken = _JWTService.GenerateRefreshToken("apk"); return(Ok(Request)); }
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)); }
static void Main(string[] args) { IAuthService authService = new JWTService(); string jwt = authService.GenerateToken("*****@*****.**"); string accessToken = authService.GetAccessToken(jwt); Console.WriteLine("Access Token:"); Console.WriteLine(accessToken); }
public ActionResult Login(string username, string pass) { var obj = _dl.GetPassByUserName(username, true); if (obj == null) { return(Json(new BaseResponse <AgencyItem>() { Erros = true, Message = "Tên tài khoản không đúng" })); } var pas = FDIUtils.CreatePasswordHash(pass, obj.PasswordSalt); if (obj.Password != pas) { return(Json(new BaseResponse <AgencyItem>() { Erros = true, Message = "Mật khẩu không đúng" })); } if (obj.isLock != true) { return(Json(new BaseResponse <AgencyItem>() { Erros = true, Message = "Tài khoản chưa được kích hoạt" })); } IAuthContainerModel model = new JWTContainerModel() { Claims = new Claim[] { new Claim(ClaimTypes.Name, obj.UserName), new Claim("ID", obj.UserId.ToString()), new Claim("AgencyId", obj.AgencyID.ToString()), } }; IAuthService authService = new JWTService(); var token = authService.GenerateToken(model); var result = new BaseResponse <AgencyItem>() { Erros = false, Data = new AgencyItem() { FullName = obj.FullName, Phone = obj.Phone, Token = token, AgencyLevelId = obj.AgencyLevelId } }; return(Json(result, JsonRequestBehavior.AllowGet)); }
public IActionResult Login([FromBody] UsuarioInputModel model) { var user = _usuarioService.Validate(model.CorreoElectronico, model.ClaveDeIngreso); if (user == null) { return(BadRequest("El correo electronico o la clave de acceso son incorrectos.")); } var response = _jwtService.GenerateToken(user); return(Ok(response)); }
public void TestGenerateToken() { var svc = new JWTService(this.testSecret); var token = svc.GenerateToken(new JWTContainerModel { Claims = new Claim[] { new Claim(ClaimTypes.Name, "user1"), new Claim(ClaimTypes.Email, "*****@*****.**") } }); Assert.IsFalse(string.IsNullOrEmpty(token)); }
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")); }
public ActionResult <UsuarioViewModel> Post(UsuarioInputModel usuarioInput) { Usuario usuario = MapearUsuario(usuarioInput); var user = _usuarioService.Validate(usuario.CorreoElectronico, usuario.ClaveDeIngreso); if (user == null) { return(BadRequest("El correo electronico o la clave de acceso son incorrectos.")); } var response = _jwtService.GenerateToken(user); return(Ok(response)); }
private static Session CreateSession(string email, string handle, string displayName, string bio) { var authTokenContainerModel = new JWTContainerModel(SessionSecretKey, SecurityAlgorithms.HmacSha256Signature, 1440, new Claim[] { new Claim(ClaimTypes.Email, email), new Claim("TokenType", JWTTokenTypes.Auth) }); var refreshTokenContainerModel = new JWTContainerModel(SessionSecretKey, SecurityAlgorithms.HmacSha256Signature, 44640, new Claim[] { new Claim(ClaimTypes.Email, email), new Claim("TokenType", JWTTokenTypes.Refresh) }); var jwtService = new JWTService(SessionSecretKey); var authTokenExpireTime = new DateTimeOffset(DateTime.UtcNow.AddMinutes(Convert.ToInt32(authTokenContainerModel.ExpireMinutes))).ToUnixTimeSeconds(); var refreshTokenExpireTime = new DateTimeOffset(DateTime.UtcNow.AddMinutes(Convert.ToInt32(refreshTokenContainerModel.ExpireMinutes))).ToUnixTimeSeconds(); var authToken = new SessionToken(authTokenExpireTime, jwtService.GenerateToken(authTokenContainerModel)); var refreshToken = new SessionToken(refreshTokenExpireTime, jwtService.GenerateToken(refreshTokenContainerModel)); return(new Session(email, handle, displayName, bio, authToken, refreshToken)); }
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); }