0

嗨,我为我的 ASP.NET MVC 应用程序编写了一个基于角色的自定义身份验证系统。

所以我所做的改变如下

Global.asax.cs文件中添加了以下方法

protected void Application_Start()
{
    AreaRegistration.RegisterAllAreas();
    FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
    RouteConfig.RegisterRoutes(RouteTable.Routes);
    BundleConfig.RegisterBundles(BundleTable.Bundles);

}
protected void FormsAuthentication_OnAuthenticate(Object sender, FormsAuthenticationEventArgs e)
{
try
{
   if (FormsAuthentication.CookiesSupported == true)
   {
    if (Request.Cookies[FormsAuthentication.FormsCookieName] != null)
    {
        try
        {                              
            string username = FormsAuthentication.Decrypt(Request.Cookies[FormsAuthentication.FormsCookieName].Value).Name;
            string roles = string.Empty;

            if(!string.IsNullOrEmpty(username))
            {
                // user --> Roles Getting from DB using Stored Procdure

                roles = user.RoleName;
            }

            e.User = new System.Security.Principal.GenericPrincipal(
              new System.Security.Principal.GenericIdentity(username, "Forms"), roles.Split(';'));
        }
        catch (Exception)
        {
           throw;
        }
    }
}
}
catch (Exception)
{
    throw;
}

}

Web.Config中

<authentication mode="Forms">
  <forms loginUrl="~/Account/Login" timeout="2880" />
</authentication>

App_Start文件夹中的FilterConfig.cs

public class FilterConfig
{
    public static void RegisterGlobalFilters(GlobalFilterCollection filters)
    {
        filters.Add(new HandleErrorAttribute());
    }
}

在登录控制器方法中

    [AllowAnonymous]
    public ActionResult Login(string returnUrl)
    {
        ViewBag.ReturnUrl = returnUrl;
        return View();
    }

    // POST: /Account/Login

    [HttpPost]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]
    public async Task<ActionResult> Login(LoginUserViewModel loginmodel, string returnUrl)
    {
       try
       { 
            UserViewModel userdata=null;

            if (loginmodel.UserName != null & loginmodel.Password != null)
            {
                // Get userData via Stored Procedure



                if (userdata != null)
                {                                                                                     

                    FormsAuthentication.SetAuthCookie(loginmodel.UserName, false);
                    if (Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/")
                        && !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\"))
                    {
                        return Redirect(returnUrl);
                    }
                    else
                    {
                        return RedirectToAction("Dashboard", "Home");
                    }


                }
                else
                {
                    ModelState.AddModelError("", "Login failed.");
                }

            }   
            else
            {
                ModelState.AddModelError("", "Login failed.");
            }

            return View(userdata);
       }
       catch (Exception)
       {
           throw;
       }
    }

Login.cshtml页面

                @using (Html.BeginForm("Login", "Account", new { ReturnUrl = ViewBag.ReturnUrl }, FormMethod.Post, new { @class = "form-horizontal", role = "form" }))
                {
                    @Html.AntiForgeryToken()
                    @* rest of data *@
                    @Html.ValidationSummary(true, "", new { @class = "text-danger" })

                    <div class="form-group ">
                        <div class="col-sm-12 col-lg-12 col-md-12">
                            <button type="submit" >Login</button>
                        </div>
                    </div>
                }

最后在HomeController.cs

    [Authorize(Roles="admin")]
    public ActionResult Dashboard()
    {
      //rest of fetching
    }

在这里一切正常,但不小心我在没有登录的情况下调试/运行仪表板视图页面,

现在我在文件中的FormsAuthentication_OnAuthenticate方法中出现以下错误,Global.asax

你调用的对象是空的。

现在,当我开始调试这个项目时,它就在那里结束

4

1 回答 1

0

您的 Authorize 属性没有使用您的实现,您创建的内容应该在继承 AuthorizeAttribute 的自定义 AuthoriseAttribue 中真正完成

像这样用你自己的代码获取角色和身份验证

public class AuthorizeUserAttribute : AuthorizeAttribute
{
 .... 
 //your code here 
}

然后你的 ViewModel \ Model 应该是这样的

[AuthorizeUserAttribute(Roles="admin")]
public ActionResult Dashboard()
{
  //rest of fetching
}
于 2016-10-20T07:40:09.510 回答