【发布时间】:2013-12-08 11:08:25
【问题描述】:
我是 Asp.net MVC Web 开发的新手,我使用它开发了一个应用程序。在我的应用程序中,我使用自己的身份验证和授权检查,如下所示: 我在这样创建的登录操作方法中创建登录控制器
[HttpPost]
public ActionResult Login(LoginViewModel Info)
{
if (ModelState.IsValid)
{
if (checking username and password exist in DB or not)
{
//Adding required values in session
Session["username"] = Info.Username;
//Redirect to dashboard
}
else
{
//not found redirect to login page
}
}
return View();
}
现在在管理控制器中访问操作方法时,我使用“自定义授权”属性来检查用户是否已登录并拥有方法权限
public class AdminController : Controller
{
[CustomAuthorize(ValidRole = "Admin")]
public ActionResult Index()
{
return View();
}
}
为此,我像这样覆盖默认 AuthorizeAttribute
public class CustomAuthorize : AuthorizeAttribute
{
// Custom property
public string ValidRole { get; set; }
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
if (httpContext.Session["username"] == null)
{
//User is not logged-in so redirect to login page
return false;
}
}
protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{
filterContext.Result = new RedirectToRouteResult(
new RouteValueDictionary(
new
{
controller = "Login",
action = "Login"
})
);
}
}
这段代码对我来说很好用。我的问题是有没有更好的解决方案来检查用户是否已登录,并根据它将用户重定向到登录或仪表板页面,以便用户无法操纵 url 并访问他未授权的功能。
提前致谢
【问题讨论】:
标签: asp.net-mvc authentication authorization