using System;
using System.Collections.Generic;
using
System.Linq;
using System.Web;
using System.Web.Mvc;
using
System.Web.Security;
namespace 验证权限.Controllers
{
public class HomeController :
Controller
{
//
// GET: /Home/
public ActionResult Index()
{
//第一种获取cookie
HttpCookie cookie = Request.Cookies["ticket"];
//解密后还原成ticket对象
FormsAuthenticationTicket ticket =
FormsAuthentication.Decrypt(cookie.Value);
Response.Write("用户名="+ticket .Name +"权限="+ticket.UserData);
//第二种 使用微软身份验证机制授权
if
(HttpContext.Request.IsAuthenticated)
{
string
username= HttpContext.User.Identity.Name;//获取用户名
FormsIdentity formsidentity= HttpContext.User.Identity as FormsIdentity;
//身份信息
// formsidentity.Ticket;
//登陆过
}
else
{
//未登录
}
return View();
}
public ActionResult
Login()
{
return View();
}
[HttpPost]
public ActionResult Login(FormCollection form)
{
if (form["txtName"] == "James" && form["txtPwd"] ==
"123")
{
#region 使用微软票据 加密方式保存cookie
//使用微软票据
加密方式保存cookie
//FormsAuthenticationTicket ticket = new
FormsAuthenticationTicket(1,"james",DateTime .Now ,DateTime .Now
.AddMinutes(5),true,"1,2,3");
////将票据对象转成加密字符串
//string
hashCookie = FormsAuthentication.Encrypt(ticket);
//HttpCookie cokie = new HttpCookie("ticket",hashCookie);
//cokie.Expires = DateTime.Now.AddMinutes(5);
//Response.Cookies.Add(cokie);
//Response.Write("登陆成功!");
#endregion
#region
使用微软自带的身份验证机制
//使用微软自带的身份验证机制
//FormsAuthentication.SetAuthCookie("james",
true);
#endregion
//结合 手动创建票据 并制定 登录用户权限 标志字符串
FormsAuthenticationTicket
ticket = new FormsAuthenticationTicket(1,"james",DateTime .Now ,DateTime .Now
.AddMinutes(5),true,"1,2,3");
////将票据对象转成加密字符串
string
hashCookie = FormsAuthentication.Encrypt(ticket);
HttpCookie
cokie = new HttpCookie(FormsAuthentication.FormsCookieName,
hashCookie);//FormsAuthentication .FormsCookieName配置文件的cookie名称
cokie.Expires
= DateTime.Now.AddMinutes(5);
Response.Cookies.Add(cokie);
}
return View();
}
}
}
原文地址:http://www.cnblogs.com/sumg/p/3744742.html