//一、首先是登录:
public class AccountController : BaseController
{
public ActionResult Login()
{
//已经登录的,直接到默认首页
if (HttpContext.Request.IsAuthenticated)
{
return Redirect(FormsAuthentication.DefaultUrl);
}
return View();
}
[HttpPost]
public ActionResult Login(string userName, string userPassword, string isRemember)
{
if (userName == "admin" && userPassword == "111")
{
Person p = new Person() { Name = userName, Roles = "admin", Age = 23, Email = "xx@qq.com", Ip = MD5Helper.MD5Encrypt(Request.UserHostAddress) };
bool remenber = isRemember == null ? false : true;
//把用户对象保存在票据里
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, userName, DateTime.Now, DateTime.Now.AddTicks(FormsAuthentication.Timeout.Ticks), remenber, p.ObjToJson());
//加密票据
string hashTicket = FormsAuthentication.Encrypt(ticket);
HttpCookie userCookie = new HttpCookie(FormsAuthentication.FormsCookieName, hashTicket);
if (remenber)
{
userCookie.Expires = DateTime.Now.AddTicks(FormsAuthentication.Timeout.Ticks);
}
Response.Cookies.Add(userCookie);
string returnUrl = HttpUtility.UrlDecode(Request["ReturnUrl"]);
if (string.IsNullOrEmpty(returnUrl))
{
return RedirectToAction("Index", "Home");
}
else
{
return Redirect(returnUrl);
}
}
else
{
ViewData["Tip"] = "用户名或密码有误!";
return View();
}
}
public ActionResult Logout()
{
//取消Session会话
Session.Abandon();
//删除Forms验证票证
FormsAuthentication.SignOut();
return RedirectToAction("Login", "Account");
}
}
//二、权限验证
public class AuthAttribute : AuthorizeAttribute
{
/// <summary>
/// 验证核心代码
/// </summary>
/// <param name="httpContext"></param>
/// <returns></returns>
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
return string.IsNullOrEmpty(UserInfo.UserID) == false;
}
/// <summary>
/// 验证失败处理
/// </summary>
/// <param name="filterContext"></param>
protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{
if (filterContext.HttpContext.Request.IsAjaxRequest())
{
JsonResult json = new JsonResult();
json.Data = new { Status = 401, Message = "权限不足,服务器已拒绝您的操作!" };
json.JsonRequestBehavior = JsonRequestBehavior.AllowGet;
filterContext.Result = json;
}
else
{
UrlHelper url = new UrlHelper(filterContext.RequestContext);
filterContext.Result = new BaseController().PageReturn("请先登录!", PubLib.PublicVars.GetNewURL(url.Action("Login", "StuEnroll")));
}
return;
}
}