public void Equals(SignatureHelper helper, object obj, bool expected) { Assert.Equal(expected, helper.Equals(obj)); if (obj is SignatureHelper && expected == true) { Assert.Equal(helper.GetHashCode(), obj.GetHashCode()); } }
public static void NegativeTest_ViaLdftn() { /* * .locals init (native int V_0) * IL_0000: nop * IL_0001: ldftn void ConsoleApplication1.Program::callback(int32) * IL_0007: stloc.0 * IL_0008: ldc.i4.s 12 * IL_000a: ldloc.0 * IL_000b: calli void(int32) * IL_0010: nop * IL_0011: ret */ DynamicMethod testNativeCallable = new DynamicMethod("TestNativeCallableLdftn", null, null, typeof(Program).Module); ILGenerator il = testNativeCallable.GetILGenerator(); il.DeclareLocal(typeof(IntPtr)); il.Emit(OpCodes.Nop); il.Emit(OpCodes.Ldftn, typeof(Program).GetMethod("LdftnCallback")); il.Emit(OpCodes.Stloc_0); il.Emit(OpCodes.Ldc_I4, 12); il.Emit(OpCodes.Ldloc_0); SignatureHelper sig = SignatureHelper.GetMethodSigHelper(typeof(Program).Module, null, new Type[] { typeof(int) }); sig.AddArgument(typeof(int)); // il.EmitCalli is not available and the below is not correct il.Emit(OpCodes.Calli, sig); il.Emit(OpCodes.Nop); il.Emit(OpCodes.Ret); NativeMethodInvoker testNativeMethod = (NativeMethodInvoker)testNativeCallable.CreateDelegate(typeof(NativeMethodInvoker)); testNativeMethod(); }
public void GetPropertySigHelper_Module_Type_TypeArray_NullModule_DoesNotThrow() { SignatureHelper helper = SignatureHelper.GetPropertySigHelper(null, typeof(string), new Type[] { typeof(string), typeof(int) }); Assert.Equal(5, helper.GetSignature().Length); }
/// <summary> /// Sets the digital signature on the specified file. /// </summary> /// <param name="filePath"> /// The name of the file on which to perform the action. /// </param> /// <returns> /// The signature on the specified file. /// </returns> protected override Signature PerformAction(string filePath) { SigningOption option = GetSigningOption(IncludeChain); if (Certificate == null) { throw PSTraceSource.NewArgumentNullException("certificate"); } // // if the cert is not good for signing, we cannot // process any more files. Exit the command. // if (!SecuritySupport.CertIsGoodForSigning(Certificate)) { Exception e = PSTraceSource.NewArgumentException( "certificate", SignatureCommands.CertNotGoodForSigning); throw e; } if (!ShouldProcess(filePath)) { return(null); } FileInfo readOnlyFileInfo = null; try { if (this.Force) { try { // remove readonly attributes on the file FileInfo fInfo = new(filePath); if (fInfo != null) { // Save some disk write time by checking whether file is readonly.. if ((fInfo.Attributes & FileAttributes.ReadOnly) == FileAttributes.ReadOnly) { // remember to reset the read-only attribute later readOnlyFileInfo = fInfo; // Make sure the file is not read only fInfo.Attributes &= ~(FileAttributes.ReadOnly); } } } // These are the known exceptions for File.Load and StreamWriter.ctor catch (ArgumentException e) { ErrorRecord er = new( e, "ForceArgumentException", ErrorCategory.WriteError, filePath); WriteError(er); return(null); } catch (IOException e) { ErrorRecord er = new( e, "ForceIOException", ErrorCategory.WriteError, filePath); WriteError(er); return(null); } catch (UnauthorizedAccessException e) { ErrorRecord er = new( e, "ForceUnauthorizedAccessException", ErrorCategory.PermissionDenied, filePath); WriteError(er); return(null); } catch (NotSupportedException e) { ErrorRecord er = new( e, "ForceNotSupportedException", ErrorCategory.WriteError, filePath); WriteError(er); return(null); } catch (System.Security.SecurityException e) { ErrorRecord er = new( e, "ForceSecurityException", ErrorCategory.PermissionDenied, filePath); WriteError(er); return(null); } } // // ProcessRecord() code in base class has already // ascertained that filePath really represents an existing // file. Thus we can safely call GetFileSize() below. // if (SecurityUtils.GetFileSize(filePath) < 4) { // Note that the message param comes first string message = string.Format( System.Globalization.CultureInfo.CurrentCulture, UtilsStrings.FileSmallerThan4Bytes, filePath); PSArgumentException e = new(message, nameof(filePath)); ErrorRecord er = SecurityUtils.CreateInvalidArgumentErrorRecord( e, "SignatureCommandsBaseFileSmallerThan4Bytes" ); WriteError(er); return(null); } return(SignatureHelper.SignFile(option, filePath, Certificate, TimestampServer, _hashAlgorithm)); } finally { // reset the read-only attribute if (readOnlyFileInfo != null) { readOnlyFileInfo.Attributes |= FileAttributes.ReadOnly; } } }
private static string GetMethodSignature(MethodInfo method, InterceptMethodAttribute attribute) { var returnType = method.ReturnType; var parameters = method.GetParameters().Select(p => p.ParameterType).ToArray(); var requiredParameterTypes = new[] { typeof(int), typeof(int), typeof(long) }; var lastParameterTypes = parameters.Skip(parameters.Length - requiredParameterTypes.Length); if (attribute.MethodReplacementAction == MethodReplacementActionType.ReplaceTargetMethod) { if (!lastParameterTypes.SequenceEqual(requiredParameterTypes)) { throw new Exception( $"Method {method.DeclaringType.FullName}.{method.Name}() does not meet parameter requirements. " + "Wrapper methods must have at least 3 parameters and the last 3 must be of types Int32 (opCode), Int32 (mdToken), and Int64 (moduleVersionPtr)."); } } else if (attribute.MethodReplacementAction == MethodReplacementActionType.InsertFirst) { if (attribute.CallerAssembly == null || attribute.CallerType == null || attribute.CallerMethod == null) { throw new Exception( $"Method {method.DeclaringType.FullName}.{method.Name}() does not meet InterceptMethodAttribute requirements. " + "Currently, InsertFirst methods must have CallerAssembly, CallerType, and CallerMethod defined. " + $"Current values: CallerAssembly=\"{attribute.CallerAssembly}\", CallerType=\"{attribute.CallerType}\", CallerMethod=\"{attribute.CallerMethod}\""); } else if (parameters.Any()) { throw new Exception( $"Method {method.DeclaringType.FullName}.{method.Name}() does not meet parameter requirements. " + "Currently, InsertFirst methods must have zero parameters."); } else if (returnType != typeof(void)) { throw new Exception( $"Method {method.DeclaringType.FullName}.{method.Name}() does not meet return type requirements. " + "Currently, InsertFirst methods must have a void return type."); } } var signatureHelper = SignatureHelper.GetMethodSigHelper(method.CallingConvention, returnType); signatureHelper.AddArguments(parameters, requiredCustomModifiers: null, optionalCustomModifiers: null); var signatureBytes = signatureHelper.GetSignature(); if (method.IsGenericMethod) { // if method is generic, fix first byte (calling convention) // and insert a second byte with generic parameter count const byte IMAGE_CEE_CS_CALLCONV_GENERIC = 0x10; var genericArguments = method.GetGenericArguments(); var newSignatureBytes = new byte[signatureBytes.Length + 1]; newSignatureBytes[0] = (byte)(signatureBytes[0] | IMAGE_CEE_CS_CALLCONV_GENERIC); newSignatureBytes[1] = (byte)genericArguments.Length; Array.Copy(signatureBytes, 1, newSignatureBytes, 2, signatureBytes.Length - 1); signatureBytes = newSignatureBytes; } return(string.Join(" ", signatureBytes.Select(b => b.ToString("X2")))); }
internal static void Emit(ILGenerator il, OpCode opcode, SignatureHelper signature) { LogIL(il, opcode, signature); il.Emit(opcode, signature); }
/// <summary> /// Gets the signature from the specified file. /// </summary> /// <param name="filePath"> /// The name of the file on which to perform the action. /// </param> /// <returns> /// The signature on the specified file. /// </returns> protected override Signature PerformAction(string filePath) { return(SignatureHelper.GetSignature(filePath, null)); }
public void GetMethodSigHelper_Module_Type_TypeArray_NullObjectInParameterType_ThrowsArgumentNullException() { ModuleBuilder module = Helpers.DynamicModule(); AssertExtensions.Throws <ArgumentNullException>("argument", () => SignatureHelper.GetMethodSigHelper(module, typeof(string), new Type[] { typeof(char), null })); }
public OmniSignature GetOmniSignature() { return(_signature ?? (_signature = SignatureHelper.GetOmniSignature(this))); }
public void Emit(OpCode opcode, SignatureHelper signature) { Debug.WriteLine($"emit: {opcode} {signature}"); Instance.Emit(opcode, signature); }
public async Task PostNotJson() { string payload = "test"; var request = new HttpRequestMessage(new HttpMethod("POST"), new Uri(client.BaseAddress, "/queue")); request.Content = new StringContent(payload); request.Headers.Date = DateTimeOffset.UtcNow; var nonce = Guid.NewGuid().ToString(); request.Headers.Add("Nonce", nonce); string authenticationSignature = SignatureHelper.Calculate("devhmacsecret", SignatureHelper.Generate(request.Headers.Date.Value, payload, request.Method.Method, request.RequestUri.AbsolutePath, request.RequestUri.Query, nonce)); request.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("HMAC", "DevQueueService:" + authenticationSignature); using var response = await client.SendAsync(request, CancellationToken.None); Assert.AreEqual(System.Net.HttpStatusCode.UnsupportedMediaType, response.StatusCode); }
private string SendHttpRequest(string url, string req, WebHeaderCollection webheader, string method) { string resultJson; try { System.Net.ServicePointManager.Expect100Continue = false; byte[] postData = Encoding.UTF8.GetBytes(req); // 将提交的字符串数据转换成字节数组 var list = JsonConvert.DeserializeObject <Dictionary <string, object> >(req); if (method == "GET") { string retStr = ""; foreach (var key in list) { retStr += string.Format("{0}={1}&", key.Key, key.Value); } retStr = retStr.TrimEnd('&'); url = url.Contains("?") ? url + retStr : url + "?" + retStr; url = url.TrimEnd('?'); } else if (method.Contains("LINE")) { foreach (var key in list) { if (key.Value != null) { url = url.Replace("{" + key.Key + "}", key.Value.ToString()); } } } list.Remove("access_token"); list.Remove("errcode"); list.Remove("errmsg"); var datastr = JsonConvert.SerializeObject(list); postData = Encoding.UTF8.GetBytes(datastr); //#if DEBUG // url += "&debug=1"; //#endif var request = WebRequest.Create(url) as HttpWebRequest; if (request != null) { request.Method = method.Replace("LINE", ""); #region 提交请求数据 if (method.Contains("POST")) { request.ContentType = "application/json; charset=UTF-8"; request.ContentLength = postData.Length; if (url.Contains("ims.jsu.edu.cn")) { string t = "" + DateTimeHelper.CurrentUnixTimeMillis(); webheader.Add("Accept", "*/*"); webheader.Add("apikey", "portal"); webheader.Add("timestamp", t); var sign = SignatureHelper.createSignature(webheader, "/ims/api/account/update/" + list["userid"] + "/" + "userpassword", "MIIBSwIBADCCASwGByqGSM44BAEwggEfAoGBAP1_U4EddRIpUt9KnC7s5Of2EbdSPO9EAMMeP4C2USZpRV1AIlH7WT2NWPq_xfW6MPbLm1Vs14E7gB00b_JmYLdrmVClpJ-f6AR7ECLCT7up1_63xhv4O1fnxqimFQ8E-4P208UewwI1VBNaFpEy9nXzrith1yrv8iIDGZ3RSAHHAhUAl2BQjxUjC8yykrmCouuEC_BYHPUCgYEA9-GghdabPd7LvKtcNrhXuXmUr7v6OuqC-VdMCz0HgmdRWVeOutRZT-ZxBxCBgLRJFnEj6EwoFhO3zwkyjMim4TwWeotUfI0o4KOuHiuzpnWRbqN_C_ohNWLx-2J6ASQ7zKTxvqhRkImog9_hWuWfBpKLZl6Ae1UlZAFMO_7PSSoEFgIUKCKbCTC3wcDaQv25MjXrv4vtiF0"); webheader.Add("signature", sign); } //读写超时 #region 提交请求数据 using (Stream outputStream = request.GetRequestStream()) { outputStream.Write(postData, 0, postData.Length); outputStream.Close(); } #endregion } #endregion } #region 获取响应json HttpWebResponse response; try { response = (HttpWebResponse)request.GetResponse(); } catch (WebException ex) { response = (HttpWebResponse)ex.Response; } using (Stream responseStream = response.GetResponseStream()) { //尝试修改流不可读的问题 if (!response.GetResponseStream().CanRead) { resultJson = "{\"code\":-1,\"message\":\"流不可读\"}"; } else { using (var reader = new StreamReader(responseStream, Encoding.UTF8)) { resultJson = reader.ReadToEnd(); if (resultJson == "false") { resultJson = "{\"errcode\":-1}"; } else if (resultJson == "true") { resultJson = "{\"errcode\":0}"; } } } responseStream.Flush(); } #endregion } catch (Exception ex) { resultJson = "{\"code\":-1,\"message\":\"" + ex.Message + "\"}"; } return(resultJson); }
/// <summary> /// ConfigureServices /// </summary> /// <param name="services"></param> public override void ConfigureServices(IServiceCollection services) { // Background Service services.AddSingleton <IBackgroundTask, IdleBackgroundTask>(); services.AddSingleton <IBackgroundTask, DailyBackgroundTask>(); // StackExchange.Redis.Extensions // https://github.com/imperugo/StackExchange.Redis.Extensions var redisConfiguration = _configuration.GetSection("RedisSettings").Get <RedisConfiguration>(); services.AddSingleton(redisConfiguration); services.AddSingleton <IRedisCacheClient, RedisCacheClient>(); services.AddSingleton <IRedisCacheConnectionPoolManager, RedisCacheConnectionPoolManager>(); services.AddSingleton <IRedisDefaultCacheClient, RedisDefaultCacheClient>(); services.AddSingleton <ISerializer, NewtonsoftSerializer>(); var redisKeyPrefix = !redisConfiguration.KeyPrefix.IsNullOrWhiteSpace() ? redisConfiguration.KeyPrefix : _environment.ApplicationName; // Cache services.AddDistributedRedisCache(options => { options.Configuration = "localhost"; options.InstanceName = redisKeyPrefix + ":"; }); services.AddMemoryCache(); // Cors services.AddCors(options => options.AddPolicy("DefaultPolicy", builder => builder.WithOrigins("http://localhost:9090", "http://localhost:8080").AllowAnyMethod().AllowAnyHeader().AllowCredentials()) // builder => builder.AllowAnyOrigin.AllowAnyMethod().AllowAnyHeader().AllowCredentials()) ); // Cookie services.Configure <CookiePolicyOptions>(options => { options.CheckConsentNeeded = context => false; // 需保持为 false, 否则 Web API 不会 Set-Cookie 。 options.MinimumSameSitePolicy = SameSiteMode.None; }); // Session services.AddSession(options => { options.IdleTimeout = TimeSpan.FromMinutes(10); options.Cookie.Name = ".Tubumu.Session"; options.Cookie.HttpOnly = true; }); // HTTP Client services.AddHttpClient(); // ApiBehaviorOptions services.Configure <ApiBehaviorOptions>(options => { options.InvalidModelStateResponseFactory = context => new OkObjectResult(new ApiResult { Code = 400, Message = context.ModelState.FirstErrorMessage() }); }); // Authentication services.AddSingleton <IAuthorizationPolicyProvider, TubumuAuthorizationPolicyProvider>(); services.AddSingleton <ITokenService, TokenService>(); var tokenValidationSettings = _configuration.GetSection("TokenValidationSettings").Get <TokenValidationSettings>(); services.AddSingleton(tokenValidationSettings); services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) .AddJwtBearer(options => { options.TokenValidationParameters = new TokenValidationParameters { ValidIssuer = tokenValidationSettings.ValidIssuer, ValidateIssuer = true, ValidAudience = tokenValidationSettings.ValidAudience, ValidateAudience = true, IssuerSigningKey = SignatureHelper.GenerateSigningKey(tokenValidationSettings.IssuerSigningKey), ValidateIssuerSigningKey = true, ValidateLifetime = tokenValidationSettings.ValidateLifetime, ClockSkew = TimeSpan.FromSeconds(tokenValidationSettings.ClockSkewSeconds), }; // We have to hook the OnMessageReceived event in order to // allow the JWT authentication handler to read the access // token from the query string when a WebSocket or // Server-Sent Events request comes in. options.Events = new JwtBearerEvents { OnMessageReceived = context => { var accessToken = context.Request.Query["access_token"]; // If the request is for our hub... var path = context.HttpContext.Request.Path; if (!string.IsNullOrEmpty(accessToken) && path.StartsWithSegments("/hubs")) { // Read the token out of the query string context.Token = accessToken; } return(Task.CompletedTask); }, OnAuthenticationFailed = context => { _logger.LogError($"Authentication Failed(OnAuthenticationFailed): {context.Request.Path} Error: {context.Exception}"); if (context.Exception.GetType() == typeof(SecurityTokenExpiredException)) { context.Response.Headers.Add("Token-Expired", "true"); } return(Task.CompletedTask); }, OnChallenge = context => { _logger.LogError($"Authentication Challenge(OnChallenge): {context.Request.Path}"); // TODO: (alby)为不同客户端返回不同的内容 var result = new ApiResultUrl() { Code = 400, Message = "Authentication Challenge", // TODO: (alby)前端 IsDevelopment 为 true 时不返回 Url Url = _environment.IsProduction() ? tokenValidationSettings.LoginUrl : null, }; var body = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(result)); context.Response.StatusCode = StatusCodes.Status401Unauthorized; context.Response.ContentType = "application/json"; context.Response.Body.Write(body, 0, body.Length); context.HandleResponse(); return(Task.CompletedTask); } }; }); // JSON Date format void JsonSetup(MvcJsonOptions options) => options.SerializerSettings.DateFormatString = "yyyy-MM-dd HH:mm:ss"; services.Configure((Action <MvcJsonOptions>)JsonSetup); // SignalR services.AddSignalR(); services.Replace(ServiceDescriptor.Singleton(typeof(IUserIdProvider), typeof(NameUserIdProvider))); // AutoMapper services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies()); AutoMapperInitalizer.Initialize(); // RabbitMQ services.AddSingleton <IConnectionPool, ConnectionPool>(); services.AddSingleton <IChannelPool, ChannelPool>(); // Swagger services.AddSwaggerGen(c => { c.SwaggerDoc("v1.0", new Info { Title = _environment.ApplicationName + " API", Version = "v1.0" }); c.AddSecurityDefinition("Bearer", new ApiKeyScheme { Description = "权限认证(数据将在请求头中进行传输) 参数结构: \"Authorization: Bearer {token}\"", Name = "Authorization", In = "header", Type = "apiKey" }); c.AddSecurityRequirement(new Dictionary <string, IEnumerable <string> > { { "Bearer", new string[] { } }, }); c.DescribeAllEnumsAsStrings(); c.DocumentFilter <HiddenApiDocumentFilter>(); IncludeXmlCommentsForModules(c); c.OrderActionsBy(m => m.ActionDescriptor.DisplayName); c.ApplyGrouping(); }); // Add Hangfire services. //services.AddHangfire(configuration => configuration // .SetDataCompatibilityLevel(CompatibilityLevel.Version_170) // .UseSimpleAssemblyNameTypeSerializer() // .UseRecommendedSerializerSettings() // .UseSqlServerStorage(_configuration.GetConnectionString("Tubumu"), new SqlServerStorageOptions // { // CommandBatchMaxTimeout = TimeSpan.FromMinutes(5), // SlidingInvisibilityTimeout = TimeSpan.FromMinutes(5), // QueuePollInterval = TimeSpan.FromSeconds(15), // 作业队列轮询间隔。默认值为15秒。 // JobExpirationCheckInterval = TimeSpan.FromHours(1), // 作业到期检查间隔(管理过期记录)。默认值为1小时。 // UseRecommendedIsolationLevel = true, // UsePageLocksOnDequeue = true, // DisableGlobalLocks = true // })); services.AddHangfire(configuration => { // 推荐使用 ConnectionMultiplexer,见:https://github.com/marcoCasamento/Hangfire.Redis.StackExchange 。 // 但是存在 StackExchange.Redis.StrongName 和 StackExchange.Redis 冲突问题。 configuration.UseRedisStorage("localhost", new RedisStorageOptions { Prefix = $"{redisKeyPrefix}:hangfire:", Db = 9, }); }); // Add the processing server as IHostedService services.AddHangfireServer(); // Data version services.AddSingleton <IDataVersionService, DataVersionService>(); }
public static ImmutableList <int?> GetEvaluationStackDepths(DisassembledMethod disassembledMethod, ReadOnlyCollection <ConstantPoolEntry> constantPool, ReadOnlyCollection <ExceptionTableEntry> exceptionTable) { Contract.Requires <ArgumentNullException>(disassembledMethod != null, "disassembledMethod"); Contract.Requires <ArgumentNullException>(constantPool != null, "constantPool"); Contract.Requires <ArgumentNullException>(exceptionTable != null, "exceptionTable"); Contract.Ensures(Contract.Result <ImmutableList <int?> >() != null); Contract.Ensures(Contract.Result <ImmutableList <int?> >().Count == disassembledMethod.Instructions.Count); int?[] depths = new int?[disassembledMethod.Instructions.Count]; Queue <int> workQueue = new Queue <int>(); // can obviously start at the beginning of the method depths[0] = 0; workQueue.Enqueue(0); // can also start inside each exception handler foreach (var entry in exceptionTable) { int nextIndex = disassembledMethod.Instructions.FindIndex(i => i.Offset == entry.HandlerOffset); if (!depths[nextIndex].HasValue) { depths[nextIndex] = 1; workQueue.Enqueue(nextIndex); } } while (workQueue.Count > 0) { int index = workQueue.Dequeue(); JavaInstruction instruction = disassembledMethod.Instructions[index]; int netImpact; List <string> argumentSignatures = null; string returnTypeSignature = null; if (instruction.OpCode.FlowControl == JavaFlowControl.Call) { IConstantMemberReference memberReference = (IConstantMemberReference)constantPool[instruction.Operands.ConstantPoolIndex - 1]; ConstantNameAndType nameAndType = (ConstantNameAndType)constantPool[memberReference.NameAndTypeIndex - 1]; ConstantUtf8 descriptor = (ConstantUtf8)constantPool[nameAndType.DescriptorIndex - 1]; string signature = descriptor.Value; SignatureHelper.ParseMethodSignature(signature, out argumentSignatures, out returnTypeSignature); } switch (instruction.OpCode.StackBehaviorPop) { case JavaStackBehavior.Pop0: netImpact = 0; break; case JavaStackBehavior.Pop1: case JavaStackBehavior.PopI: case JavaStackBehavior.PopI8: case JavaStackBehavior.PopR4: case JavaStackBehavior.PopR8: case JavaStackBehavior.PopRef: netImpact = -1; break; case JavaStackBehavior.Pop1_Pop1: case JavaStackBehavior.PopI_PopI: case JavaStackBehavior.PopI8_PopI8: case JavaStackBehavior.PopI8_PopI: case JavaStackBehavior.PopR4_PopR4: case JavaStackBehavior.PopR8_PopR8: case JavaStackBehavior.PopRef_Pop1: case JavaStackBehavior.PopRef_PopI: netImpact = -2; break; case JavaStackBehavior.PopRef_PopI_PopI: case JavaStackBehavior.PopRef_PopI_PopI8: case JavaStackBehavior.PopRef_PopI_PopR4: case JavaStackBehavior.PopRef_PopI_PopR8: case JavaStackBehavior.PopRef_PopI_PopRef: case JavaStackBehavior.PopRef_PopRef: netImpact = -3; break; case JavaStackBehavior.PopVar: switch (instruction.OpCode.OpCode) { case JavaOpCodeTag.Dup_x2: case JavaOpCodeTag.Dup2: case JavaOpCodeTag.Dup2_x1: case JavaOpCodeTag.Dup2_x2: netImpact = 1; break; case JavaOpCodeTag.Invokestatic: netImpact = -argumentSignatures.Count; if (returnTypeSignature != "V") { netImpact++; } break; case JavaOpCodeTag.Invokeinterface: case JavaOpCodeTag.Invokespecial: case JavaOpCodeTag.Invokevirtual: netImpact = -argumentSignatures.Count - 1; if (returnTypeSignature != "V") { netImpact++; } break; case JavaOpCodeTag.Multianewarray: netImpact = -instruction.Operands.Dimensions; break; default: throw new FormatException(); } break; default: throw new FormatException(); } switch (instruction.OpCode.StackBehaviorPush) { case JavaStackBehavior.Push0: break; case JavaStackBehavior.Push1: case JavaStackBehavior.PushI: case JavaStackBehavior.PushI8: case JavaStackBehavior.PushR4: case JavaStackBehavior.PushR8: case JavaStackBehavior.PushRef: case JavaStackBehavior.PushRet: netImpact++; break; case JavaStackBehavior.Push1_Push1: netImpact += 2; break; case JavaStackBehavior.PushVar: // these are all handled in the pop section break; default: throw new FormatException(); } switch (instruction.OpCode.FlowControl) { case JavaFlowControl.Next: case JavaFlowControl.Break: case JavaFlowControl.Call: case JavaFlowControl.ConditionalBranch: case JavaFlowControl.Special: if (!depths[index + 1].HasValue) { depths[index + 1] = depths[index] + netImpact; workQueue.Enqueue(index + 1); } if (instruction.OpCode.FlowControl == JavaFlowControl.ConditionalBranch) { goto case JavaFlowControl.Branch; } break; case JavaFlowControl.Branch: switch (instruction.OpCode.OpCode) { case JavaOpCodeTag.Lookupswitch: { LookupSwitchData switchData = (LookupSwitchData)disassembledMethod.SwitchData[instruction.Operands.SwitchDataIndex]; foreach (var pair in switchData.Pairs) { int nextIndex = disassembledMethod.Instructions.FindIndex(i => i.Offset == instruction.Offset + pair.Value); if (!depths[nextIndex].HasValue) { depths[nextIndex] = depths[index] + netImpact; workQueue.Enqueue(nextIndex); } } break; } case JavaOpCodeTag.Tableswitch: { TableSwitchData switchData = (TableSwitchData)disassembledMethod.SwitchData[instruction.Operands.SwitchDataIndex]; foreach (var offset in switchData.Offsets) { int nextIndex = disassembledMethod.Instructions.FindIndex(i => i.Offset == instruction.Offset + offset); if (!depths[nextIndex].HasValue) { depths[nextIndex] = depths[index] + netImpact; workQueue.Enqueue(nextIndex); } } break; } default: { // single branch target int nextIndex = disassembledMethod.Instructions.FindIndex(i => i.Offset == instruction.Offset + instruction.Operands.BranchTarget); if (!depths[nextIndex].HasValue) { depths[nextIndex] = depths[index] + netImpact; workQueue.Enqueue(nextIndex); } break; } } break; case JavaFlowControl.Return: // no work in this method following this instruction break; case JavaFlowControl.Throw: // 'catch' blocks are handled separately break; case JavaFlowControl.Meta: throw new NotImplementedException(); default: throw new FormatException(); } } return(new ImmutableList <int?>(depths)); }
internal void PrepareRequest(System.Net.Http.HttpClient client, System.Net.Http.HttpRequestMessage request, string url) { if (request.Method == HttpMethod.Post) { var uri = new Uri(url); var urlPath = uri.AbsolutePath.Replace("/openapi/", ""); //var queryString = ParseQueryString(uri.Query); var content_ = request.Content as System.Net.Http.MultipartFormDataContent; var content2_ = request.Content as System.Net.Http.FormUrlEncodedContent; if (content_ != null) { ////返回的数据格式(可选) //content_.Add(new System.Net.Http.StringContent("json2"), "_aop_responseFormat");//json2,xml2,xml,json ////时间格式(可选) //content_.Add(new System.Net.Http.StringContent("yyyyMMddHHmmssSSS"), "_aop_datePattern"); ////时间戳(可选) //content_.Add(new System.Net.Http.StringContent(DateTimeHelper.GetCurrentTimestamp().ToString()), "_aop_timestamp"); //授权码 content_.Add(new System.Net.Http.StringContent(this._accessToken), "access_token"); //签名 //var queryString = System.Web.HttpUtility.ParseQueryString(uri.Query); //var dictParaQuery = queryString.AllKeys.ToDictionary(f => f, f => queryString.Get(f)); var dictPara = content_.ToDictionary(f => f.Headers.ContentDisposition.Name, f => f.ReadAsStringAsync().Result); //var dictPara = dictParaQuery.Concat(dictParaForm).ToDictionary(f => f.Key, f => f.Value); var sign = SignatureHelper.HmacSha1(urlPath, dictPara, this._clientSecret); var signStr = SignatureHelper.ToHex(sign); content_.Add(new System.Net.Http.StringContent(signStr), "_aop_signature"); } else if (content2_ != null) { var queryString = ParseQueryString(content2_.ReadAsStringAsync().Result); var dictPara = queryString.AllKeys.ToDictionary(f => f, f => queryString.Get(f)); queryString["_aop_responseFormat"] = "json2"; queryString["_aop_datePattern"] = "yyyyMMddHHmmssSSS"; queryString["_aop_timestamp"] = DateTimeHelper.GetCurrentTimestamp().ToString(); queryString["access_token"] = this._accessToken; var sign = SignatureHelper.HmacSha1(urlPath, dictPara, this._clientSecret); var signStr = SignatureHelper.ToHex(sign); dictPara.Add("_aop_signature", signStr); request.Content = new System.Net.Http.FormUrlEncodedContent(dictPara); } else { var dictPara = new System.Collections.Generic.Dictionary <string, string> { //{ "_aop_responseFormat", "json2" }, //{ "_aop_datePattern", "yyyyMMddHHmmssSSS" }, //{ "_aop_timestamp", DateTimeHelper.GetCurrentTimestamp().ToString() }, { "access_token", this._accessToken } }; var sign = SignatureHelper.HmacSha1(urlPath, dictPara, this._clientSecret); var signStr = SignatureHelper.ToHex(sign); dictPara.Add("_aop_signature", signStr); request.Content = new System.Net.Http.FormUrlEncodedContent(dictPara); var ssss = new System.Net.Http.FormUrlEncodedContent(dictPara).ReadAsStringAsync().Result; } } }
protected virtual SignatureAndHashAlgorithm SelectSignatureAlgorithm() { return(SignatureHelper.SelectSignatureType(HandshakeParameters)); }
public virtual void Emit(OpCode opcode, SignatureHelper signature);
public virtual void Emit (OpCode opcode, SignatureHelper signature) { throw new PlatformNotSupportedException (); }
public async Task PostExecuteWorkerNotExists() { string payload = System.Text.Json.JsonSerializer.Serialize(new EnqueueRequest { Payload = "test", QueueName = "test" }); var request = new HttpRequestMessage(new HttpMethod("POST"), new Uri(client.BaseAddress, "/queue")) { Content = new StringContent(payload, Encoding.UTF8, "application/json") }; request.Headers.Date = DateTimeOffset.UtcNow; var nonce = Guid.NewGuid().ToString(); request.Headers.Add("Nonce", nonce); string authenticationSignature = SignatureHelper.Calculate("devhmacsecret", SignatureHelper.Generate(request.Headers.Date.Value, payload, request.Method.Method, request.RequestUri.AbsolutePath, request.RequestUri.Query, nonce)); request.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("HMAC", "DevQueueService:" + authenticationSignature); using var response = await client.SendAsync(request, CancellationToken.None); Assert.AreEqual(System.Net.HttpStatusCode.InternalServerError, response.StatusCode); }
public void GetPropertySigHelper_NullTypeInParameterTypes_ThrowsArgumentNullException() { Type[] types = new Type[] { typeof(short), null }; Type[][] customModifiers = new Type[][] { types, types }; ModuleBuilder module = Helpers.DynamicModule(); AssertExtensions.Throws <ArgumentNullException>("optionalCustomModifiers", () => SignatureHelper.GetPropertySigHelper(module, typeof(string), types, types, types, customModifiers, customModifiers)); }
public void GetMethodSigHelper_CallingConventions_Type_Length_ReturnsThree(CallingConventions callingConventions, Type type) { SignatureHelper helper = SignatureHelper.GetMethodSigHelper(callingConventions, type); Assert.Equal(3, helper.GetSignature().Length); }
// This method gets called by the runtime. Use this method to add services to the container. // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940 public void ConfigureServices(IServiceCollection services) { services.AddMvc() .AddNewtonsoftJson(options => { var settings = options.SerializerSettings; settings.ContractResolver = new CamelCasePropertyNamesContractResolver(); settings.DateFormatString = "yyyy'-'MM'-'dd' 'HH':'mm':'ss"; // 自定义日期格式。默认是 ISO8601 格式。 settings.Converters = new JsonConverter[] { new EnumStringValueEnumConverter() }; }); // Cache services.AddDistributedRedisCache(options => { options.Configuration = "localhost"; options.InstanceName = "Meeting:"; }); services.AddMemoryCache(); // Cors var corsSettings = Configuration.GetSection("CorsSettings").Get <CorsSettings>(); services.AddCors(options => options.AddPolicy("DefaultPolicy", builder => builder.WithOrigins(corsSettings.Origins).AllowAnyMethod().AllowAnyHeader().AllowCredentials()) //builder => builder.WithOrigins("*").AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader()) ); // Authentication services.AddSingleton <ITokenService, TokenService>(); var tokenValidationSettings = Configuration.GetSection("TokenValidationSettings").Get <TokenValidationSettings>(); services.AddSingleton(tokenValidationSettings); services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) .AddJwtBearer(options => { options.TokenValidationParameters = new TokenValidationParameters { ValidIssuer = tokenValidationSettings.ValidIssuer, ValidateIssuer = true, ValidAudience = tokenValidationSettings.ValidAudience, ValidateAudience = true, IssuerSigningKey = SignatureHelper.GenerateSigningKey(tokenValidationSettings.IssuerSigningKey), ValidateIssuerSigningKey = true, ValidateLifetime = tokenValidationSettings.ValidateLifetime, ClockSkew = TimeSpan.FromSeconds(tokenValidationSettings.ClockSkewSeconds), }; // We have to hook the OnMessageReceived event in order to // allow the JWT authentication handler to read the access // token from the query string when a WebSocket or // Server-Sent Events request comes in. options.Events = new JwtBearerEvents { OnMessageReceived = context => { var accessToken = context.Request.Query["access_token"]; // If the request is for our hub... var path = context.HttpContext.Request.Path; if (!string.IsNullOrEmpty(accessToken) && path.StartsWithSegments("/hubs")) { // Read the token out of the query string context.Token = accessToken; } return(Task.CompletedTask); }, OnAuthenticationFailed = context => { //_logger.LogError($"Authentication Failed(OnAuthenticationFailed): {context.Request.Path} Error: {context.Exception}"); if (context.Exception.GetType() == typeof(SecurityTokenExpiredException)) { context.Response.Headers.Add("Token-Expired", "true"); } return(Task.CompletedTask); }, OnChallenge = async context => { //_logger.LogError($"Authentication Challenge(OnChallenge): {context.Request.Path}"); // TODO: (alby)为不同客户端返回不同的内容 var body = Encoding.UTF8.GetBytes("{\"code\": 400, \"message\": \"Authentication Challenge\"}"); context.Response.StatusCode = StatusCodes.Status401Unauthorized; context.Response.ContentType = "application/json"; await context.Response.Body.WriteAsync(body, 0, body.Length); context.HandleResponse(); } }; }); // SignalR services.AddSignalR(options => { options.EnableDetailedErrors = true; }) .AddNewtonsoftJsonProtocol(options => { var settings = options.PayloadSerializerSettings; settings.ContractResolver = new CamelCasePropertyNamesContractResolver(); settings.DateFormatString = "yyyy'-'MM'-'dd' 'HH':'mm':'ss"; // 自定义日期格式。默认是 ISO8601 格式。 settings.Converters = new JsonConverter[] { new EnumStringValueEnumConverter() }; }); services.Replace(ServiceDescriptor.Singleton(typeof(IUserIdProvider), typeof(NameUserIdProvider))); var mediasoupStartupSettings = Configuration.GetSection("MediasoupStartupSettings").Get <MediasoupStartupSettings>(); var workerSettings = Configuration.GetSection("MediasoupSettings:WorkerSettings").Get <WorkerSettings>(); var routerSettings = Configuration.GetSection("MediasoupSettings:RouterSettings").Get <RouterSettings>(); var webRtcTransportSettings = Configuration.GetSection("MediasoupSettings:WebRtcTransportSettings").Get <WebRtcTransportSettings>(); services.AddMediasoup(options => { // MediasoupStartupSettings if (mediasoupStartupSettings != null) { options.MediasoupStartupSettings.MediasoupVersion = mediasoupStartupSettings.MediasoupVersion; options.MediasoupStartupSettings.WorkerPath = mediasoupStartupSettings.WorkerPath; options.MediasoupStartupSettings.NumberOfWorkers = !mediasoupStartupSettings.NumberOfWorkers.HasValue || mediasoupStartupSettings.NumberOfWorkers <= 0 ? Environment.ProcessorCount : mediasoupStartupSettings.NumberOfWorkers; } // WorkerSettings if (workerSettings != null) { options.MediasoupSettings.WorkerSettings.LogLevel = workerSettings.LogLevel; options.MediasoupSettings.WorkerSettings.LogTags = workerSettings.LogTags; options.MediasoupSettings.WorkerSettings.RtcMinPort = workerSettings.RtcMinPort; options.MediasoupSettings.WorkerSettings.RtcMaxPort = workerSettings.RtcMaxPort; options.MediasoupSettings.WorkerSettings.DtlsCertificateFile = workerSettings.DtlsCertificateFile; options.MediasoupSettings.WorkerSettings.DtlsPrivateKeyFile = workerSettings.DtlsPrivateKeyFile; } // RouteSettings if (routerSettings != null && !routerSettings.RtpCodecCapabilities.IsNullOrEmpty()) { options.MediasoupSettings.RouterSettings = routerSettings; } // WebRtcTransportSettings if (webRtcTransportSettings != null) { options.MediasoupSettings.WebRtcTransportSettings.ListenIps = webRtcTransportSettings.ListenIps; options.MediasoupSettings.WebRtcTransportSettings.InitialAvailableOutgoingBitrate = webRtcTransportSettings.InitialAvailableOutgoingBitrate; options.MediasoupSettings.WebRtcTransportSettings.MinimumAvailableOutgoingBitrate = webRtcTransportSettings.MinimumAvailableOutgoingBitrate; options.MediasoupSettings.WebRtcTransportSettings.MaxSctpMessageSize = webRtcTransportSettings.MaxSctpMessageSize; } }); }
public void Emit(OpCode opcode, SignatureHelper signature) => DispatchEmit(opcode, signature);
public void Emit(OpCode opcode, SignatureHelper signature) { lastOpCode = opcode; lastOperand = signature; }
/// <summary> /// 处理微信消息 /// </summary> /// <param name="channelId"></param> /// <param name="msg_signature"></param> /// <param name="timestamp"></param> /// <param name="nonce"></param> /// <param name="msg"></param> /// <returns></returns> public async Task <ExecuteResult <string> > HandleInputWeixinQyMessageAsync(int channelId, string msg_signature, string timestamp, string nonce, string msg) { var result = new ExecuteResult <string> { Success = false, ErrorMsg = "", ErrorCode = ExecuteResult.ErrorCodeEnum.Fail, }; try { var configDto = await ChannelHelper.GetAgentConfigDTOByChannelIdAsync(channelId); Senparc.Weixin.Work.Tencent.WXBizMsgCrypt crypt = new Senparc.Weixin.Work.Tencent.WXBizMsgCrypt(configDto.Token, configDto.EncodingAESKey, configDto.CorpId); var info = string.Empty; var r1 = crypt.DecryptMsg(msg_signature, timestamp, nonce, msg, ref info); var replyMsg = string.Empty; var reply = info.Replace("<ToUserName><![CDATA[wx9a80f6e6ed2a89e6]]></ToUserName><FromUserName><![CDATA[Yan-Xia]]></FromUserName>", "<ToUserName><![CDATA[Yan-Xia]]></ToUserName><FromUserName><![CDATA[wx9a80f6e6ed2a89e6]]></FromUserName>"); crypt.EncryptMsg(reply, timestamp, nonce, ref replyMsg); result.Data = replyMsg; var signHelper = new SignatureHelper(configDto); //signHelper.d string testXml = @"<xml><ToUserName><![CDATA[wx7618c0a6d9358622]]></ToUserName> <Encrypt><![CDATA[h3z+AK9zKP4dYs8j1FmthAILbJghEmdo2Y1U9Pdghzann6H2KJOpepaDT1zcp09/1/e/6ta48aUXebkHlu0rhzk4GW+cvVUHzbEiQVFlIvD+q4T/NLIm8E8BM+gO+DHslM7aXmYjvgMw6AYiBx80D+nZKNyJD3I8lRT3aHCq/hez0c+HTAnZyuCi5TfUAw0c6jWSfAq61VesRw4lhV925vJUOBXT/zOw760CEsYXSr2IAr/n4aPfDgRs2Ww2h/HPiVOQ2Ms1f/BOtFiKVWMqZCxbmJ7cyPHH7+uOSAS6DtXiQAdwpEZwHz+A5QTsmK6V0C6Ifgr7zrStb7ygM7kmcrAJctPhCfG7WlfrWrFNLdtx9Q2F7d6/soinswdoYF8g56s8UWguOVkM7UFGr8H2QqrUJm5S5iFP/XNcBwvPWYA=]]></Encrypt> <AgentID><![CDATA[2]]></AgentID> </xml>"; var postModel = new Senparc.Weixin.Work.Entities.PostModel() { Msg_Signature = "845997ceb6e4fd73edd9a377be227848ce20d34f", Timestamp = "1412587525", Nonce = "1501543730", Token = "fzBsmSaI8XE1OwBh", EncodingAESKey = "9J8CQ7iF9mLtQDZrUM1loOVQ6oNDxVtBi1DBU2oaewl", CorpId = "wx7618c0a6d9358622" }; var messageHandler = new CustomMessageHandlers(XDocument.Parse(testXml), postModel, 10); var xmlInfo = XDocument.Parse(msg); var postModel1 = new Senparc.Weixin.Work.Entities.PostModel { CorpId = configDto.CorpId, EncodingAESKey = configDto.EncodingAESKey, Msg_Signature = msg_signature, Nonce = nonce, Timestamp = timestamp, Token = configDto.Token, //Msg_Signature = "845997ceb6e4fd73edd9a377be227848ce20d34f", //Timestamp = "1412587525", //Nonce = "1501543730", //Token = "fzBsmSaI8XE1OwBh", //EncodingAESKey = "9J8CQ7iF9mLtQDZrUM1loOVQ6oNDxVtBi1DBU2oaewl", //CorpId = "wx7618c0a6d9358622" }; var handler = new CustomMessageHandler(xmlInfo, postModel1, 10); return(result); } catch (Exception ex) { ex.WriteExceptionLog(""); } return(result); }
public static SignatureHelper ResolveReflectionSignature(this IMethodSignature csite, Module context) { SignatureHelper shelper; switch (csite.CallingConvention) { #if !NETSTANDARD case MethodCallingConvention.C: shelper = SignatureHelper.GetMethodSigHelper(context, CallingConvention.Cdecl, csite.ReturnType.ResolveReflection()); break; case MethodCallingConvention.StdCall: shelper = SignatureHelper.GetMethodSigHelper(context, CallingConvention.StdCall, csite.ReturnType.ResolveReflection()); break; case MethodCallingConvention.ThisCall: shelper = SignatureHelper.GetMethodSigHelper(context, CallingConvention.ThisCall, csite.ReturnType.ResolveReflection()); break; case MethodCallingConvention.FastCall: shelper = SignatureHelper.GetMethodSigHelper(context, CallingConvention.FastCall, csite.ReturnType.ResolveReflection()); break; case MethodCallingConvention.VarArg: shelper = SignatureHelper.GetMethodSigHelper(context, CallingConventions.VarArgs, csite.ReturnType.ResolveReflection()); break; #else case MethodCallingConvention.C: case MethodCallingConvention.StdCall: case MethodCallingConvention.ThisCall: case MethodCallingConvention.FastCall: case MethodCallingConvention.VarArg: throw new NotSupportedException("Unmanaged calling conventions for callsites not supported"); #endif default: if (csite.ExplicitThis) { shelper = SignatureHelper.GetMethodSigHelper(context, CallingConventions.ExplicitThis, csite.ReturnType.ResolveReflection()); } else { shelper = SignatureHelper.GetMethodSigHelper(context, CallingConventions.Standard, csite.ReturnType.ResolveReflection()); } break; } if (context != null) { List <Type> modReq = new List <Type>(); List <Type> modOpt = new List <Type>(); foreach (ParameterDefinition param in csite.Parameters) { if (param.ParameterType.IsSentinel) { shelper.AddSentinel(); } if (param.ParameterType.IsPinned) { shelper.AddArgument(param.ParameterType.ResolveReflection(), true); continue; } modOpt.Clear(); modReq.Clear(); for ( TypeReference paramTypeRef = param.ParameterType; paramTypeRef is TypeSpecification paramTypeSpec; paramTypeRef = paramTypeSpec.ElementType ) { switch (paramTypeRef) { case RequiredModifierType paramTypeModReq: modReq.Add(paramTypeModReq.ModifierType.ResolveReflection()); break; case OptionalModifierType paramTypeOptReq: modOpt.Add(paramTypeOptReq.ModifierType.ResolveReflection()); break; } } shelper.AddArgument(param.ParameterType.ResolveReflection(), modReq.ToArray(), modOpt.ToArray()); } } else { foreach (ParameterDefinition param in csite.Parameters) { shelper.AddArgument(param.ParameterType.ResolveReflection()); } } return(shelper); }
/// <summary> /// ConfigureServices /// </summary> /// <param name="services"></param> public override void ConfigureServices(IServiceCollection services) { // Background Service services.AddSingleton <IBackgroundTask, IdleBackgroundTask>(); // Cache services.AddDistributedRedisCache(options => { options.Configuration = "localhost"; options.InstanceName = _environment.ApplicationName + ":"; }); services.AddMemoryCache(); // Cors services.AddCors(options => options.AddPolicy("DefaultPolicy", builder => builder.WithOrigins("http://localhost:9090", "http://localhost:8080").AllowAnyMethod().AllowAnyHeader().AllowCredentials()) // builder => builder.AllowAnyOrigin.AllowAnyMethod().AllowAnyHeader().AllowCredentials()) ); // Cookie services.Configure <CookiePolicyOptions>(options => { options.CheckConsentNeeded = context => false; // 需保持为 false, 否则 Web API 不会 Set-Cookie 。 options.MinimumSameSitePolicy = SameSiteMode.None; }); // Session services.AddSession(options => { options.IdleTimeout = TimeSpan.FromMinutes(10); options.Cookie.Name = ".Tubumu.Session"; options.Cookie.HttpOnly = true; }); // HTTP Client services.AddHttpClient(); // ApiBehaviorOptions services.Configure <ApiBehaviorOptions>(options => { options.InvalidModelStateResponseFactory = context => new OkObjectResult(new ApiResult { Code = 400, Message = context.ModelState.FirstErrorMessage() }); }); // Authentication var registeredServiceDescriptor = services.FirstOrDefault(s => s.Lifetime == ServiceLifetime.Transient && s.ServiceType == typeof(IApplicationModelProvider) && s.ImplementationType == typeof(AuthorizationApplicationModelProvider)); if (registeredServiceDescriptor != null) { services.Remove(registeredServiceDescriptor); } services.AddTransient <IApplicationModelProvider, PermissionAuthorizationApplicationModelProvider>(); services.AddSingleton <ITokenService, TokenService>(); var tokenValidationSettings = _configuration.GetSection("TokenValidationSettings").Get <TokenValidationSettings>(); services.AddSingleton(tokenValidationSettings); services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) .AddJwtBearer(options => { options.TokenValidationParameters = new TokenValidationParameters { ValidIssuer = tokenValidationSettings.ValidIssuer, ValidateIssuer = true, ValidAudience = tokenValidationSettings.ValidAudience, ValidateAudience = true, IssuerSigningKey = SignatureHelper.GenerateSigningKey(tokenValidationSettings.IssuerSigningKey), ValidateIssuerSigningKey = tokenValidationSettings.ValidateLifetime, ValidateLifetime = true, ClockSkew = TimeSpan.FromSeconds(tokenValidationSettings.ClockSkewSeconds), }; // We have to hook the OnMessageReceived event in order to // allow the JWT authentication handler to read the access // token from the query string when a WebSocket or // Server-Sent Events request comes in. options.Events = new JwtBearerEvents { OnMessageReceived = context => { var accessToken = context.Request.Query["access_token"]; // If the request is for our hub... var path = context.HttpContext.Request.Path; if (!string.IsNullOrEmpty(accessToken) && path.StartsWithSegments("/hubs")) { // Read the token out of the query string context.Token = accessToken; } return(Task.CompletedTask); }, OnAuthenticationFailed = context => { _logger.LogError($"Authentication Failed(OnAuthenticationFailed): {context.Request.Path} Error: {context.Exception}"); if (context.Exception.GetType() == typeof(SecurityTokenExpiredException)) { context.Response.Headers.Add("Token-Expired", "true"); } return(Task.CompletedTask); }, OnChallenge = context => { _logger.LogError($"Authentication Challenge(OnChallenge): {context.Request.Path}"); // TODO: (alby)为不同客户端返回不同的内容 var result = new ApiResultUrl() { Code = 400, Message = "Authentication Challenge", Url = _environment.IsProduction() ? tokenValidationSettings.LoginUrl : null, }; var body = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(result)); context.Response.StatusCode = StatusCodes.Status401Unauthorized; context.Response.ContentType = "application/json"; context.Response.Body.Write(body, 0, body.Length); context.HandleResponse(); return(Task.CompletedTask); } }; }); // JSON Date format void JsonSetup(MvcJsonOptions options) => options.SerializerSettings.DateFormatString = "yyyy-MM-dd HH:mm:ss"; services.Configure((Action <MvcJsonOptions>)JsonSetup); // SignalR services.AddSignalR(); services.Replace(ServiceDescriptor.Singleton(typeof(IUserIdProvider), typeof(NameUserIdProvider))); // AutoMapper services.AddAutoMapper(); Initalizer.Initialize(); // Swagger services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new Info { Title = _environment.ApplicationName + " API", Version = "v1" }); c.AddSecurityDefinition("Bearer", new ApiKeyScheme { Description = "权限认证(数据将在请求头中进行传输) 参数结构: \"Authorization: Bearer {token}\"", Name = "Authorization", In = "header", Type = "apiKey" }); var security = new Dictionary <string, IEnumerable <string> > { { "Bearer", new string[] { } }, }; c.AddSecurityRequirement(security); c.DescribeAllEnumsAsStrings(); c.DocumentFilter <HiddenApiDocumentFilter>(); IncludeXmlCommentsForModules(c); c.OrderActionsBy(m => m.ActionDescriptor.DisplayName); }); }
protected override void AddSignature(SignatureHelper signature) { signature.AddElementType(elementType); }
/// <summary> /// Gets the signature from the specified file contents. /// </summary> /// <param name="sourcePathOrExtension">The file type associated with the contents.</param> /// <param name="content"> /// The contents of the file on which to perform the action. /// </param> /// <returns> /// The signature on the specified file contents. /// </returns> protected override Signature PerformAction(string sourcePathOrExtension, byte[] content) { return(SignatureHelper.GetSignature(sourcePathOrExtension, System.Text.Encoding.Unicode.GetString(content))); }
public SignatureToken GetSignatureToken(SignatureHelper sigHelper) {}
public string GetComponentTypeName() { return(SignatureHelper.DecodeTypeName(GetSignature().Substring(1))); }
private static IDispatchInvokeDelegate Create_IDispatchInvoke(bool returnResult) { const int dispatchPointerIndex = 0; const int memberDispIdIndex = 1; const int flagsIndex = 2; const int dispParamsIndex = 3; const int resultIndex = 4; const int exceptInfoIndex = 5; const int argErrIndex = 6; Debug.Assert(argErrIndex + 1 == typeof(IDispatchInvokeDelegate).GetMethod("Invoke").GetParameters().Length); Type[] paramTypes = new Type[argErrIndex + 1]; paramTypes[dispatchPointerIndex] = typeof(IntPtr); paramTypes[memberDispIdIndex] = typeof(int); paramTypes[flagsIndex] = typeof(ComTypes.INVOKEKIND); paramTypes[dispParamsIndex] = typeof(ComTypes.DISPPARAMS).MakeByRefType(); paramTypes[resultIndex] = typeof(Variant).MakeByRefType(); paramTypes[exceptInfoIndex] = typeof(ExcepInfo).MakeByRefType(); paramTypes[argErrIndex] = typeof(uint).MakeByRefType(); // Define the dynamic method in our assembly so we skip verification DynamicMethod dm = new DynamicMethod("IDispatchInvoke", typeof(int), paramTypes, DynamicModule); ILGenerator method = dm.GetILGenerator(); // return functionPtr(...) EmitLoadArg(method, dispatchPointerIndex); EmitLoadArg(method, memberDispIdIndex); // burn the address of our empty IID in directly. This is never freed, relocated, etc... // Note passing this as a Guid directly results in a ~30% perf hit for IDispatch invokes so // we also pass it directly as an IntPtr instead. if (IntPtr.Size == 4) { method.Emit(OpCodes.Ldc_I4, UnsafeMethods.NullInterfaceId.ToInt32()); // riid } else { method.Emit(OpCodes.Ldc_I8, UnsafeMethods.NullInterfaceId.ToInt64()); // riid } method.Emit(OpCodes.Conv_I); method.Emit(OpCodes.Ldc_I4_0); // lcid EmitLoadArg(method, flagsIndex); EmitLoadArg(method, dispParamsIndex); if (returnResult) { EmitLoadArg(method, resultIndex); } else { method.Emit(OpCodes.Ldsfld, typeof(IntPtr).GetField("Zero")); } EmitLoadArg(method, exceptInfoIndex); EmitLoadArg(method, argErrIndex); // functionPtr = *(IntPtr*)(*(dispatchPointer) + VTABLE_OFFSET) int idispatchInvokeOffset = ((int)IDispatchMethodIndices.IDispatch_Invoke) * Marshal.SizeOf(typeof(IntPtr)); EmitLoadArg(method, dispatchPointerIndex); method.Emit(OpCodes.Ldind_I); method.Emit(OpCodes.Ldc_I4, idispatchInvokeOffset); method.Emit(OpCodes.Add); method.Emit(OpCodes.Ldind_I); SignatureHelper signature = SignatureHelper.GetMethodSigHelper(CallingConvention.Winapi, typeof(int)); Type[] invokeParamTypes = new Type[] { typeof(IntPtr), // dispatchPointer typeof(int), // memberDispId typeof(IntPtr), // riid typeof(int), // lcid typeof(ushort), // flags typeof(IntPtr), // dispParams typeof(IntPtr), // result typeof(IntPtr), // excepInfo typeof(IntPtr), // argErr }; signature.AddArguments(invokeParamTypes, null, null); method.Emit(OpCodes.Calli, signature); method.Emit(OpCodes.Ret); return((IDispatchInvokeDelegate)dm.CreateDelegate(typeof(IDispatchInvokeDelegate))); }
/// <inheritdoc/> public IEmitter Emit(OpCode opcode, SignatureHelper signature) { this.ilGen.Emit(opcode, signature); return(this); }
public void Emit(OpCode opcode, SignatureHelper signature) => Instance.Emit(opcode, signature);