0

Bonjour, J'ai écrit un système d'authentification personnalisé basé sur les rôles pour mon application ASP.NET MVC.Système d'authentification personnalisé basé sur les rôles dans ASP.NET MVC redirigeant vers l'erreur

Ainsi changements je l'ai fait comme la suite

Dans Global.asax.cs Fichier ajouté Après Méthode

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; 
} 

}

dans Web.Config

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

à FilterConfig.cs dans App_Start dossier

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

Login méthode Controller

[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 page

   @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> 
       } 

Enfin, dans HomeController.cs

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

Ici, tout a parfaitement fonctionné, mais je Accidentellement Debuged/Run Dashboard Voir la page sans connecter,

Maintenant, je suis de se retrouver avec l'erreur suivante dans FormsAuthentication_OnAuthenticate méthode dans Global.asax Fichier,

La référence d'objet n'est pas définie sur une instance d'un objet.

Maintenant, quand je commence à déboguer ce projet sa fin il

+0

Quelle ligne lançant une exception de référence d'objet dans 'FormsAuthentication_OnAuthenticate'? Semble qu'une variable essaye d'assigner une référence nulle à partir d'un autre objet. –

+0

@TetsuyaYamamoto obtenir une erreur comme suit http://i.imgur.com/jJb18Mi.png –

Répondre

0

votre attribut Autorisez est de ne pas utiliser votre implémentation, ce que vous avez créé vous devriez avoir vraiment fait dans AuthoriseAttribue personnalisé qui hérite de la AuthorizeAttribute

quelque chose comme ceci avec votre propre code obtenir des rôles et l'authentification

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

puis votre ViewModel \ modèle devrait ressembler à ceci

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

ai-je besoin de créer une nouvelle classe en tant que AuthorizeUserAttribute? –

+0

oui, vous aurez besoin de. Pour tous les filtres personnalisés, vous devrez ajouter une nouvelle classe, mais assurez-vous que tout filtre que vous utilisez finira par Attribute et héritera de sa classe de base –

+0

où dois-je placer cette classe 'AuthorizeUserAttribute' dans un emplacement spécifique?, ma méthode de contrôleur 'Dashboard' dans Home Controller Class –