private async Task <string> CallWorkflow(WorkflowConfig workflow) { var req = new HttpRequestMessage(HttpMethod.Get, "http://localhost/workflow"); var flowConfig = this.workflowEngine.Config; var flowName = workflow.Name; flowConfig.FlowEdgeEnvironmentEndpointUri = new Uri("http://localhost"); using (RequestCorrelationContext.Current.Initialize(apiVersion: FlowConstants.PrivatePreview20190601ApiVersion, localizationLanguage: "en-us")) { var clientRequestIdentity = new RequestIdentity { Claims = new Dictionary <string, string>(), IsAuthenticated = true, }; clientRequestIdentity.AuthorizeRequest(RequestAuthorizationSource.Direct); RequestCorrelationContext.Current.SetAuthenticationIdentity(clientRequestIdentity); var flow = await FindExistingFlow(workflow.Name); var triggerName = flow.Definition.Triggers.Keys.Single(); var trigger = flow.Definition.GetTrigger(triggerName); var ct = CancellationToken.None; if (trigger.IsFlowRecurrentTrigger() || trigger.IsNotificationTrigger()) { await this.workflowEngine.Engine .RunFlowRecurrentTrigger( flow : flow, flowName : flowName, triggerName : triggerName); return(""); } else { var triggerOutput = this.workflowEngine.Engine.GetFlowHttpEngine().GetOperationOutput(req, flowConfig.EventSource, ct).Result; var resp = await this.workflowEngine.Engine .RunFlowPushTrigger( request : req, context : new FlowDataPlaneContext(flow), trigger : trigger, subscriptionId : EdgeFlowConfiguration.EdgeSubscriptionId, resourceGroup : EdgeFlowConfiguration.EdgeResourceGroupName, flowName : flowName, triggerName : triggerName, triggerOutput : triggerOutput, clientCancellationToken : ct); return(await resp.Content.ReadAsStringAsync()); } } }
protected virtual RequestIdentity SetIndentity(IOwinRequest request) { var entry = new RequestIdentity(); entry.ClientIp = request.RemoteIpAddress; entry.Endpoint = request.Uri.AbsolutePath.ToLowerInvariant(); entry.ClientKey = request.Headers.Keys.Contains("Authorization-Token") ? request.Headers.GetValues("Authorization-Token").First() : "anon"; return(entry); }
protected virtual RequestIdentity SetIndentity(HttpRequestMessage request) { var entry = new RequestIdentity(); entry.ClientIp = processer.GetClientIp(request).ToString(); entry.Endpoint = request.RequestUri.AbsolutePath.ToLowerInvariant(); entry.ClientKey = request.Headers.Contains("Authorization-Token") ? request.Headers.GetValues("Authorization-Token").First() : "anon"; return(entry); }
private RequestIdentity GetIndentity(HttpActionContext actionContext) { var tempRequest = actionContext.Request; var entry = new RequestIdentity(); entry.ClientIp = processer.GetClientIp(tempRequest).ToString(); entry.Endpoint = tempRequest.RequestUri.AbsolutePath.ToLowerInvariant(); entry.ClientKey = tempRequest.Headers.Contains("Authorization-Token") ? tempRequest.Headers.GetValues("Authorization-Token").First() : "anon"; return(entry); }
/// <summary> /// 是否在白名单 /// </summary> /// <param name="requestIdentity"></param> /// <returns></returns> private bool IsWhitelisted(RequestIdentity requestIdentity) { var whiteList = _cacheManager.Get <List <RateLimitItemValve> >(RateLimitCacheKey.WhiteListKey); if (whiteList == null) { whiteList = _policyStore.GetWhiteList(); _cacheManager.Set(RateLimitCacheKey.WhiteListKey, whiteList, _options.ProlicyCacheTime); } if (whiteList != null && whiteList.Count > 0) { var result = whiteList.FirstOrDefault(x => x.PolicyType == requestIdentity.PolicyType && x.Value == requestIdentity.Value); return(result != null); } return(false); }
private string ComputeCounterKey(RequestIdentity requestIdentity, RateLimitRule rule) { var key = $"{_options.RateLimitCounterPrefix}_{requestIdentity.Value}_{rule.Period}"; key += $"_{requestIdentity.HttpVerb}_{requestIdentity.Path}"; return(key); //加密key //var idBytes = Encoding.UTF8.GetBytes(key); //byte[] hashBytes; //using (var algorithm = System.Security.Cryptography.SHA1.Create()) //{ // hashBytes = algorithm.ComputeHash(idBytes); //} //return BitConverter.ToString(hashBytes).Replace("-", string.Empty); }
public async Task InvokeAsync(HttpContext httpContext) { RequestIdentity = new RequestIdentity { Context = httpContext.GetRouteData().Values[ContextRouteName]?.ToString(), }; using var scope = Logger.BeginScope("context: {context}", RequestIdentity.Context); ClientDate = httpContext.Request.Query[ClientDateParameterName].Count > 0 && DateTime.TryParse(httpContext.Request.Query[ClientDateParameterName][0], out var clientDate) ? clientDate.ToUniversalTime() : DateTime.UtcNow; await InterceptErrors(InternalExecuteAsync, httpContext); }
public T HttpGet <T>(string url, RequestIdentity requestIdentity) { try { Func <HttpContent, string> stringFunc = hc => { var responsejson = hc.ReadAsStringAsync().Result; return(responsejson); }; return(HttpHelper.HttpRequestGet <T>(url, HttpHelper.HttpHeaderHandler(requestIdentity.ClientName, requestIdentity.ClientVersion, requestIdentity.RandomCode, requestIdentity.ApiVersion), stringFunc)); } catch (Exception exception) { throw; } return(default(T)); }
/// <summary> /// 校验 /// </summary> /// <param name="identity"></param> /// <returns></returns> public bool Check(RequestIdentity identity) { //白名单 if (IsWhitelisted(identity)) { return(true); } //规则 var rules = GetMatchingRules(identity); foreach (var rule in rules) { if (rule.Limit > 0) { //处理请求数 var counter = ProcessRequest(identity, rule); //过期 var expiry = counter.Timestamp + rule.PeriodTimespan.Value; if (expiry < DateTime.Now) { continue; } //超过最大数量 if (counter.TotalRequests > rule.Limit) { LogBlockedRequest(identity, counter, rule); return(false); } } else { var counter = ProcessRequest(identity, rule); LogBlockedRequest(identity, counter, rule); return(false); } } //没有匹配到规则 默认放行 return(true); }
public RequestIdentity GetIdentity() { if (_identity != null) { return(_identity); } var userIdString = HttpContextAccessor.HttpContext.User.Claims.SingleOrDefault(claim => claim.Type == "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier")?.Value; var serializedUser = HttpContextAccessor.HttpContext.User.Claims.SingleOrDefault(claim => claim.Type == "user")?.Value; if (string.IsNullOrWhiteSpace(userIdString)) { return(null); } var userId = Convert.ToInt32(userIdString); using (var textReader = new StringReader(serializedUser)) { using (var jsonReader = new JsonTextReader(textReader)) { return(_identity = new RequestIdentity(JsonSerializer.Deserialize <User>(jsonReader))); } } }
private RequestIdentity GetIndentity(ActionExecutingContext filterContext) { var request = filterContext.HttpContext.Request; var entry = new RequestIdentity(); entry.ClientIp = processer.GetClientIp(request).ToString(); entry.ClientKey = request.IsAuthenticated ? "auth" : "anon"; var rd = request.RequestContext.RouteData; string currentAction = rd.GetRequiredString("action"); string currentController = rd.GetRequiredString("controller"); switch (processer.Policy.EndpointType) { case EndpointThrottlingType.AbsolutePath: entry.Endpoint = request.Url.AbsolutePath; break; case EndpointThrottlingType.PathAndQuery: entry.Endpoint = request.Url.PathAndQuery; break; case EndpointThrottlingType.ControllerAndAction: entry.Endpoint = currentController + "/" + currentAction; break; case EndpointThrottlingType.Controller: entry.Endpoint = currentController; break; default: break; } //case insensitive routes entry.Endpoint = entry.Endpoint.ToLowerInvariant(); return(entry); }
public T HttpGet <T>(string url, RequestIdentity requestIdentity) { try { Func <HttpContent, string> stringFunc = hc => { var responsejson = hc.ReadAsByteArrayAsync().Result; var str = DeflateStream.UncompressBuffer(responsejson); var deresponsejson = Encoding.UTF8.GetString(str); return(deresponsejson); }; return(HttpHelper.HttpRequestGet <T>(url, HttpHelper.HttpHeaderHandler(requestIdentity.ClientName, requestIdentity.ClientVersion, requestIdentity.RandomCode, requestIdentity.ApiVersion), stringFunc)); } catch (Exception exception) { //var message = exception.Message; throw; } return(default(T)); }
private void PopulateSenderFromAuthHeader() { var token = this.Request.Headers.Authorization.Parameter; var parsedToken = new JwtSecurityTokenHandler().ReadJwtToken(token) as JwtSecurityToken; var connectionRequestIdentity = new RequestIdentity { AuthenticationType = PowerFlowConstants.MicrosoftGraphTokenAuthenticationType, IsAuthenticated = true, Claims = parsedToken.Claims .Where(claim => !claim.Type.EqualsInsensitively("signin_state")) .Where(claim => !claim.Type.EqualsInsensitively("amr")) .ToInsensitiveDictionary(claim => claim.Type, claim => claim.Value), Name = parsedToken.Claims.Where(claim => claim.Type.EqualsOrdinal("name")).FirstOrDefault().Value }; // Get tenantId and objectId set them into authentication identity var tenantId = parsedToken.Claims.Where(thisClaim => thisClaim.Type.EqualsOrdinal("tid")).FirstOrDefault().Value; var objectId = parsedToken.Claims.Where(thisClaim => thisClaim.Type.EqualsOrdinal("oid")).FirstOrDefault().Value; connectionRequestIdentity.Claims.Add(ClaimsConstants.ArmClaimNames.TenantId, tenantId); connectionRequestIdentity.Claims.Add(ClaimsConstants.ArmClaimNames.ObjectId, objectId); RequestCorrelationContext.Current.SetAuthenticationIdentity(connectionRequestIdentity); }
public string GetRequestKey(HttpRequestMessage request, RequestIdentity identity = null) { if (identity == null) { identity = new RequestIdentity { ClientId = GetClientId(request), Endpoint = System.Web.HttpContext.Current?.Request?.Path?.ToLower() }; } var endpoint = identity.Endpoint.ToLower(); var appPath = System.Web.HttpContext.Current?.Request?.ApplicationPath?.ToLower(); if (!string.IsNullOrWhiteSpace(appPath) && appPath != "/") { endpoint = endpoint.Replace(appPath, ""); } if (!endpoint.StartsWith("/")) { endpoint = "/" + endpoint; } return($"{identity.ClientId}|{endpoint}|{request.Method.Method.ToLower()}"); }
/// <summary> /// 获取匹配的规则 /// </summary> /// <param name="requestIdentity"></param> /// <returns></returns> private List <RateLimitRule> GetMatchingRules(RequestIdentity requestIdentity) { var policyList = _cacheManager.Get <List <RateLimitPolicy> >(RateLimitCacheKey.PolicysKey); if (policyList == null) { policyList = _policyStore.GetPolicys(); _cacheManager.Set(RateLimitCacheKey.PolicysKey, policyList, _options.ProlicyCacheTime); } var limits = new List <RateLimitRule>(); var policy = policyList.FirstOrDefault(x => x.PolicyType == requestIdentity.PolicyType && x.Value == requestIdentity.Value); if (policy != null && policy.Rules != null && policy.Rules.Count > 0) { // 搜索类似规则: "*" 和 "*:/matching_path" var pathLimits = policy.Rules.Where(x => $"*:{requestIdentity.Path}".ContainsIgnoreCase(x.Endpoint)).AsEnumerable(); limits.AddRange(pathLimits); // 搜索类似规则: "matching_verb:/matching_path" var verbLimits = policy.Rules.Where(x => $"{requestIdentity.HttpVerb}:{requestIdentity.Path}".ContainsIgnoreCase(x.Endpoint)).AsEnumerable(); limits.AddRange(verbLimits); } //获取每个周期的最小限制,如 //规则1 * 20/1m //规则2 get:/api/values 10/1m //当前请求为get:/api/values,同时满足规则1和2,在相同周期1m内,取次数最小的10次 limits = limits.GroupBy(x => x.Period).Select(x => x.OrderBy(o => o.Limit)).Select(x => x.First()).ToList(); foreach (var item in limits) { item.PeriodTimespan = ConvertToTimeSpan(item.Period); } limits = limits.OrderBy(x => x.PeriodTimespan).ToList(); return(limits); }
public override void OnActionExecuting(HttpActionContext actionContext) { string endPointName = actionContext.Request.RequestUri.AbsolutePath; #region STEP 1: Get user details like email, IP address, customerid, etc. & fill dictionary requestIdentity = GetIdentity(actionContext); Dictionary <string, string> dictIdentity = new Dictionary <string, string>(); dictIdentity.Add(KeyType.clientKey.ToString(), requestIdentity.clientKey); dictIdentity.Add(KeyType.ip.ToString(), requestIdentity.ipAddress); #endregion #region STEP 2: Get ThrottleData.json file data which is saved in http memory cache. List <Client> clients = (List <Client>)MemoryCacherHelper.GetValue(allClientThrollingPolicyCacheData); Client client = clients.Where(x => x.clientKey == requestIdentity.clientKey).FirstOrDefault(); ThrottlePolicy throttlePolicy = client != null ? client.throttlePolicy : clients[0].throttlePolicy; #endregion #region STEP 3: Filtered whiteList users, throttling not applied to these users. if (throttlePolicy.whiteListClients.Contains(requestIdentity.clientKey) || throttlePolicy.whiteListClients.Contains(requestIdentity.ipAddress)) { return; } #endregion #region Step 4: Apply policy -> unique -> method name + identity key like emil, ip etc. ClientRateLimiting clientRateLimiting = throttlePolicy.clientRateLimiting.Where(p => p.key == _ThrottlePolicyKey).FirstOrDefault(); if (clientRateLimiting != null && !string.IsNullOrEmpty(dictIdentity[clientRateLimiting.keyType.ToString()])) { ApplyAndCheckPolicy(actionContext, clientRateLimiting.policy, dictIdentity[clientRateLimiting.keyType.ToString()] + endPointName); Trace.TraceInformation("******************Identity=>" + clientRateLimiting.keyType.ToString() + " => " + dictIdentity[clientRateLimiting.keyType.ToString()] + "/Method Call=>" + actionContext.Request.RequestUri.AbsoluteUri); } #endregion }
private async Task <string> CallWorkflow(WorkflowConfig workflow, ByteString data) { var req = new HttpRequestMessage(HttpMethod.Post, "http://localhost/workflow"); var content = new System.Net.Http.StringContent(data.ToStringUtf8(), Encoding.UTF8, "application/json"); req.Content = content; var flowConfig = this.workflowEngine.Config; var flowName = workflow.Name; flowConfig.FlowEdgeEnvironmentEndpointUri = new Uri("http://localhost"); using (RequestCorrelationContext.Current.Initialize(apiVersion: FlowConstants.PrivatePreview20190601ApiVersion, localizationLanguage: "en-us")) { var clientRequestIdentity = new RequestIdentity { Claims = new Dictionary <string, string>(), IsAuthenticated = true, }; clientRequestIdentity.AuthorizeRequest(RequestAuthorizationSource.Direct); RequestCorrelationContext.Current.SetAuthenticationIdentity(clientRequestIdentity); var flow = await FindExistingFlow(workflow.Name); var triggerName = flow.Definition.Triggers.Keys.Single(); var trigger = flow.Definition.GetTrigger(triggerName); var ct = CancellationToken.None; if (trigger.IsFlowRecurrentTrigger() || trigger.IsNotificationTrigger()) { await this.workflowEngine.Engine .RunFlowRecurrentTrigger( flow : flow, flowName : flowName, triggerName : triggerName); return(""); } else { var triggerOutput = this.workflowEngine.Engine.GetFlowHttpEngine().GetOperationOutput(req, flowConfig.EventSource, ct).Result; var resp = await this.workflowEngine.Engine .RunFlowPushTrigger( request : req, context : new FlowDataPlaneContext(flow), trigger : trigger, subscriptionId : EdgeFlowConfiguration.EdgeSubscriptionId, resourceGroup : EdgeFlowConfiguration.EdgeResourceGroupName, flowName : flowName, triggerName : triggerName, triggerOutput : triggerOutput, clientCancellationToken : ct); var returnContent = await resp.Content.ReadAsStringAsync(); if (!resp.IsSuccessStatusCode) { Console.WriteLine($"Error invoking workflow. Status code: {0}. Reason: {1}. Return message: {2}", resp.StatusCode.ToString(), resp.ReasonPhrase, returnContent); } return(returnContent); } } }
internal static async Task <Result> GetToken( string clientId, string clientSecret, string state, string redirectUri, string htmlResponseToShowInBrowser) { // Creates an HttpListener to listen for requests on that redirect URI. var http = new HttpListener(); http.Prefixes.Add(redirectUri); Debug("Listening on " + redirectUri); http.Start(); // Creates the OAuth 2.0 authorization request. RequestIdentity.Request(clientId, state, redirectUri); // Waits for the OAuth authorization response. var context = await http.GetContextAsync(); // Brings the Console to Focus. ConsoleHack.BringConsoleToFront(); // Sends an HTTP response to the browser. var response = context.Response; var buffer = System.Text.Encoding.UTF8.GetBytes(htmlResponseToShowInBrowser); response.ContentLength64 = buffer.Length; var responseOutput = response.OutputStream; Task responseTask = responseOutput.WriteAsync( buffer, 0, buffer.Length).ContinueWith((task) => { responseOutput.Close(); http.Stop(); Debug("HTTP server stopped."); }); // Checks for errors. if (context.Request.QueryString.Get("error") != null) { return(new Result() { Token = null, Error = string.Format("OAuth authorization error: {0}.", context.Request.QueryString.Get("error")) }); } if (context.Request.QueryString.Get("code") == null || context.Request.QueryString.Get("state") == null) { return(new Result() { Token = null, Error = "Malformed authorization response. " + context.Request.QueryString }); } // extracts the code var code = context.Request.QueryString.Get("code"); var incoming_state = context.Request.QueryString.Get("state"); // Compares the receieved state to the expected value, to ensure that // this app made the request which resulted in authorization. if (incoming_state != state) { return(new Result() { Token = null, Error = string.Format( "Received request with invalid state ({0})", incoming_state) }); } Debug("Authorization code: " + code); return(new Result() { Token = await RequestToken.Get(clientId, clientSecret, code, redirectUri, state), Error = null }); }
public ExternalTableRateEnrty GetEntry(HttpRequestMessage request, RequestIdentity identity = null) { return(zAppDev.DotNet.Framework.Utilities.ApplicationCache.Get <List <ExternalTableRateEnrty> >(GetRequestKey(request, identity))?.FirstOrDefault()); }
public RateLimits Get(HttpRequestMessage request, RequestIdentity identity) { return(GetEntry(request, identity)?.Limits?.NotNullable()); }
public void UpdateIdentity(RequestIdentity identity, HttpRequestMessage request) { identity.ClientId = GetClientId(request); identity.ProductName = GetEntry(request)?.ProductName + "_" + AppCode.BaseViewPage <string> .AppVersion; }
public bool AuthentificateUserOrder(OrderModel order, RequestIdentity user) { return(order.Customer?.UserId == user.UserId || user.HasAdminAccess || user.HasAgentAccess); }
/// <summary> /// 日志 /// </summary> /// <param name="requestIdentity"></param> /// <param name="counter"></param> /// <param name="rule"></param> public void LogBlockedRequest(RequestIdentity requestIdentity, RateLimitCounter counter, RateLimitRule rule) { var log = $"{requestIdentity.RequestPath}\r\n已限制来自[{requestIdentity.PolicyType.ToString()}]{requestIdentity.Value}的请求 {requestIdentity.HttpVerb}:{requestIdentity.Path}\r\n匹配规则: {rule.Endpoint},{rule.Limit}/{rule.Period}\r\n计数器: [{ComputeCounterKey(requestIdentity, rule)}] {counter.TotalRequests},{counter.Timestamp.ToString("yyyy-MM-dd HH:mm:ss")}"; _options.LogHandler.Invoke(log); }