示例#1
0
        protected override async Task OnRealActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
        {
            var logger = _loggerFactory.CreateLogger(_errorCatalogName);
            await HttpErrorHelper.ExecuteByActionExecutingFilterContextAsync(context, logger, async() =>
            {
                var actionName = context.ActionDescriptor.DisplayName;

                using (var resultDispoint = await _appRequestControl.Do(actionName))
                {
                    var result = await resultDispoint.Execute();

                    if (!result.Result)
                    {
                        var fragment = new TextFragment()
                        {
                            Code = string.Empty,
                            DefaultFormatting = result.Description,
                            ReplaceParameters = new List <object>()
                            {
                            }
                        };

                        throw new UtilityException((int)Errors.RequestOverflow, fragment);
                    }
                    else
                    {
                        await next();
                    }
                }
            });
        }
示例#2
0
        public async Task Invoke(HttpContext context)
        {
            ILogger logger = null;


            using (var diContainer = DIContainerContainer.CreateContainer())
            {
                var loggerFactory = diContainer.Get <ILoggerFactory>();
                logger = loggerFactory.CreateLogger(_errorCatalogName);
            }


            await HttpErrorHelper.ExecuteByHttpContextAsync(context, logger, async() =>
            {
                var claimsIdentity = await _appSystemAuthentication.Do(context, _generatorName);


                if (claimsIdentity == null)
                {
                    context.User = null;
                }
                else
                {
                    context.User = new ClaimsPrincipal(claimsIdentity);
                }

                await _nextMiddleware(context);
            });
        }
        // GET api/values
        public async Task <HttpResponseMessage> Get()
        {
            // OWIN middleware validated the audience, but the scope must also be validated. It must contain "access_as_user".
            string[] addinScopes = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/scope").Value.Split(' ');
            if (!(addinScopes.Contains("access_as_user")))
            {
                return(HttpErrorHelper.SendErrorToClient(HttpStatusCode.Unauthorized, null, "Missing access_as_user."));
            }

            // Assemble all the information that is needed to get a token for Microsoft Graph using the "on behalf of" flow.
            // Beginning with MSAL.NET 3.x.x, the bootstrapContext is just the bootstrap token itself.
            string        bootstrapContext = ClaimsPrincipal.Current.Identities.First().BootstrapContext.ToString();
            UserAssertion userAssertion    = new UserAssertion(bootstrapContext);

            var cca = ConfidentialClientApplicationBuilder.Create(ConfigurationManager.AppSettings["ida:ClientID"])
                      .WithRedirectUri("https://localhost:44355")
                      .WithClientSecret(ConfigurationManager.AppSettings["ida:Password"])
                      .WithAuthority(ConfigurationManager.AppSettings["ida:Authority"])
                      .Build();

            // MSAL.NET adds the profile, offline_access, and openid scopes itself. It will throw an error if you add
            // them redundantly here.
            string[] graphScopes = { "https://graph.microsoft.com/Files.Read.All" };

            // Get the access token for Microsoft Graph.
            AcquireTokenOnBehalfOfParameterBuilder parameterBuilder = null;
            AuthenticationResult authResult = null;

            try
            {
                parameterBuilder = cca.AcquireTokenOnBehalfOf(graphScopes, userAssertion);
                authResult       = await parameterBuilder.ExecuteAsync();
            }
            catch (MsalServiceException e)
            {
                // Handle request for multi-factor authentication.
                if (e.Message.StartsWith("AADSTS50076"))
                {
                    string responseMessage = String.Format("{{\"AADError\":\"AADSTS50076\",\"Claims\":{0}}}", e.Claims);
                    return(HttpErrorHelper.SendErrorToClient(HttpStatusCode.Forbidden, null, responseMessage));
                    // The client should recall the getAccessToken function and pass the claims string as the
                    // authChallenge value in the function's Options parameter.
                }

                // Handle lack of consent (AADSTS65001) and invalid scope (permission).
                if ((e.Message.StartsWith("AADSTS65001")) || (e.Message.StartsWith("AADSTS70011: The provided value for the input parameter 'scope' is not valid.")))
                {
                    return(HttpErrorHelper.SendErrorToClient(HttpStatusCode.Forbidden, e, null));
                }

                // Handle all other MsalServiceExceptions.
                else
                {
                    throw e;
                }
            }

            return(await GraphApiHelper.GetOneDriveFileNames(authResult.AccessToken));
        }
示例#4
0
文件: DIWrapper.cs 项目: rhw1111/DCEM
        public async Task Invoke(HttpContext context)
        {
            var logger = _loggerFactory.CreateLogger(_categoryName);
            await HttpErrorHelper.ExecuteByHttpContextAsync(context, logger, async() =>
            {
                using (var diContainer = DIContainerContainer.CreateContainer())
                {
                    ContextContainer.SetValue <IDIContainer>(_name, diContainer);

                    var replaceExcludePaths = await _appGetOutputStreamReplaceExcludePaths.Do();
                    bool needReplace        = true;
                    if (context.Request.Path.HasValue)
                    {
                        //检查当前请求路径是否匹配
                        foreach (var item in replaceExcludePaths)
                        {
                            Regex regex = new Regex(item, RegexOptions.IgnoreCase);
                            if (regex.IsMatch(context.Request.Path.Value))
                            {
                                needReplace = false;
                                break;
                            }
                        }
                    }

                    if (needReplace)
                    {
                        Stream originalBody = context.Response.Body;
                        try
                        {
                            using (var responseStream = new MemoryStream())
                            {
                                context.Response.Body = responseStream;


                                await InnerInvoke(context);


                                responseStream.Position = 0;
                                await responseStream.CopyToAsync(originalBody);
                            }
                        }
                        finally
                        {
                            context.Response.Body = originalBody;
                        }
                    }
                    else
                    {
                        await InnerInvoke(context);
                    }
                }
            });
        }
示例#5
0
        protected override async Task OnRealAuthorizationAsync(AuthorizationFilterContext context)
        {
            ILogger logger = null;

            using (var diContainer = DIContainerContainer.CreateContainer())
            {
                var loggerFactory = diContainer.Get <ILoggerFactory>();
                logger = loggerFactory.CreateLogger(ErrorCatalogName);
            }

            await HttpErrorHelper.ExecuteByAuthorizationFilterContextAsync(context, logger, async() =>
            {
                //如果_directGeneratorName不为空,则直接使用该生成器名称
                if (!string.IsNullOrEmpty(_directGeneratorName))
                {
                    var authorizeResult = await _appUserAuthorize.Do(null, _directGeneratorName);
                    //存储到http上下文中
                    context.HttpContext.Items["AuthorizeResult"] = authorizeResult;
                }

                //判断是否已经通过验证
                if (context.HttpContext.User != null && context.HttpContext.User.Identity != null && context.HttpContext.User.Identity.IsAuthenticated && context.HttpContext.User.Claims != null)
                {
                    var authorizeResult = await _appUserAuthorize.Do(context.HttpContext.User.Claims, _userGeneratorName);

                    //存储到Http上下文中
                    context.HttpContext.Items["AuthorizeResult"] = authorizeResult;
                    //authorizeResult.Execute();
                }
                else
                {
                    if (_allowAnonymous)
                    {
                        //未通过验证,但允许匿名,则调用匿名上下文生成
                        var authorizeResult = await _appUserAuthorize.Do(null, _anonymousGeneratorName);
                        //存储到http上下文中
                        context.HttpContext.Items["AuthorizeResult"] = authorizeResult;
                        //authorizeResult.Execute();
                    }
                    else
                    {
                        //返回错误响应

                        ErrorMessage errorMessage = new ErrorMessage()
                        {
                            Code    = (int)Errors.AuthorizeFail,
                            Message = string.Format(StringLanguageTranslate.Translate(TextCodes.AuthorizeFail, "用户授权失败,没有找到对应的身份信息"))
                        };
                        context.Result = new JsonContentResult <ErrorMessage>(StatusCodes.Status401Unauthorized, errorMessage);
                    }
                }
            });
        }
示例#6
0
        protected override async Task OnRealAuthorizationAsync(AuthorizationFilterContext context)
        {
            ILogger logger = null;

            using (var diContainer = DIContainerContainer.CreateContainer())
            {
                var loggerFactory = diContainer.Get <ILoggerFactory>();
                logger = loggerFactory.CreateLogger(ErrorCatalogName);
            }

            await HttpErrorHelper.ExecuteByAuthorizationFilterContextAsync(context, logger, async() =>
            {
                //检查在http头中是否已经存在Authorization
                if (!context.HttpContext.Request.Headers.TryGetValue("WhitelistAuthorization", out StringValues authorizationValue))
                {
                    ErrorMessage errorMessage = new ErrorMessage()
                    {
                        Code    = (int)Errors.NotFoundAuthorizationInHttpHeader,
                        Message = StringLanguageTranslate.Translate(TextCodes.NotFoundWhitelistAuthorizationInHttpHeader, "在http头中没有找到WhitelistAuthorization")
                    };
                    context.Result = new JsonContentResult <ErrorMessage>(StatusCodes.Status401Unauthorized, errorMessage);
                }
                //检查在http头中是否已经存在SystemName
                if (!context.HttpContext.Request.Headers.TryGetValue("SystemName", out StringValues systemNameValue))
                {
                    ErrorMessage errorMessage = new ErrorMessage()
                    {
                        Code    = (int)Errors.NotFoundSystemNameInHttpHeader,
                        Message = StringLanguageTranslate.Translate(TextCodes.NotFoundSystemNameInHttpHeader, "在http头中没有找到SystemName")
                    };
                    context.Result = new JsonContentResult <ErrorMessage>(StatusCodes.Status401Unauthorized, errorMessage);
                }

                //获取ActionName的全路径名称
                var actinName = context.ActionDescriptor.DisplayName.Split(' ')[0];
                //获取访问的IP
                var ip = context.HttpContext.Connection.RemoteIpAddress.ToString();

                //执行验证
                var validateResult = await _appValidateRequestForWhitelist.Do(actinName, systemNameValue[0], authorizationValue[0], ip);

                if (!validateResult.Result)
                {
                    ErrorMessage errorMessage = new ErrorMessage()
                    {
                        Code    = (int)Errors.WhitelistValidateFail,
                        Message = string.Format(StringLanguageTranslate.Translate(TextCodes.WhitelistValidateFail, "系统操作{0}针对调用方系统{1}的白名单验证未通过,原因:{2}"), actinName, systemNameValue[0], validateResult.Description)
                    };
                    context.Result = new JsonContentResult <ErrorMessage>(StatusCodes.Status401Unauthorized, errorMessage);
                }
            });
示例#7
0
        public async Task Invoke(HttpContext context)
        {
            ILogger logger = null;

            using (var diContainer = DIContainerContainer.CreateContainer())
            {
                var loggerFactory = diContainer.Get <ILoggerFactory>();
                logger = loggerFactory.CreateLogger(_errorCatalogName);
            }


            await HttpErrorHelper.ExecuteByHttpContextAsync(context, logger, async() =>
            {
                var contextInit = await _appInternationalizationExecute.Do(context.Request, _name);

                context.Items["InternationalizationContextInit"] = contextInit;

                await _nextMiddleware(context);
            });
        }
示例#8
0
        public async Task Invoke(HttpContext context)
        {
            var logger = _loggerFactory.CreateLogger(_categoryName);

            await HttpErrorHelper.ExecuteByHttpContextAsync(context, logger, async() =>
            {
                //执行通用日志信息处理
                var needCreatRootLog = await _appCommonLogInfoHttpHandle.Do(context);
                //写入一条日志作为初始日志
                if (needCreatRootLog)
                {
                    var rootContent = await _appCreateCommonLogRootContentByHttpContext.Do(context);
                    LoggerHelper.LogInformation(_categoryName, rootContent);
                }
                else
                {
                    var content = await _appCreateCommonLogContentByHttpContext.Do(context);
                    LoggerHelper.LogInformation(_categoryName, content);
                }
                await _nextMiddleware(context);
            });
        }
示例#9
0
        protected void Application_Error(Object sender, EventArgs e)
        {
            var exception = Server.GetLastError();

            LogException(exception);

            //process 404 HTTP errors
            var httpException = exception as HttpException;

            if (httpException != null)
            {
                if (httpException.GetHttpCode() == 404)
                {
                    if (!HttpErrorHelper.IsStaticResource(this.Request))
                    {
                        Server.ClearError();
                        Response.TrySkipIisCustomErrors = true;

                        Response.Redirect("~/Common/PageNotFound", true);
                    }
                }
            }
        }
示例#10
0
        public async Task Invoke(HttpContext context)
        {
            ILogger logger = null;

            using (var diContainer = DIContainerContainer.CreateContainer())
            {
                var loggerFactory = diContainer.Get <ILoggerFactory>();
                logger = loggerFactory.CreateLogger(_errorCatalogName);
            }

            await HttpErrorHelper.ExecuteByHttpContextAsync(context, logger, async() =>
            {
                bool complete = false;
                //检查在http头中是否已经存在WhitelistAuthorization
                if (!context.Request.Headers.TryGetValue("WhitelistAuthorization", out StringValues authorizationValue))
                {
                    ErrorMessage errorMessage = new ErrorMessage()
                    {
                        Code    = (int)Errors.NotFoundAuthorizationInHttpHeader,
                        Message = StringLanguageTranslate.Translate(TextCodes.NotFoundWhitelistAuthorizationInHttpHeader, "在http头中没有找到WhitelistAuthorization")
                    };

                    await context.Response.WriteJson(StatusCodes.Status401Unauthorized, errorMessage);
                    complete = true;
                }
                //检查在http头中是否已经存在SystemName
                if (!context.Request.Headers.TryGetValue("SystemName", out StringValues systemNameValue))
                {
                    ErrorMessage errorMessage = new ErrorMessage()
                    {
                        Code    = (int)Errors.NotFoundSystemNameInHttpHeader,
                        Message = StringLanguageTranslate.Translate(TextCodes.NotFoundSystemNameInHttpHeader, "在http头中没有找到SystemName")
                    };
                    await context.Response.WriteJson(StatusCodes.Status401Unauthorized, errorMessage);
                    complete = true;
                }

                //获取请求路径名称
                var actinName = context.Request.Path;
                //获取访问的IP
                var ip = context.Connection.RemoteIpAddress.ToString();

                //执行验证
                var validateResult = await _appValidateRequestForWhitelist.Do(actinName, systemNameValue[0], authorizationValue[0], ip);

                if (!validateResult.Result)
                {
                    ErrorMessage errorMessage = new ErrorMessage()
                    {
                        Code    = (int)Errors.WhitelistValidateFail,
                        Message = string.Format(StringLanguageTranslate.Translate(TextCodes.WhitelistValidateFail, "系统操作{0}针对调用方系统{1}的白名单验证未通过,原因:{2}"), actinName, systemNameValue[0], validateResult.Description)
                    };
                    await context.Response.WriteJson(StatusCodes.Status401Unauthorized, errorMessage);
                    complete = true;
                }

                //如果检测通过,则继续执行下面的管道
                if (!complete)
                {
                    await _nextMiddleware(context);
                }
            });