【问题标题】:Role based custom authentication system in ASP.NET MVC directing to ErrorASP.NET MVC 中针对错误的基于角色的自定义身份验证系统
【发布时间】:2016-10-20 07:22:18
【问题描述】:

您好,我为我的 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
    }

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

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

对象引用未设置为对象的实例。

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

【问题讨论】:

  • FormsAuthentication_OnAuthenticate 内的哪一行抛出对象引用异常?似乎一个变量试图从其他对象分配空引用。
  • @TetsuyaYamamoto 出现错误,如关注 i.imgur.com/jJb18Mi.png

标签: c# asp.net-mvc asp.net-mvc-4 form-authentication custom-authentication


【解决方案1】:

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

类似这样的事情,你自己的代码获取角色和身份验证

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

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

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

【讨论】:

  • 我需要以AuthorizeUserAttribute 创建新类吗?
  • 是的,您需要这样做。对于任何自定义过滤器,您都需要添加一个新类,但请确保您使用的任何过滤器都以 Attribute 结尾,然后对其基类进行某种形式的继承
  • 我应该将 AuthorizeUserAttribute 类放在任何特定位置的什么位置?,我在 Home Controller 类中的 Dashboard 控制器方法
  • 我这样做的方法是有一个名为过滤器的文件夹,它们都保存在其中。它可以帮助任何查看您的代码的人知道应该在哪里
  • 其实我有点不清楚,您是否建议在其中创建新文件夹调用filters,然后在其中创建类调用AuthorizeUserAttribute,然后将FormsAuthentication_OnAuthenticate 方法放入AuthorizeUserAttribute 类不在全球.asax ?
猜你喜欢
  • 2016-03-07
  • 2017-08-26
  • 1970-01-01
  • 2021-02-21
  • 2013-11-07
  • 2018-09-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多