DefaultRpcInvoker.cs 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272
  1. using JsonRPC4.Common;
  2. using JsonRPC4.Router.Abstractions;
  3. using JsonRPC4.Router.Utilities;
  4. using Microsoft.AspNetCore.Authorization;
  5. using Microsoft.Extensions.DependencyInjection;
  6. using Microsoft.Extensions.Logging;
  7. using Microsoft.Extensions.Options;
  8. using System;
  9. using System.Collections.Concurrent;
  10. using System.Collections.Generic;
  11. using System.Linq;
  12. using System.Reflection;
  13. using System.Threading.Tasks;
  14. namespace JsonRPC4.Router.Defaults
  15. {
  16. public class DefaultRpcInvoker : IRpcInvoker
  17. {
  18. private ILogger<DefaultRpcInvoker> logger
  19. {
  20. get;
  21. }
  22. private IAuthorizationService authorizationService
  23. {
  24. get;
  25. }
  26. private IAuthorizationPolicyProvider policyProvider
  27. {
  28. get;
  29. }
  30. private IOptions<RpcServerConfiguration> serverConfig
  31. {
  32. get;
  33. }
  34. private IRpcRequestMatcher rpcRequestMatcher
  35. {
  36. get;
  37. }
  38. private ConcurrentDictionary<Type, ObjectFactory> objectFactoryCache
  39. {
  40. get;
  41. } = new ConcurrentDictionary<Type, ObjectFactory>();
  42. private ConcurrentDictionary<Type, (List<IAuthorizeData>, bool)> classAttributeCache
  43. {
  44. get;
  45. } = new ConcurrentDictionary<Type, (List<IAuthorizeData>, bool)>();
  46. private ConcurrentDictionary<RpcMethodInfo, (List<IAuthorizeData>, bool)> methodAttributeCache
  47. {
  48. get;
  49. } = new ConcurrentDictionary<RpcMethodInfo, (List<IAuthorizeData>, bool)>();
  50. public DefaultRpcInvoker(IAuthorizationService authorizationService, IAuthorizationPolicyProvider policyProvider, ILogger<DefaultRpcInvoker> logger, IOptions<RpcServerConfiguration> serverConfig, IRpcRequestMatcher rpcRequestMatcher)
  51. {
  52. this.authorizationService = authorizationService;
  53. this.policyProvider = policyProvider;
  54. this.logger = logger;
  55. this.serverConfig = serverConfig;
  56. this.rpcRequestMatcher = rpcRequestMatcher;
  57. }
  58. public async Task<List<RpcResponse>> InvokeBatchRequestAsync(IList<RpcRequest> requests, IRouteContext routeContext, RpcPath path = null)
  59. {
  60. logger.InvokingBatchRequests(requests.Count);
  61. List<Task<RpcResponse>> invokingTasks = new List<Task<RpcResponse>>();
  62. foreach (RpcRequest request in requests)
  63. {
  64. Task<RpcResponse> item = InvokeRequestAsync(request, routeContext, path);
  65. if (request.Id.HasValue)
  66. {
  67. invokingTasks.Add(item);
  68. }
  69. }
  70. await Task.WhenAll(invokingTasks.ToArray());
  71. List<RpcResponse> result = (from t in invokingTasks
  72. select t.Result into r
  73. where r != null
  74. select r).ToList();
  75. logger.BatchRequestsComplete();
  76. return result;
  77. }
  78. public async Task<RpcResponse> InvokeRequestAsync(RpcRequest request, IRouteContext routeContext, RpcPath path = null)
  79. {
  80. if (request == null)
  81. {
  82. throw new ArgumentNullException("request");
  83. }
  84. logger.InvokingRequest(request.Id);
  85. RpcResponse result;
  86. try
  87. {
  88. if (!routeContext.MethodProvider.TryGetByPath(path, out IReadOnlyList<MethodInfo> methods))
  89. {
  90. throw new RpcException(RpcErrorCode.MethodNotFound, $"No methods found with the path: {path}");
  91. }
  92. RpcMethodInfo rpcMethod = rpcRequestMatcher.GetMatchingMethod(request, methods);
  93. if (await IsAuthorizedAsync(rpcMethod, routeContext))
  94. {
  95. logger.InvokeMethod(request.Method);
  96. object obj = await InvokeAsync(rpcMethod, path, routeContext.RequestServices);
  97. logger.InvokeMethodComplete(request.Method);
  98. IRpcMethodResult rpcMethodResult = obj as IRpcMethodResult;
  99. result = ((rpcMethodResult == null) ? new RpcResponse(request.Id, obj) : rpcMethodResult.ToRpcResponse(request.Id));
  100. }
  101. else
  102. {
  103. RpcError error = new RpcError(RpcErrorCode.InvalidRequest, "Unauthorized");
  104. result = new RpcResponse(request.Id, error);
  105. }
  106. }
  107. catch (Exception ex)
  108. {
  109. logger.LogException(ex, "An Rpc error occurred while trying to invoke request.");
  110. RpcException ex2 = ex as RpcException;
  111. result = new RpcResponse(error: (ex2 == null) ? new RpcError(RpcErrorCode.InternalError, "An Rpc error occurred while trying to invoke request.", ex) : ex2.ToRpcError(serverConfig.Value.ShowServerExceptions), id: request.Id);
  112. }
  113. if (request.Id.HasValue)
  114. {
  115. logger.FinishedRequest(request.Id.ToString());
  116. return result;
  117. }
  118. logger.FinishedRequestNoId();
  119. return null;
  120. }
  121. private async Task<bool> IsAuthorizedAsync(RpcMethodInfo methodInfo, IRouteContext routeContext)
  122. {
  123. (List<IAuthorizeData>, bool) orAdd = classAttributeCache.GetOrAdd(methodInfo.Method.DeclaringType, GetClassAttributeInfo);
  124. List<IAuthorizeData> item = orAdd.Item1;
  125. bool item2 = orAdd.Item2;
  126. (List<IAuthorizeData>, bool) orAdd2 = methodAttributeCache.GetOrAdd(methodInfo, GetMethodAttributeInfo);
  127. List<IAuthorizeData> authorizeDataListMethod = orAdd2.Item1;
  128. bool item3 = orAdd2.Item2;
  129. if (item.Any() || authorizeDataListMethod.Any())
  130. {
  131. if (item2 || item3)
  132. {
  133. logger.SkippingAuth();
  134. }
  135. else
  136. {
  137. logger.RunningAuth();
  138. AuthorizationResult authorizationResult = await CheckAuthorize(item, routeContext);
  139. if (authorizationResult.Succeeded)
  140. {
  141. authorizationResult = await CheckAuthorize(authorizeDataListMethod, routeContext);
  142. }
  143. if (!authorizationResult.Succeeded)
  144. {
  145. logger.AuthFailed();
  146. return false;
  147. }
  148. logger.AuthSuccessful();
  149. }
  150. }
  151. else
  152. {
  153. logger.NoConfiguredAuth();
  154. }
  155. return true;
  156. (List<IAuthorizeData> Data, bool allowAnonymous) GetAttributeInfo(IEnumerable<Attribute> attributes)
  157. {
  158. bool flag = false;
  159. List<IAuthorizeData> list = new List<IAuthorizeData>(10);
  160. foreach (Attribute attribute in attributes)
  161. {
  162. IAuthorizeData authorizeData = attribute as IAuthorizeData;
  163. if (authorizeData != null)
  164. {
  165. list.Add(authorizeData);
  166. }
  167. if (!flag && attribute is IAllowAnonymous)
  168. {
  169. flag = true;
  170. }
  171. }
  172. return (list, flag);
  173. }
  174. (List<IAuthorizeData> Data, bool allowAnonymous) GetClassAttributeInfo(Type type)
  175. {
  176. return GetAttributeInfo(type.GetCustomAttributes());
  177. }
  178. (List<IAuthorizeData> Data, bool allowAnonymous) GetMethodAttributeInfo(RpcMethodInfo info)
  179. {
  180. return GetAttributeInfo(info.Method.GetCustomAttributes());
  181. }
  182. }
  183. private async Task<AuthorizationResult> CheckAuthorize(List<IAuthorizeData> authorizeDataList, IRouteContext routeContext)
  184. {
  185. if (!authorizeDataList.Any())
  186. {
  187. return AuthorizationResult.Success();
  188. }
  189. AuthorizationPolicy policy = await AuthorizationPolicy.CombineAsync(policyProvider, authorizeDataList);
  190. return await authorizationService.AuthorizeAsync(routeContext.User, policy);
  191. }
  192. private async Task<object> InvokeAsync(RpcMethodInfo methodInfo, RpcPath path, IServiceProvider serviceProvider)
  193. {
  194. object obj = null;
  195. if (serviceProvider != null)
  196. {
  197. obj = objectFactoryCache.GetOrAdd(methodInfo.Method.DeclaringType, (Type t) => ActivatorUtilities.CreateFactory(t, new Type[0]))(serviceProvider, null);
  198. }
  199. if (obj == null)
  200. {
  201. obj = Activator.CreateInstance(methodInfo.Method.DeclaringType);
  202. }
  203. try
  204. {
  205. return await HandleAsyncResponses(methodInfo.Method.Invoke(obj, methodInfo.Parameters));
  206. }
  207. catch (TargetInvocationException ex)
  208. {
  209. RpcRouteInfo routeInfo = new RpcRouteInfo(methodInfo, path, serviceProvider);
  210. RpcErrorFilterAttribute customAttribute = methodInfo.Method.DeclaringType.GetTypeInfo().GetCustomAttribute<RpcErrorFilterAttribute>();
  211. if (customAttribute != null)
  212. {
  213. OnExceptionResult onExceptionResult = customAttribute.OnException(routeInfo, ex.InnerException);
  214. if (!onExceptionResult.ThrowException)
  215. {
  216. return onExceptionResult.ResponseObject;
  217. }
  218. Exception ex2 = onExceptionResult.ResponseObject as Exception;
  219. if (ex2 != null)
  220. {
  221. throw ex2;
  222. }
  223. }
  224. throw new RpcException(RpcErrorCode.InternalError, "Exception occurred from target method execution.", ex);
  225. }
  226. catch (Exception innerException)
  227. {
  228. throw new RpcException(RpcErrorCode.InvalidParams, "Exception from attempting to invoke method. Possibly invalid parameters for method.", innerException);
  229. }
  230. }
  231. private static async Task<object> HandleAsyncResponses(object returnObj)
  232. {
  233. Task task = returnObj as Task;
  234. if (task == null)
  235. {
  236. return returnObj;
  237. }
  238. try
  239. {
  240. await task;
  241. }
  242. catch (Exception inner)
  243. {
  244. throw new TargetInvocationException(inner);
  245. }
  246. PropertyInfo property = task.GetType().GetProperty("Result");
  247. if (property != null)
  248. {
  249. return property.GetValue(returnObj);
  250. }
  251. return null;
  252. }
  253. }
  254. }