我是ASP.net MVC的新手,并使用它创建了我的第一个Web应用程序。在我的应用程序中我使用数据库身份验证我在控制器中创建了Login操作,检查输入的用户名和密码是否存在于DB中,如果存在,则在Session中输入所需的值,并根据权限将用户重定向到页面,将用户重定向到登录页面。喜欢这个
public ActionResult Login()
{
if(uservalid)
{
//set session values and redirect to dashboard
}
else
{
//redirect to login
}
}
在我的应用程序中,有些功能只能在用户登录时访问。我想在用户尝试访问这些功能之前检查用户是否登录,如果他没有登录或没有权限,则重定向到登录页面或显示一些错误消息。
public ActionResult SomeAction()
{
//Available only when user is logged-in
}
那么我该如何检查用户是否登录并授予访问权限。我阅读了有关Authorize属性但不知道如何使用它,因为我正在使用数据库身份验证。
答案 0 :(得分:4)
我应用[Authorize]
以及我自己的customattribute来限制基于权限的操作。代码在
[Authorize]
[FeatureAuthentication(AllowFeature=FeatureConst.ShowDashboard)]
public ActionResult Index()
{
}
过滤代码
public class FeatureAuthenticationAttribute : FilterAttribute, IAuthorizationFilter
{
public FeatureConst AllowFeature { get; set; }
public void OnAuthorization(AuthorizationContext filterContext)
{
//var featureConst = (FeatureConst)filterContext.RouteData.Values["AllowFeature"];
var filterAttribute = filterContext.ActionDescriptor.GetFilterAttributes(true)
.Where(a => a.GetType() == typeof(FeatureAuthenticationAttribute));
if (filterAttribute != null)
{
foreach (FeatureAuthenticationAttribute attr in filterAttribute)
{
AllowFeature = attr.AllowFeature;
}
User currentLoggedInUser = (User)filterContext.HttpContext.Session["CurrentUser"];
bool allowed = ACLAccessHelper.IsAccessible(AllowFeature.ToString(), currentLoggedInUser);
// do your logic...
if (!allowed)
{
string unAuthorizedUrl = new UrlHelper(filterContext.RequestContext).RouteUrl(new { controller = "home", action = "UnAuthorized" });
filterContext.HttpContext.Response.Redirect(unAuthorizedUrl);
}
}
}
}
答案 1 :(得分:4)
如果您使用FormsAuthentication
,则无需使用ASP.NET会话来跟踪当前经过身份验证的用户。
我读过有关授权属性但不知道如何使用它的原因 使用数据库身份验证。
假设你选择了FormsAuthentication,一旦验证了用户的凭据,就应该设置一个表单身份验证cookie:
public ActionResult Login()
{
if(uservalid)
{
FormsAuthentication.SetAuthCookie("username", false);
return RedirectToAction("SomeProtectedAction");
}
else
{
//redirect to login
}
}
然后:
[Authorize]
public ActionResult SomeAction()
{
string currentlyLoggedInUser = User.Identity.Name;
}
顺便说一下,如果使用Visual Studio中的Internet模板创建新的ASP.NET MVC应用程序,您可以查看AccountController,它负责验证用户身份并设置表单身份验证cookie。当然,您可以抛弃所有Entity Framework废话,并针对您自己的数据库表实现您自己的凭据验证。
答案 2 :(得分:2)
您应该创建一个基本控制器并从基本控制器继承其他控制器,然后检查会话是否为空以验证用户。
public class BaseController : Controller
{
protected override void OnActionExecuting(ActionExecutingContext filterContext)
{
if (Session["User"]== null)
{
filterContext.HttpContext.Response.Redirect("/somepage");
}
}
public class SomeController : BaseController
{
}
答案 3 :(得分:0)
有多种方法可以做到,但首选的方法是使用Annotation。这是一篇文章 How to get custom annotation attributes for a controller action in ASP.NET MVC 4?
如果您开始使用,我建议您按照教程进行操作 http://www.asp.net/mvc