授权失败后,Asp.net核心授权将重定向到指定路径

时间:2018-07-11 18:12:19

标签: asp.net-mvc asp.net-core

用户jcaddy写道:

在仔细阅读并参考了《 ASP.NET Core MVC Pro专业书籍》(第6版,Adam Freeman)之后,对我的问题的简单回答是创建一个“授权过滤器”。这使用单个方法OnAuthorization(AuthorizationFilterContext context)实现IAuthorizationFilter。用这种方法可以执行检查请求的所有操作。如果授权失败,只需将context.Result属性设置为某些IActionResult,在我的情况下为RedirectToActionResult。如果请求通过授权,则什么都不做。

如果可以,请给出一个代码示例,我将不胜感激。我尝试过没有成功。

这是我到目前为止所做的,但没有成功。

protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, AuthorizedUserRequirement requirement)
    {
        var user = context.User.Identity.Name;
        var delimiterIndex = user.IndexOf(@"\");
        var userName = user.Substring(delimiterIndex + 1);

        var userExists = _userAuthenticationService.IsValidUserAsync(userName);

        if (userExists)
        {
            context.Succeed(requirement);
        }
        else
        {
            if (context.Resource is AuthorizationFilterContext mvcContext)
            {
                mvcContext.Result = new RedirectToActionResult("Error", "Home", mvcContext.RouteData);

                RedirectToActionResult redirectToActionResult = new RedirectToActionResult("Error", "Home", mvcContext.Result);
                redirectToActionResult.ExecuteResultAsync(mvcContext);
                //RedirectToPageResult redirectToPageResult = new RedirectToPageResult("/Views/Home/Error403.cshtml");
                //redirectToPageResult.ExecuteResultAsync(mvcContext);
            }
         }
        //TODO: Use the following if targeting a version of
        //.NET Framework older than 4.6:
        //      return Task.FromResult(0);
        return Task.CompletedTask;

    }

0 个答案:

没有答案