private async Task <AuthorServiceResult> ValidateAppSecretAuthentication(ServiceRoute route, string path, Dictionary <string, object> model) { AuthorServiceResult authorServiceResult = new AuthorServiceResult(); var author = HttpContext.Request.Headers["Authorization"]; if (author.Count > 0) { var token = AuthenticationCommon.GetAuthToken(author); authorServiceResult.isSuccess = await _authorizationServerProvider.ValidateClientAuthentication(token); if (!authorServiceResult.isSuccess) { authorServiceResult.result = new Surging.Core.ApiGateWay.ServiceResult <object> { IsSucceed = false, StatusCode = (int)ServiceStatusCode.AuthorizationFailed, Message = "Invalid authentication credentials" }; } else { var keyValue = model.FirstOrDefault(); if (!(keyValue.Value is IConvertible) || !typeof(IConvertible).GetTypeInfo().IsAssignableFrom(keyValue.Value.GetType())) { dynamic instance = keyValue.Value; instance.Payload = _authorizationServerProvider.GetPayloadString(token); RpcContext.GetContext().SetAttachment("payload", instance.Payload.ToString()); model.Remove(keyValue.Key); model.Add(keyValue.Key, instance); } } } else { authorServiceResult.result = new Surging.Core.ApiGateWay.ServiceResult <object> { IsSucceed = false, StatusCode = (int)ServiceStatusCode.RequestError, Message = "Request error" }; authorServiceResult.isSuccess = false; } return(authorServiceResult); }
public async Task <Surging.Core.ApiGateWay.ServiceResult <object> > Path([FromServices] IServicePartProvider servicePartProvider, string path, [FromBody] Dictionary <string, object> model) { string serviceKey = this.Request.Query["servicekey"]; path = path.IndexOf("/") < 0 ? $"/{path}" : path; if (model == null) { model = new Dictionary <string, object>(); } foreach (string n in this.Request.Query.Keys) { model[n] = this.Request.Query[n].ToString(); } Surging.Core.ApiGateWay.ServiceResult <object> result = Surging.Core.ApiGateWay.ServiceResult <object> .Create(false, null); path = String.Compare(path.ToLower(), GateWayAppConfig.TokenEndpointPath, true) == 0 ? GateWayAppConfig.AuthorizationRoutePath : path.ToLower(); var route = await _serviceRouteProvider.GetRouteByPathRegex(path); var httpMethods = route.ServiceDescriptor.HttpMethod(); if (!string.IsNullOrEmpty(httpMethods) && !httpMethods.Contains(Request.Method)) { return new Surging.Core.ApiGateWay.ServiceResult <object> { IsSucceed = false, StatusCode = (int)ServiceStatusCode.Http405Endpoint, Message = "405 HTTP Method Not Supported" } } ; if (!GetAllowRequest(route)) { return new Surging.Core.ApiGateWay.ServiceResult <object> { IsSucceed = false, StatusCode = (int)ServiceStatusCode.RequestError, Message = "Request error" } } ; if (servicePartProvider.IsPart(path)) { //result = ServiceResult<object>.Create(true, await servicePartProvider.Merge(path, model)); //result.StatusCode = (int)ServiceStatusCode.Success; var data = (string)await servicePartProvider.Merge(path, model); return(AuthenticationCommon.CreateServiceResult(data)); } else { var auth = await OnAuthorization(path, route, model); result = auth.result; if (auth.isSuccess) { if (path == GateWayAppConfig.AuthorizationRoutePath) { var oAuthUser = await _authorizationServerProvider.GenerateTokenCredential(model); if (oAuthUser.IsSucceed) { result = Surging.Core.ApiGateWay.ServiceResult <object> .Create(true, oAuthUser); result.StatusCode = (int)ServiceStatusCode.Success; } else { result = new Surging.Core.ApiGateWay.ServiceResult <object> { IsSucceed = false, StatusCode = (int)ServiceStatusCode.AuthorizationFailed, Entity = oAuthUser }; } } else { if (String.Compare(route.ServiceDescriptor.RoutePath, path, true) != 0) { var pamars = RouteTemplateSegmenter.Segment(route.ServiceDescriptor.RoutePath, path); foreach (KeyValuePair <string, object> item in pamars) { model.Add(item.Key, item.Value); } } if (!string.IsNullOrEmpty(serviceKey)) { //result = ServiceResult<object>.Create(true, await _serviceProxyProvider.Invoke<object>(model, route.ServiceDescriptor.RoutePath, serviceKey)); //result.StatusCode = (int)ServiceStatusCode.Success; var data = await _serviceProxyProvider.Invoke <object>(model, path, serviceKey); return(AuthenticationCommon.CreateServiceResult(data)); } else { //result = ServiceResult<object>.Create(true, await _serviceProxyProvider.Invoke<object>(model, route.ServiceDescriptor.RoutePath)); //result.StatusCode = (int)ServiceStatusCode.Success; var data = await _serviceProxyProvider.Invoke <object>(model, path); return(AuthenticationCommon.CreateServiceResult(data)); } } } } return(result); }
public async Task <AuthorServiceResult> ValidateJwtAuthentication(ServiceRoute route, string path, Dictionary <string, object> model) { AuthorServiceResult authorServiceResult = new AuthorServiceResult(); // bool isSuccess = true; var author = HttpContext.Request.Headers["Authorization"]; if (author.Count > 0) { var token = AuthenticationCommon.GetAuthToken(author); authorServiceResult.isSuccess = await _authorizationServerProvider.ValidateClientAuthentication(token); if (!authorServiceResult.isSuccess) { authorServiceResult.result = new Surging.Core.ApiGateWay.ServiceResult <object> { IsSucceed = false, StatusCode = (int)ServiceStatusCode.AuthorizationFailed, Message = "Invalid authentication credentials" }; } else { var onAuthorModel = new Dictionary <string, object>(); var payload = _authorizationServerProvider.GetPayloadString(token);; var keyValue = model.FirstOrDefault(); if (!(keyValue.Value is IConvertible) || !typeof(IConvertible).GetTypeInfo().IsAssignableFrom(keyValue.Value.GetType())) { dynamic instance = keyValue.Value; instance.Payload = payload; RpcContext.GetContext().SetAttachment("payload", instance.Payload.ToString()); model.Remove(keyValue.Key); model.Add(keyValue.Key, instance); } //onAuthorModel.Add("input", JsonConvert.SerializeObject(new //{ // Path = path, // Payload = payload //})); //var data = await _serviceProxyProvider.Invoke<bool>(onAuthorModel, "api/user/onauthentication", "User"); //if (!data) //{ // authorServiceResult.isSuccess = false; // authorServiceResult.result = new Surging.Core.ApiGateWay.ServiceResult<object> { IsSucceed = false, StatusCode = (int)ServiceStatusCode.AuthorizationFailed, Message = "没有该操作权限" }; //} //else //{ // var keyValue = model.FirstOrDefault(); // if (!(keyValue.Value is IConvertible) || !typeof(IConvertible).GetTypeInfo().IsAssignableFrom(keyValue.Value.GetType())) // { // dynamic instance = keyValue.Value; // instance.Payload = payload; // RpcContext.GetContext().SetAttachment("payload", instance.Payload.ToString()); // model.Remove(keyValue.Key); // model.Add(keyValue.Key, instance); // } //} } } else { authorServiceResult.result = new Surging.Core.ApiGateWay.ServiceResult <object> { IsSucceed = false, StatusCode = (int)ServiceStatusCode.RequestError, Message = "Request error" }; authorServiceResult.isSuccess = false; } return(authorServiceResult); }
private BWebServiceResponse OnRequest_Internal(HttpListenerContext _Context, Action <string> _ErrorMessageAction = null) { if (_Context.Request.HttpMethod != "POST") { _ErrorMessageAction?.Invoke("LoginRequest: POST method is accepted. But received request method: " + _Context.Request.HttpMethod); return(BWebResponse.MethodNotAllowed("POST method is accepted. But received request method: " + _Context.Request.HttpMethod)); } JObject ParsedBody; using (var InputStream = _Context.Request.InputStream) { using (var ResponseReader = new StreamReader(InputStream)) { try { ParsedBody = JObject.Parse(ResponseReader.ReadToEnd()); } catch (Exception e) { _ErrorMessageAction?.Invoke("LoginRequest-> Read request body stage has failed. Exception: " + e.Message + ", Trace: " + e.StackTrace); return(BWebResponse.BadRequest("Malformed request body. Request must be a valid json form.")); } } } if (!ParsedBody.ContainsKey(AuthMethod.API_KEY_PROPERTY) && ((!ParsedBody.ContainsKey(AuthMethod.USER_NAME_PROPERTY) && !ParsedBody.ContainsKey(AuthMethod.USER_EMAIL_PROPERTY)) || !ParsedBody.ContainsKey(AuthMethod.PASSWORD_MD5_PROPERTY))) { _ErrorMessageAction?.Invoke("LoginRequest-> Request does not have required fields."); return(BWebResponse.BadRequest("Request does not have required fields.")); } string Method; if (ParsedBody.ContainsKey(AuthMethod.API_KEY_PROPERTY)) { var ApiKey = (string)ParsedBody[AuthMethod.API_KEY_PROPERTY]; Method = ApiKey; } else { var PasswordMD5 = ((string)ParsedBody[AuthMethod.PASSWORD_MD5_PROPERTY]).ToLower(); if (ParsedBody.ContainsKey(UserDBEntry.USER_NAME_PROPERTY)) { Method = (string)ParsedBody[UserDBEntry.USER_NAME_PROPERTY] + PasswordMD5; } else { Method = ((string)ParsedBody[UserDBEntry.USER_EMAIL_PROPERTY]).ToLower() + PasswordMD5; } } if (!AuthenticationCommon.FetchUserInfoFromMemoryService_ByMethod(MemoryService, Method, out string UserID, out string _, out string _, _ErrorMessageAction)) { if (!AuthenticationCommon.FetchUserInfoFromDatabaseService_ByMethod(DatabaseService, MemoryService, Method, out UserID, out _, out _, out BWebServiceResponse FailureResponse, _ErrorMessageAction)) { return(FailureResponse); } } if (!BUtility.CalculateStringMD5(BUtility.RandomString(32, true), out string AccessTokenMD5, _ErrorMessageAction)) { return(BWebResponse.InternalError("Hash operation failed.")); } var AccessTokenMD5WithTokenType = "Basic " + AccessTokenMD5; var QueryParameters = new BMemoryQueryParameters() { Domain = Resources_DeploymentManager.Get().GetDeploymentBranchNameEscapedLoweredWithDash().ToUpper(), SubDomain = "SELF_SIGNED_ACCESS_TOKEN_VALIDATION", Identifier = AccessTokenMD5WithTokenType }; MemoryService.SetKeyValue(QueryParameters, new Tuple <string, BPrimitiveType>[] { new Tuple <string, BPrimitiveType>("method", new BPrimitiveType(Method)) }, _ErrorMessageAction); MemoryService.SetKeyExpireTime(QueryParameters, TimeSpan.FromHours(1), _ErrorMessageAction); return(BWebResponse.StatusOK("Login successful.", new JObject() { ["userId"] = UserID, ["token"] = AccessTokenMD5WithTokenType })); }