public async Task PostApi() { using (var Client = new HttpClient()) { //Client.DefaultRequestHeaders.Clear(); //Client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); //Client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(ApiToken.token_type, " " + ApiToken.access_token); Tuple <bool, string> Token_Header = ApiToken.Token_HeaderDetails(Client); if (Token_Header.Item1 == true) { //var serializedUser = JsonConvert.SerializeObject(_User_det); //var content = new StringContent(serializedUser, Encoding.UTF8, "application/json"); HttpResponseMessage reponse = await Client.GetAsync("http://localhost:28537/api/test/Res2"); if (reponse.IsSuccessStatusCode) { string ResponseStream = await reponse.Content.ReadAsStringAsync(); string Result = JsonConvert.DeserializeObject <string>(ResponseStream); } } } }
/// <summary> /// 修改一条数据 /// </summary> /// <param name="model"></param> /// <returns></returns> public ReturnResult <bool> Update(ApiToken model) { var rst = new ReturnResult <bool>(); try { StringBuilder strSql = new StringBuilder(); strSql.Append("update api_token set "); strSql.Append("AccessToken=@AccessToken,"); strSql.Append("RefreshToken=@RefreshToken,"); strSql.Append("AccessTokenExpiresIn=@AccessTokenExpiresIn,"); strSql.Append("AccessTokenCreateTime=@AccessTokenCreateTime,"); strSql.Append("RefreshTokenExpiresTime=@RefreshTokenExpiresTime "); strSql.Append("where AppId=@AppId"); int count = conn.Execute(strSql.ToString(), model); if (count > 0) { rst.Result = true; rst.Message = "更新成功"; } else { rst.Message = "更新失败"; } } catch (Exception ex) { rst.Message = "更新失败:" + ex.Message; Log4netUtil.Error("ApiTokenDal/Update", ex); } return(rst); }
public async Task <IActionResult> Post() { var user = await _userManager.GetUserAsync(User); if (user == null) { return(NotFound("The specified user could not be found.")); } using (var rng = new RNGCryptoServiceProvider()) { var data = new byte[16]; rng.GetBytes(data); var token = new ApiToken { Token = Convert.ToBase64String(data), UserId = user.Id }; _context.ApiTokens.Add(token); await _context.SaveChangesAsync(); return(new JsonResult(token)); } }
/// <summary> /// 新增一条数据 /// </summary> /// <param name="model"></param> /// <returns></returns> public ReturnResult <bool> Add(ApiToken model) { var rst = new ReturnResult <bool>(); try { var check = GetOne(model); if (check.Result) { return(Update(model)); } else { StringBuilder strSql = new StringBuilder(); strSql.Append("insert into api_token("); strSql.Append("AppId,AccessToken,RefreshToken,AccessTokenExpiresIn,AccessTokenCreateTime,RefreshTokenExpiresTime) "); strSql.Append("values ("); strSql.Append("@AppId,@AccessToken,@RefreshToken,@AccessTokenExpiresIn,@AccessTokenCreateTime,@RefreshTokenExpiresTime)"); conn.Execute(strSql.ToString(), model); rst.Result = true; rst.Message = "添加成功"; } } catch (Exception ex) { rst.Message = "添加失败:" + ex.Message; Log4netUtil.Error("ApiTokenDal/Add", ex); } return(rst); }
/// <summary> /// 删除一条数据 /// </summary> /// <param name="model"></param> /// <returns></returns> public ReturnResult <bool> Delete(ApiToken model) { var rst = new ReturnResult <bool>(); try { StringBuilder strSql = new StringBuilder(); strSql.Append("delete from api_token "); strSql.Append("where AppId=@AppId"); int count = conn.Execute(strSql.ToString(), model); if (count > 0) { rst.Result = true; rst.Message = "删除成功"; } else { rst.Message = "删除失败"; } } catch (Exception ex) { rst.Message = "删除失败:" + ex.Message; Log4netUtil.Error("ApiTokenDal/Delete", ex); } return(rst); }
private async void SignIn() { SignInInProgress = true; LoginStackPanelVisibility = Visibility.Collapsed; ProgressRingStackPanelVisibility = Visibility.Visible; PushbulletUser user = null; try { user = _dataService.SignIn(ApiToken); AppSettings.SignIn.ApiToken = await ApiToken.ProtectAsync(); } catch (Exception ex) { _dialogService.ShowError(Resources.UnableToSignIn + Environment.NewLine + ex.Message, Package.Current.DisplayName, "OK", null); } if (user != null) { _navigationService.Navigate(typeof(MainPage)); } else { SignInInProgress = false; LoginStackPanelVisibility = Visibility.Visible; ProgressRingStackPanelVisibility = Visibility.Collapsed; } }
public async Task <string> RenewToken(ApiKey key) { if (key == null) { throw new ArgumentNullException(nameof(key)); } ResetCache(); string oldHash = key.TokenHash; ApiToken apiToken = GenerateKey(key.Purpose); key.TokenHash = apiToken.Key.TokenHash; key.TokenType = apiToken.Key.TokenType; key.LastModified = DateTime.UtcNow; // // Save foreach (var s in _storages) { if (await s.GetKeyByHash(oldHash) != null) { await s.SaveKey(key); } } return(apiToken.Token); }
public async Task <object> Post([FromBody] dynamic model) { if (model == null) { throw new ApiArgumentException("model"); } if (model.expires_on == null) { throw new ApiArgumentException("expires_on"); } string purpose = DynamicHelper.Value(model.purpose) ?? string.Empty; DateTime?expiresOn = DynamicHelper.Value(model.expires_on) != String.Empty ? DynamicHelper.To <DateTime>(model.expires_on) : null; ApiToken token = _keyProvider.GenerateKey(purpose); token.Key.ExpiresOn = expiresOn; await _keyProvider.SaveKey(token.Key); // // Create response dynamic key = ApiKeyHelper.ToJsonModel(token); return(Created(ApiKeyHelper.GetLocation(key.id), key)); }
public ApiToken GetAccessToken(GetAccessTokenRequest tokenRequest) { ApiToken _token = new ApiToken(); try { using (var client = new HttpClient()) { client.BaseAddress = new Uri(ConstantData.ApiURL.ToString() + "api/token"); client.DefaultRequestHeaders.Accept.Clear(); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); var body = new List <KeyValuePair <string, string> > { new KeyValuePair <string, string>("grant_type", "client_credentials"), new KeyValuePair <string, string>("client_id", tokenRequest.client_id), new KeyValuePair <string, string>("client_secret", tokenRequest.client_secret) }; var content = new FormUrlEncodedContent(body); var response = client.PostAsync(client.BaseAddress, content).Result; if (response.IsSuccessStatusCode) { var responseStream = response.Content.ReadAsStringAsync().Result; _token = JsonConvert.DeserializeObject <ApiToken>(responseStream); } } } catch (Exception ex) { throw ex; } return(_token); }
public void Add(ApiTokensAddModel model, Customer customer) { var apiToken = new ApiToken(model.Name, customer); _apiTokenRepository.Add(apiToken); _unitOfWork.Commit(); }
private void Update(EvaluationContext context) { var search = Search.GetValue(context); var collectionId = CollectionId.GetValue(context); var triggerRequest = TriggerRequest.GetValue(context); if (triggerRequest && (search != _searchQuery || collectionId != _collectionId)) { TriggerRequest.Value = false; TriggerRequest.TypedInputValue.Value = false; TriggerRequest.DirtyFlag.Invalidate(); _maxResultCount = MaxResultCount.GetValue(context); _apiToken = ApiToken.GetValue(context); _searchQuery = search; _collectionId = collectionId; _request = SearchImagesTask(); } var photoIndex = GetPhotoIndex.GetValue(context); if (photoIndex != _photoIndex) { _photoIndex = photoIndex; if (_photos != null && _photos.Count != 0) { var index = Math.Abs(_photoIndex) % _photos.Count; PhotoAuthor.Value = _photos[index].User.Name; PhotoUrl.Value = _photos[index].Urls.Regular; Log.Debug($"Update photo properties: Author {PhotoAuthor.Value} Url {PhotoUrl.Value}"); } } }
private bool CheckAuth(HttpContext context) { CompilationSection ds = (CompilationSection)WebConfigurationManager.GetSection("system.web/compilation"); if (ds.Debug) { return(true); } bool result = false; string access_token = context.Request["access_token"]; List <ApiToken> tokenList = context.Application["api_token"] as List <ApiToken>; if (tokenList == null) { tokenList = new List <ApiToken>(); } ApiToken token = (from i in tokenList where i.access_token == access_token select i).SingleOrDefault(); if (token != null) { if (token.update_time.AddSeconds(7200) <= DateTime.Now) { result = true; } } return(result); }
// [ValidateAntiForgeryToken] public async Task <ActionResult> Login(LoginModel model) { var error = ""; ApiToken tokenData = null; if (ModelState.IsValid) { if (WebSecurity.Login(model.Email, new Security(model.Password).Encrypt(), persistCookie: false)) //Check the database { var user = GetUserRepository().GetUserProfile(model.Email); string role = ((UserRole)user.RoleId).ToString(); string baseUrl = Request.Url.AbsoluteUri.ToLowerInvariant().Contains("localhost") ? AppKeys.LocalApiDomain : AppKeys.LocalApiDomain; tokenData = await WebHelper.GetTokenAsync(model.Email, model.Password, baseUrl); List <Claim> claims = new ClaimExtension().AddClaims(model.Email, user.UserId.ToString(), user.FirstName + " " + user.LastName, role); if (null != claims) { AddClaims(claims); } } else { error = ("Invalid username or password!."); } } else { error = ("Data is not valid!."); } return(Json(new { status = error == "", error, tokenData })); }
public async Task <List <GusContractor> > GetGusDataAsync(string vatId, ApiToken apiToken) { var client = new HttpClient() { DefaultRequestHeaders = { Authorization = new AuthenticationHeaderValue("Bearer", apiToken.Token) } }; var vatNumberJson = JsonConvert.SerializeObject(new NipRequest { Nip = vatId }); var httpContent = new StringContent(vatNumberJson, Encoding.UTF8, "application/json"); var response = await client.PostAsync($"{apiUrl}gusapi/data", httpContent); if (response.StatusCode == HttpStatusCode.OK) { try { var result = JsonConvert.DeserializeObject <List <GusContractor> >(await response.Content.ReadAsStringAsync()); if (result != null && result[0].Name == "ERROR") { return(new List <GusContractor>()); } return(result); } catch { return(new List <GusContractor>()); } } return(new List <GusContractor>()); }
public Configuration(string token, string dbName, string pathToPlugins, int remindTimeOut) { Token = new ApiToken(token); Db = new DbInfo(dbName); PathToPluginsFolder = new PluginsPath(pathToPlugins); RemindTimeOut = new ReminderTimeOut(remindTimeOut); }
public async Task <IActionResult> Create(string purpose, string expiration) { long exp = 0; // seconds if (!string.IsNullOrWhiteSpace(expiration)) { exp = long.Parse(expiration); if (exp < 0) { throw new ArgumentOutOfRangeException(nameof(expiration)); } } // Create a key ApiToken key = _keyProvider.GenerateKey(purpose); // Set expiration if (exp > 0) { key.Key.ExpiresOn = DateTime.UtcNow.AddSeconds(exp); } // Store the key await _keyProvider.SaveKey(key.Key); return(View("Index", new { Keys = await GetAllKeys(), NewToken = new { Purpose = purpose, Value = key.Token }.ToExpando() }.ToExpando())); }
public async Task <object> Post([FromBody] dynamic model) { if (model == null) { throw new ApiArgumentException("model"); } if (model.api_key == null || model.api_key.id == null) { throw new ApiArgumentException("api_key"); } string apikeyId = DynamicHelper.Value(model.api_key.id); ApiKey key = _keyProvider.GetKey(apikeyId); if (key == null) { return(NotFound()); } // Renew the token ApiToken token = await _keyProvider.RenewToken(key); // // Create response dynamic obj = AccessTokenHelper.ToJsonModel(token); return(Created(AccessTokenHelper.GetLocation(key.Id), obj)); }
public static DashboardItem AddExceptionsWhere( ApiToken apiToken, string name = "Exceptions", Action <DashboardItem>?options = null, string whereQuery = "") { var query = $@" exceptions | where timestamp > ago(1h) | where client_Type == 'PC' {whereQuery} | summarize _count=sum(itemCount) by bin(timestamp, 2m) | project timestamp, _count"; var item = new DashboardItem(name, apiToken, query) { MinChartValue = 10, Total = ItemTotal.Sum, WarningThreshold = 10, ErrorThreshold = 50 }; options?.Invoke(item); return(item); }
public static DashboardItem AddWebTestsPercentage( ApiToken apiToken, string name = "Web tests 24h", Action <DashboardItem>?options = null, string whereQuery = "") { var query = $@" availabilityResults | where timestamp > ago(24h) | where client_Type == 'PC' {whereQuery} | summarize _successCount=todouble(countif(success == 1)), _totalCount=todouble(count()) by bin(timestamp, 1h) | project timestamp, 100.0 - (_successCount / _totalCount * 100.0)"; var item = new DashboardItem(name, apiToken, query) { Postfix = "%", MinChartValue = 10, Duration = ItemDuration.TwelveHours, FormatValue = d => (100.0 - d).ToString("0.#"), WarningThreshold = 1, ErrorThreshold = 5 }; options?.Invoke(item); return(item); }
protected override void Execute(CodeActivityContext context) { string api_url = ApiUrl.Get(context); string api_token = ApiToken.Get(context); List <string> allowed_classes = AllowedClasses.Get(context); string image = Image.Get(context); var ac = String.Join(",", allowed_classes.ToArray()); HttpClient client = new HttpClient(); client.DefaultRequestHeaders.TryAddWithoutValidation("Accept", "application/json"); client.DefaultRequestHeaders.TryAddWithoutValidation("Authorization", "Token " + api_token); MultipartFormDataContent form = new MultipartFormDataContent(); FileStream fs = File.Open(image, FileMode.Open); StreamContent sc = new StreamContent(fs); form.Add(sc, "image", Path.GetFileName(image)); form.Add(new StringContent(ac), "text"); HttpResponseMessage response = client.PostAsync(api_url, form).Result; if (response.IsSuccessStatusCode) { var json = response.Content.ReadAsStringAsync().Result; Documents.Set(context, json); } else { Documents.Set(context, ""); } client.Dispose(); }
public static DashboardItem AddFailedRequestsPercentage( ApiToken apiToken, string name = "Failed requests", Action <DashboardItem>?options = null, string whereQuery = "") { var query = $@" requests | where timestamp > ago(1h) | where client_Type == 'PC' {whereQuery} | summarize totalCount=sum(itemCount), errorCount=sumif(itemCount, success == false) by bin(timestamp, 2m) | project timestamp, 100.0 / totalCount * errorCount"; var item = new DashboardItem(name, apiToken, query) { Postfix = "%", MinChartValue = 10, FormatValue = d => d.ToString("0.#"), WarningThreshold = 5, ErrorThreshold = 10 }; options?.Invoke(item); return(item); }
protected HttpMessageHandler GetHandler(ApiToken token, HttpMessageHandler innerHandler) { return(new ApiAuthenticationHandler(() => { return Task.FromResult(token); }, innerHandler)); }
} //removed static for race condition /// <summary> /// Function to generate unique token with expiry against the provided userId. /// Also add a record in database for generated token. /// </summary> /// <param name="userId"></param> /// <returns></returns> public ApiToken GenerateToken(string userId) { string token = Guid.NewGuid().ToString(); DateTime issuedOn = DateTime.UtcNow; DateTime expiredOn = DateTime.UtcNow.AddSeconds(Convert.ToDouble(ConfigurationManager.AppSettings["AuthTokenExpiry"])); var tokendomain = new ApiToken { T_UsersID = userId, T_AuthToken = token, T_IssuedOn = issuedOn, T_ExpiresOn = expiredOn }; db.ApiTokens.Add(tokendomain); db.SaveChanges(); var tokenModel = new ApiToken { T_UsersID = userId, T_AuthToken = token, T_IssuedOn = issuedOn, T_ExpiresOn = expiredOn }; return(tokenModel); }
public TelegramMessengerBot(ApiToken token, SessionHandler sessionHandler, Reminder reminder, TelegramResponseHandler responseHandler) { Reminder = reminder; Bot = new TelegramBotClient(token.Token); SessionHandler = sessionHandler; ResponseHandler = responseHandler; }
public DashboardSite(ApiToken apiToken, SiteSettings siteSettings, bool silent = false) { ApplicationId = apiToken.ApplicationId; ApiKey = apiToken.ApiKey; Silent = silent; SiteSettings = siteSettings; DashboardType = DashboardType.Site; }
public ApiTokensUpdateModel Details(Guid id) { ApiToken apiToken = _apiTokenRepository.Get(id); ApiTokensUpdateModel model = Mapper.Map <ApiTokensUpdateModel>(apiToken); return(model); }
public void Update(ApiTokensUpdateModel model, Guid id) { ApiToken apiToken = _apiTokenRepository.Get(id); apiToken.Name = model.Name; _apiTokenRepository.Update(apiToken); _unitOfWork.Commit(); }
private async Task HandleValidSaveSubmit() { this.GuildWarsClient.Key = formModel.ApiKey; var tokenInfo = await this.GuildWarsClient.V2.GetTokenInfo(); this.token = new ApiToken(formModel.ApiKey, tokenInfo); await this.JS.SetApiKey(this.token); }
public void Delete(Guid id) { ApiToken apiToken = _apiTokenRepository.Get(id); _apiTokenRepository.Delete(apiToken); _unitOfWork.Commit(); }
public TokenManager() { _ApiToken = SessionHelper.UserApiToken; _IAuthenticationApiConsumer = new AuthenticationApiConsumer(); _UserCredential = SessionHelper.UserCredential; // var applicationManagerDependencyResolver = GlobalConfiguration.Configuration.DependencyResolver.GetService(typeof(ICustomAuthenticationService)) as ICustomAuthenticationService; _TokenApiConsumer = new TokenApiConsumer(); }