【问题标题】:Redirect users to unauthorized page (temp solution)将用户重定向到未经授权的页面(临时解决方案)
【发布时间】:2021-05-24 12:56:20
【问题描述】:

我有一个不使用 Identity 的基本 .net5(asp.net mvc 核心)应用程序。但是,我使用 Windows 身份验证来识别用户。

app.UseAuthentication();
app.UseAuthorization();

services.AddAuthentication(NegotiateDefaults.AuthenticationScheme).AddNegotiate();

我有一个表MyUsers,还有一个Login 列。我希望将不在MyUsers(登录不适合)表中的任何用户重定向到自定义页面,例如/Views/UnAuthorised

我将其用作临时解决方案,直到我将实施 Indentity,但在实际版本中,我只需将所有其他用户重定向到一个页面,作为 quickfix .

我尝试将“无法识别”的用户重定向到 401:

public IActionResult Index()
{
    var user = _userService.GetCurrentUser();
    if (user == null)
        return Unauthorized();

    return View();
}

这给了我一个空白页...如果 GetCurrentUser 返回 null。

这是我的 UserResolverService:

public async System.Threading.Tasks.Task<MyUser> GetCurrentUserAsync()
{
    UserGeobase currentUser;
    var currentSessionUser = _sessionService.GetCurrentUser();

    if (currentSessionUser != null)
    {
        currentUser = _repository.GetById<MyUser>(currentSessionUser.Id);
        if (currentUser != null)
            return currentUser;
    }

    var name = (_context.HttpContext.User.Identity.Name).Split('\\')[1]; // split 'DOMAIN\UserLogin'
    currentUser = _repository.SingleOrDefault(new MyUserByUsernameSpecification(name));

    if (currentUser is null)
    {
        // if not found, redirect to unauthorized page
        // ??
        // ??
    }
    else
    {
        currentUser.ConnectionDate = DateTime.Now;
        await _repository.UpdateAsync(currentUser);
    }

    _sessionService.SetCurrentUser(currentUser.Id, currentUser.UserName);
    return currentUser;
}

问题:

  1. 如何将 401 重定向到自定义视图?
  2. 如何检查所有控制器,而不仅仅是 Home/Index

【问题讨论】:

    标签: c# authentication asp.net-core-mvc asp.net-identity .net-5


    【解决方案1】:

    请尝试使用 RedirectAction() 重定向到所需的页面。

    【讨论】:

    • 我明白了,但是在哪里实现...我的意思是,一个中间件可以检查...
    • 我认为我们需要将这些未经授权的用户从表示层本身重定向到未经授权的页面。如果服务返回 null 作为 currentUser,则类似 LoginPage -> 调用 UserResolverService 并重定向到未经授权的页面。
    • 我想我需要使用一个中间件将所有无法识别的用户重定向到一个页面
    • 如果要使用中间件可以参考官方doc,需要注意的是中间件会在actions之前触发。
    【解决方案2】:

    您看到的是一个空白页,因为您没有返回任何 View,而是返回诸如 OkBadRequest 等其他内容。

    如果您想根据任何决定重定向到另一个视图,请使用return View("MyView", model); // model is optional

    所以你的代码应该如下所示。

    if(user == null)
    {
        return View("MyView", model);
    }
    

    你也可以使用return RedirectToAction("MyView");

    【讨论】:

      猜你喜欢
      • 2011-06-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-30
      • 1970-01-01
      相关资源
      最近更新 更多