5

我試圖在我的應用程序中實現窗體身份驗證。我舉了各種例子,看了這個論壇和ASP.net MVC中提供的示例和問題,但我無法實現它的工作。表單身份驗證:角色(MVC 4)C#

我管理我的用戶進行身份驗證,但作用似乎並不:-(

我已經安裝我的web.config如下工作:

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

在我的控制器我設置索引頁使用AllowAnonymous,然後在那裏檢查,如果用戶進行身份驗證。如果沒有,那麼重定向到登錄頁面..

[AllowAnonymous] 
    public ActionResult Index(string sortOrder, string searchString,string currentFilter, int? page) 
    { 
     if (!Request.IsAuthenticated) 
     { 

      return RedirectToAction("Login", "Account"); 

     } 
//Find all the employees 
     var employees = from s in db.Employees 
         select s; 
//Pass employees to the view (All works fine) 
return View(employees.ToPagedList(pageNumber, pageSize)); 
} 

這所有工作100%

我登錄的代碼如下所示:

[HttpPost] 
    [AllowAnonymous] 
    [ValidateAntiForgeryToken] 
    public ActionResult Login(User user, string returnUrl) 
    { 
     var myUser = db.Users.Where(b => b.UserName == user.UserName).FirstOrDefault(); 
     if(myUser != null) 
     { 
      if(myUser.Password==user.Password) 
      { 
       //These session values are just for demo purpose to show the user details on master page 
       //Session["User"] = user; 
       ICollection<UserAccessLevel> levels = db.UserAccessLevels.Where(b => b.UserId == myUser.UserId).ToList(); 
       //Session["levels"] = levels; 

       //Let us now set the authentication cookie so that we can use that later. 
       FormsAuthentication.SetAuthCookie(user.UserName, false); 

       return RedirectToAction("Index","Employee"); 
      } 
     } 
     ViewBag.Message = "Invalid User name or Password."; 
     return View(user); 
    } 

我也有在Global.asax文件下面的代碼:

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

        using (TrainingContext entities = new TrainingContext()) 
        { 
         User user = entities.Users.SingleOrDefault(u => u.UserName == username); 

         roles = "admin";//user.Roles; 
        } 
        //Let us set the Pricipal with our user specific details 
        e.User = new System.Security.Principal.GenericPrincipal(
         new System.Security.Principal.GenericIdentity(username, "Forms"), roles.Split(';')); 
       } 
       catch (Exception) 
       { 
        //somehting went wrong 
       } 
      } 
     } 
    } 

當我登錄我FormsAuthentication_OnAuthenticate執行一切看起來不錯。我的用戶設置和我在會話中的角色也存在...

但是,當我點擊我的員工/索引屏幕的詳細信息時,我會回到登錄屏幕(我期望它帶我到我點擊的員工的詳細信息,因爲我已登錄並且設置爲管理員角色)

請您幫助我嘗試解決問題。我坐了超過18個小時,已經試圖弄清楚這一點。

我已經看了這些解決方案,正如你所看到的大多數我的代碼來自那裏...... codeproject.com/Articles/578374/AplusBeginner-27splusTutorialplusonplusCustomplusF codeproject.com/Articles/342061/Understanding-ASP- NET-Roles-and-Membership-A-Begin codeproject.com/Articles/408306/Understanding-and-Implementing-ASP-NET-Custom-Form

如果你需要更多關於我的代碼的細節,你也可以下載它來自GitHub https://github.com/Ruandv/Training/tree/FormsAuthentication

我會感謝您的協助。

+0

你可以發佈你有你的Authorize屬性類嗎? –

+0

我沒有自定義的授權屬性類。我正在使用標準的。 – Gremlin1708

回答

3

如果您轉到數據庫並查找向用戶分配角色的表(可能由SimpleMembership?生成),您的用戶是否具有「管理員」角色?

看起來你只是在FormsAuthentication_OnAuthenticate方法中分配角色,而沒有在DB中實際設置它。

// Your method (...) 
User user = entities.Users.SingleOrDefault(u => u.UserName == username); 
roles = "admin";//user.Roles; 

而且,雖然我不能完全肯定,[Authorize(Roles = "admin")]可能會使用您的角色提供並檢查用戶是否具有/不具有在數據庫中的作用。

+0

感謝您指出數據庫部分。我在數據庫中添加了角色,並且一切正常。無時無刻。 – Gremlin1708