public virtual bool AuthorizedRoute(HttpContext context, RoutingModel route, IAuthorizationService authorizationService) { var ssourl = CommonUtility.GetAppConfigValue(CommonConst.CommonValue.SSOURL_CONFIG_KEY); if (!route.auth_users.Where(f => f == CommonConst.CommonValue.ACCESS_ALL).Any() && !string.IsNullOrEmpty(ssourl)) { try { if (route.auth_users.IndexOf(CommonConst.CommonField.API_AUTH_TOKEN) != -1) { var api_access_key = _httpContextProxy.GetHeader(CommonConst.CommonField.API_AUTH_TOKEN); return(api_access_key == CommonUtility.GetApiAuthKey()); } var oauthclient = context.Request.Headers[CommonConst.CommonField.OAUTH_CLIENT_ID]; if (!string.IsNullOrEmpty(oauthclient)) { var oauthUser = ValidateOAuthRequest(oauthclient, context, route); return(oauthUser != null); } UserModel userModel = null; userModel = _httpContextProxy.User; if (userModel == null) // || (userModel != null && userModel.user_id == "auth2") { var accessToken = _httpContextProxy.GetAccessTokenAync().GetAwaiter().GetResult(); var cackeKey = $"{accessToken}"; userModel = _inMemoryCacheService.Get <UserModel>(cackeKey); if (userModel == null) { var endpoint = ApplicationConfig.AppEndpoint; if (endpoint == ApplicationConfig.SSOEndpoint) { endpoint = ApplicationConfig.ApiGatewayEndpoint; } var response = _apiGatewayService.CallAsync(CommonConst.ActionMethods.GET, "~/user/getuserinfo", "", null, new Dictionary <string, string>() { }, endpoint).GetAwaiter().GetResult(); if (response["user"] != null) { userModel = JsonConvert.DeserializeObject <UserModel>(response["user"].ToString()); _inMemoryCacheService.Put <UserModel>(cackeKey, userModel); } } if (userModel != null) { var identity = new ClaimsIdentity(); foreach (var claim in userModel.claims) { if (claim.Key == "roles") { var roles = new List <string>(); roles.AddRange(userModel.roles); identity.AddClaim(new System.Security.Claims.Claim("roles", Newtonsoft.Json.JsonConvert.SerializeObject(roles))); } else { identity.AddClaim(new System.Security.Claims.Claim(claim.Key, claim.Value)); } } context.User = new ClaimsPrincipal(identity); } } if (userModel != null) { if (userModel.tenants != null && userModel.tenants.Any()) { context.Response.Headers[CommonConst.CommonField.TENANT_ID] = userModel.tenants.First().tenant_id; } var u = _httpContextProxy.User; _logger.Debug($"Assign user id :{u.user_id} Claims:{string.Join(", ", u.claims.Select(f => $"{f.Key}:{f.Value}"))} OrgRoles: { string.Join(",", userModel.roles)}"); var hasaccess = false; hasaccess = userModel.roles.Where(f => route.auth_users.IndexOf(f) != -1).Any(); if (!hasaccess) { _logger.Debug($"Access :{hasaccess}:{route.ToString()}:{ string.Join(",", route.auth_users)}"); } return(hasaccess); } return(false); } catch (UnauthorizedAccessException) { return(false); } } else { return(true); } }
public void Exec(RoutingModel route, IHttpContextProxy httpProxy) { ILogger loggerController = Logger.GetLogger(route.ExecuteType, httpProxy.TransactionId); RouteEventHandler routeEventHandler = new RouteEventHandler(); try { loggerController.Info(string.Format("{0}:: Route: [{1}]", "RouteExecuter.Exec", route.ToString())); IActionExecuter actionExecuter = new ActionExecuter(loggerController); ParamContainer paramContainer = ActionExecuterHelper.CreateParamContainer(route, httpProxy, loggerController, actionExecuter); WriteStartTransaction(loggerController, httpProxy, route); (paramContainer.GetKey(CommonConst.CommonValue.PARAM_SESSION_PROVIDER) as ISessionProvider).SetValue(CommonConst.CommonField.UPDATED_DATE_TIME, CommonUtility.GetUnixTimestamp(DateTime.Now)); // Execute before Events routeEventHandler.ExecBeforeEvent(actionExecuter, route, paramContainer); var objResult = actionExecuter.Exec(route, paramContainer); httpProxy.ContentType = route.ContentType; // Add response in param paramContainer.AddKey(CommonConst.CommonValue.PARAM_API_RESPONSE, () => { return(objResult); }); if (objResult == null) { httpProxy.SetResponse(CommonConst._500_SERVER_ERROR); } else if (objResult is byte[]) { WriteEndTransaction(loggerController, "*** Binary Data ***"); httpProxy.SetResponse(CommonConst._200_OK, (byte[])objResult); } else if (objResult is string) { WriteEndTransaction(loggerController, (objResult as string)); httpProxy.SetResponse(CommonConst._200_OK, objResult as string); } else { var responseData = (objResult as JObject).ToString(); WriteEndTransaction(loggerController, responseData); httpProxy.SetResponse(CommonConst._200_OK, responseData); } // Execute after Events routeEventHandler.ExecAfterEvent(actionExecuter, route, paramContainer, objResult); // List<string> userGroups = _httpProxy.GetSessionUserGroups(); // if (route.auth_users.Count == 0 || userGroups.Intersect(route.auth_users).Any()) // { // var objResult = routeExecuter.Exec(route, helper); // if (objResult == null) // { // SetInternalServerError(); // return null; // } // else if (objResult is byte[]) // { // return (byte[])objResult; // } // else // { // return Encoding.UTF8.GetBytes((objResult as JObject).ToString()); // } // } // else // { // SetUnauthorized(); // return Encoding.UTF8.GetBytes((ZApp.Common.HttpUtility.GetFullResponse((int)ResponseCodes.Unauthorized, ResponseCodes.Unauthorized.ToString(), null)).ToString()); // } } catch (UnauthorizedAccessException ex) { loggerController.Error(string.Format("Error While executing Route : {0}, Error : {1}", route.ToString(), ex.Message), ex); httpProxy.SetResponse(CommonConst._401_UNAUTHORIZED); } catch (Exception ex) { httpProxy.SetResponse(CommonConst._500_SERVER_ERROR); loggerController.Error(string.Format("Error While executing Route : {0}, Error : {1}", route.ToString(), ex.Message), ex); } }