2013-04-18 33 views
2

验证cookie中如何添加用户ID TI认证的饼干如何添加的用户ID在mvc4

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Web; 
using System.Web.Mvc; 
using System.Web.Security; 
using System.Security.Cryptography; 
using System.Text; 

namespace project.Controllers 
{ 
    public class LoginController : Controller 
    { 
     // GET: /Login/ 
     private DataContext db = new DataContext(); 

     public ActionResult Index() 
     { 
      return View(); 
     } 

     [HttpPost] 
     public ActionResult index(Loginmodel model) 
     { 
      if (ModelState.IsValid) 
      { 
       String username = model.Username; 
       User Login = db.Users.Where(m => m.Name == username).First(); 
       String pass = Convert.ToBase64String(new MD5CryptoServiceProvider().ComputeHash(new UTF8Encoding().GetBytes(model.Password))); 

       if (Login != null && pass == Login.Password) 
       { 
        FormsAuthentication.SetAuthCookie(model.Username, false); 
        return RedirectToAction("index", "Project"); 
       } 

       ModelState.AddModelError("", "Invalid username or password"); 
      } 

      return View(); 
     }    
    } 
} 

回答

1

这是一个很好的代码项目的文章,在相当不错的细节不同的方式解释完成你想要做的事情。 http://www.codeproject.com/Articles/36836/Forms-Authentication-and-Role-based-Authorization

if (!FormsAuthentication.CookiesSupported) 
{ 
    //If the authentication ticket is specified not to use cookie, set it in the Uri 
    FormsAuthentication.SetAuthCookie(encrypetedTicket, createPersistentCookie); 
} 
else 
{ 
    //If the authentication ticket is specified to use a cookie, wrap it within a cookie. 
    //The default cookie name is .ASPXAUTH if not specified 
    //in the <forms> element in web.config 
    HttpCookie authCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encrypetedTicket); 

    //Set the cookie's expiration time to the tickets expiration time 
    if(ticket.IsPersistent) 
     authCookie.Expires =ticket.Expiration ; 

    ////Set the cookie in the Response 
    HttpContext.Current.Response.Cookies.Add(authCookie); 
} 
+0

它把它放在登录控制器吗?我的代码不能识别加密票据。 –

+0

对不起,我没有详细说明。该票据来自FormsAuthenticationTicket formsTicket = new FormsAuthenticationTicket(...)。当您向门票提问时,tickets.userdata将是您在创建时指定的任何内容。加密的一块可以使用:string encrypetedTicket = FormsAuthentication.Encrypt(ticket); –