我有一个 Controller ,我只希望经过身份验证的用户能够访问它。我是否必须检查我的 Controller 中的每个方法以验证用户是否已通过身份验证,或者是否有另一种方法来处理这个问题?我可以改用注释来执行此操作吗?
来 self 的 Controller 的示例:
public ActionResult Index()
{
if (UserVerified())
{
...
}
return RedirectToAction("Login", "Account");
}
public ActionResult FacebookLogin()
{
if (UserVerified())
{
....
}
return RedirectToAction("Login", "Account");
}
private bool UserVerified()
{
if (User != null && User.Identity != null && User.Identity.IsAuthenticated)
{
return true;
}
return false;
}
最佳答案
你可以为它使用 AuthorizeAttribute。
把它付诸行动。
[Authorize]
public ActionResult Index()
{
}
[Authorize]
public ActionResult FacebookLogin()
{
}
它将为您完成所有工作。它检查当前用户是否已通过身份验证。如果他通过了身份验证 - 继续执行操作,如果他没有通过身份验证 - 返回主页。
您还可以将此属性添加到 Controller 。然后所有操作都需要授权。
[Authorize]
public class HomeController
{
public ActionResult Index()
{
}
public ActionResult FacebookLogin()
{
}
}
更新:是的,正如 Kamil 所说。请阅读这篇文章。
http://www.asp.net/web-api/overview/security/authentication-and-authorization-in-aspnet-web-api
您现在花一些时间,将来花在 ASP.NET 身份验证问题上的时间会少得多。
顺便说一句,你不需要检查
User != null && User.Identity != null
如果您使用默认身份验证,那么您始终可以确定 User.Identity
是一个正确的对象。您可以直接访问 User.Identity.IsAuthenticated
。
关于C# mvc5 - 检查用户是否在每个 Controller 方法中经过身份验证的简单方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30658315/