【发布时间】: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;
}
问题:
- 如何将 401 重定向到自定义视图?
- 如何检查所有控制器,而不仅仅是 Home/Index
【问题讨论】:
标签: c# authentication asp.net-core-mvc asp.net-identity .net-5