【问题标题】:ASP.NET Core 3.1 MVC redirect in a custom AuthorizationHandler自定义 AuthorizationHandler 中的 ASP.NET Core 3.1 MVC 重定向
【发布时间】:2021-06-19 00:58:41
【问题描述】:

在一个 ASP.NET Core 2 MVC 应用程序中,我有一个自定义的 AuthorizationHandler 将被阻止的用户重定向回主页。

protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, IsAllowedIpAddressRequirement requirement)
{
    // Cast the context resource
    if (context.Resource is AuthorizationFilterContext cxt)
    {
            // Failed!
            cxt.Result = new RedirectToActionResult("Index", "Home", new { msg = "Your auth has failed." });
            context.Succeed(requirement);
    }
    ...
}

由于迁移到 ASP.NET Core 3.1,上下文是类 Microsoft.AspNetCore.Routing.RouteEndpoint 的对象,它没有 Result 属性。

如何将用户重定向到特定页面?

【问题讨论】:

  • 同样的问题。我有一个订阅策略,其要求类似于 op。根据用户的订阅类型,我想重定向到特定的订阅页面.. 但是如何在 net core3.1.. 中做到这一点?

标签: .net-core-3.1 asp.net-authorization


【解决方案1】:

如果您想将用户重定向到某些页面,例如登录页面,如果用户没有访问权限,您可以按照以下步骤进行修复:

  1. 进入HandleRequirementAsync方法

        if (Condition())
        {
            context.Succeed(requirement);
        }
        else {
            context.Fail();
        } 
    

如果用户有访问权限,则执行context.Succeed(requirement);,如果用户没有访问权限,则执行context.Fail();

  1. 进入startup.cs => ConfigureServices 方法

    services.ConfigureApplicationCookie(options =>
    {
        options.Cookie.HttpOnly = true;
        options.ExpireTimeSpan = TimeSpan.FromHours(12);
        options.LoginPath = "/Account/Login";
        options.AccessDeniedPath = "/Account/AccessDenied";
        options.SlidingExpiration = true;
    });
    

在我们写的那一行

 options.LoginPath = "/Account/Login";

我们在HandleRequirementAsync 方法检查访问失败后任命用户,被重定向到控制器“家”控制器和“登录”操作。

希望我的回答对朋友有用。

【讨论】:

  • 我认为这根本不能满足要求。 OP 需要什么,我所在的船是以前存在的一种方法,如果授权失败,可以将用户重定向到其他地方。
【解决方案2】:

我遇到了同样的问题,为了解决它,我改为过滤器 (IAsyncResourceFilter) 而不是策略。

您可以将您的授权逻辑包装到一个策略中,然后调用 IAuthorizationService 并在您需要的任何时间/任何时间重定向。

例子:

public class MySampleActionFilter: IActionFilter
{
   public void OnActionExecuting(ActionExecutingContext context)
   {
       //if failed
       context.Result = new RedirectToRouteResult(new RouteValueDictonary(new
       {
           controller = "Your Controller",
           action = "Your Action"
       }));
   }
}

顺便说一下,这是针对 .net Core 3 及更高版本的

Documentation

【讨论】:

    猜你喜欢
    • 2017-06-02
    • 2018-02-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多