private UserJwt GenerateJSONWebToken() { var jwtSection = _config.GetSection("AppSettings").GetSection("Jwt"); // configure jwt authentication var jwtSettings = jwtSection.Get <AppSettings.Jwt>(); var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtSettings.Key)); var credentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256); DateTime expiry = DateTime.Now.AddMinutes(int.Parse(jwtSettings.ExpiryInMinutes)); var token = new JwtSecurityToken(jwtSettings.Issuer, jwtSettings.Issuer, null, expires: expiry, signingCredentials: credentials); UserJwt uj = new UserJwt(); uj.token_String = new JwtSecurityTokenHandler().WriteToken(token); uj.expiry = expiry; return(uj); }
public IActionResult GenerateNewApiToken([FromRoute] string ApiKey, [FromBody] UserObj obj) { IActionResult response = Unauthorized(); UserApiTokenResponse resp = new UserApiTokenResponse(); try { UserJwt uj = GenerateJSONWebToken(); int ReturnVal; string ReturnMsg; UserApiTokenObj utj = new UserApiTokenObj(); utj.user_id = obj.user_id; utj.api_token = uj.token_String; utj.token_expiry = uj.expiry; SetUserApiToken(ApiKey, utj, out ReturnVal, out ReturnMsg); if (ReturnVal == 1) { resp.statuscode = (int)Common.ResponseStatusCode.Success; resp.message = "success"; resp.api_token = uj.token_String; response = Ok(resp); } else { resp.statuscode = (int)Common.ResponseStatusCode.SqlException; resp.message = ReturnMsg; response = Conflict(resp); } } catch (Exception ex) { Common c = new Common(); ExceptionObj exobj = c.GetExceptionObjBase(ex); exobj.form_name = "AuthentcationController"; exobj.page_url = "api/Authentication/GenerateNewApiToken"; int ReturnVal; string ReturnMsg; ExceptionDAO exd = new ExceptionDAO(_ConStr); exd.SetExceptionLog(ApiKey, exobj, out ReturnVal, out ReturnMsg); resp.statuscode = (int)Common.ResponseStatusCode.Exception; resp.message = ex.Message.ToString(); response = BadRequest(resp); } return(response); }
public static UserJwt AuthenticateUser(UserJwt loginCredentials) { using (var context = new Context()) { User user1 = context.Users.SingleOrDefault(x => x.Username == loginCredentials.Username && x.Password == loginCredentials.Password); UserJwt user = new UserJwt { Username = user1.Username, Password = user1.Password, UserRole = user1.Role.Role_name }; return(user); } }
public IActionResult Login([FromBody] UserJwt login) { IActionResult response = Unauthorized(); UserJwt user = AuthenticateHelper.AuthenticateUser(login); if (user != null) { var tokenString = AuthenticateHelper.GenerateJWTToken(user, _config); response = Ok(new { token = tokenString, userDetails = user, }); } return(response); }
public virtual async Task <UserJwt> LoginAsync(string userName, string password) { var user = await _userAccountRepository.GetByUsernameAsync(userName); if (!_passwordService.IsPasswordValid(password, user.Password, user.Salt)) { throw new InvalidCredentialException("Username or password doesn't match!"); } var jwt = _jwtHandler.Create(user.Id.ToString()); var payload = new UserJwt() { Id = user.Id, Token = jwt.Token, ExpiresIn = jwt.Expires }; return(payload); }
public static string GenerateJWTToken(UserJwt userInfo, IConfiguration _config) { var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config["Jwt: SecretKey"])); var credentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256); var claims = new[] { new Claim(JwtRegisteredClaimNames.Sub, userInfo.Username), new Claim("role", userInfo.UserRole), new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()), }; var token = new JwtSecurityToken( issuer: _config["Jwt: Issuer"], audience: _config["Jwt: Audience"], claims: claims, expires: DateTime.Now.AddMinutes(30), signingCredentials: credentials ); return(new JwtSecurityTokenHandler().WriteToken(token)); }
public static async Task SendToSignalRWithTimeUsedAsync(UserJwt user, string header, string body, string footer, Stopwatch stopwatch, DateTime timeStart, DateTime timeEnd) { if (string.IsNullOrEmpty(user.TrackingStatus)) { return; } if (user.TrackingStatus != "T") { return; } if (WebApiTracking.SetUpSignalRTracking() != "OK") { return; } string trackMessage = string.Empty; TimeSpan ts = stopwatch.Elapsed; trackMessage += System.Environment.NewLine + " Time : " + timeStart.ToString() + " => " + timeEnd.ToString() + System.Environment.NewLine + " Time used : " + String.Format("{0:00} Hours {1:00} Minutes {2:00} Seconds {3:00} Milliseconds", ts.Hours, ts.Minutes, ts.Seconds, ts.Milliseconds / 10) + System.Environment.NewLine; Message m = new Message(); m.Header = header; m.Body = body; m.Footer = footer; m.TimeStamp = trackMessage; await WebApiTracking.hubConnection.InvokeAsync("AddToGroup", user.UserId); await WebApiTracking.hubConnection.InvokeAsync("SendMessage", user.UserId, m); await WebApiTracking.hubConnection.InvokeAsync("RemoveFromGroup", user.UserId); }
public IActionResult AuthorizationToken([FromRoute] string ApiKey, [FromBody] LoginObj obj) { IActionResult response = Unauthorized(); UserAuthenticationResponse resp = new UserAuthenticationResponse(); try { DataSet ds; int ReturnVal; string ReturnMsg; var IsAuth = AuthenticateApiCaller(ApiKey, obj, out ds, out ReturnVal, out ReturnMsg); if (IsAuth) { var tokenString = ""; if (String.IsNullOrEmpty(ds.Tables[0].Rows[0]["active_api_token"].ToString())) { UserJwt uj = GenerateJSONWebToken(); tokenString = uj.token_String; int ReturnVal_utj; string ReturnMsg_utj; UserApiTokenObj utj = new UserApiTokenObj(); utj.user_id = int.Parse(ds.Tables[0].Rows[0]["user_id"].ToString()); utj.api_token = uj.token_String; utj.token_expiry = uj.expiry; SetUserApiToken(ApiKey, utj, out ReturnVal_utj, out ReturnMsg_utj); if (ReturnVal_utj != 1) { resp.statuscode = (int)Common.ResponseStatusCode.SqlException; resp.message = ReturnMsg_utj; response = Conflict(resp); return(response); } } else { tokenString = ds.Tables[0].Rows[0]["active_api_token"].ToString(); } resp.statuscode = (int)Common.ResponseStatusCode.Success; resp.message = "success"; resp.user_id = int.Parse(ds.Tables[0].Rows[0]["user_id"].ToString()); resp.studio_id = int.Parse(ds.Tables[0].Rows[0]["studio_id"].ToString()); resp.full_name = ds.Tables[0].Rows[0]["full_name"].ToString(); resp.api_key = ds.Tables[0].Rows[0]["api_key"].ToString(); resp.api_token = tokenString; response = Ok(resp); } else { resp.statuscode = (int)Common.ResponseStatusCode.ValidationException; resp.message = ReturnMsg; response = Unauthorized(resp); } } catch (Exception ex) { Common c = new Common(); ExceptionObj exobj = c.GetExceptionObjBase(ex); exobj.form_name = "AuthentcationController"; exobj.page_url = "api/Authentication/AuthorizationToken"; int ReturnVal; string ReturnMsg; ExceptionDAO exd = new ExceptionDAO(_ConStr); exd.SetExceptionLog(ApiKey, exobj, out ReturnVal, out ReturnMsg); resp.statuscode = (int)Common.ResponseStatusCode.Exception; resp.message = ex.Message.ToString(); response = BadRequest(resp); } return(response); }