码迷,mamicode.com
首页 > Web开发 > 详细

mvc 微软票据验证

时间:2014-05-22 15:36:02      阅读:264      评论:0      收藏:0      [点我收藏+]

标签:class   c   ext   http   a   get   

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 微软票据验证,布布扣,bubuko.com

mvc 微软票据验证

标签:class   c   ext   http   a   get   

原文地址:http://www.cnblogs.com/sumg/p/3744742.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!