mvc 微软票据验证

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


}
}

mvc 微软票据验证,古老的榕树,5-wow.com

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。