Form Authentication

1.创建登陆的控制器和视图,实现登陆基本功能

2.创建视图模型,并在Action里面引用。

3.创建一个接口两个类,那个IUserPricipal接口要实现IPrincipal接口,UserPricipal类需要继承这个接口,然后去初始化IIdentity这个接口,UserPricipalModel类则是返回用户输出的Cookie的数据模型。

 

具体代码:

两个类一个接口:

interface ICustomPrincipal : IPrincipal
{
UserViewModel User { get; set; }
}

public class CustomPriceipal : ICustomPrincipal
{
public IIdentity Identity { get; private set; }

public bool IsInRole(string role)
{
return false;
}

public CustomPriceipal(string email)
{
this.Identity = new GenericIdentity(email);
}
public bool IsAdmin { get; set; } = false;
public string UserName { get; set; }
public UserViewModel User { get; set; }

}

public class CustomPrincipalSerializeModel
{
public string UserName { get; set; }
public bool IsAdmin { get; set; }
public UserViewModel User { get; set; }
}

 

Action代码  :

[HttpPost]
public ActionResult Login(UserViewModel model)
{
if (model.Password == "" || model.UserName == "")
{
return View(model);
}
CustomPrincipalSerializeModel serializeModel = new CustomPrincipalSerializeModel();
JavaScriptSerializer serializer = new JavaScriptSerializer();
serializeModel.User = model;
serializeModel.UserName = model.UserName;
string userData = serializer.Serialize(serializeModel);
var ticket = new FormsAuthenticationTicket(2, model.UserName, DateTime.Now, DateTime.Now.AddMinutes(1), false, userData);
string encryptTickey = FormsAuthentication.Encrypt(ticket);
HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName,encryptTickey);

Response.Cookies.Remove(cookie.Name);
Response.Cookies.Add(cookie);
return Redirect("/Home/Index");
}

 

Global文件代码:

 

protected void Application_PostAuthenticateRequest(Object sender, EventArgs e)
{
HttpCookie cookie = Request.Cookies[FormsAuthentication.FormsCookieName];

if(cookie!=null)
{
FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(cookie.Value);
if (ticket != null && !string.IsNullOrEmpty(ticket.UserData))
{
JavaScriptSerializer serializer = new JavaScriptSerializer();
CustomPrincipalSerializeModel serializeModel = serializer.Deserialize<CustomPrincipalSerializeModel>(ticket.UserData);

CustomPriceipal newUser = new CustomPriceipal(ticket.Name);
newUser.User = serializeModel.User;
newUser.UserName = serializeModel.UserName;
newUser.IsAdmin = serializeModel.IsAdmin;
HttpContext.Current.User = newUser;
}
}
}

 

转载于:https://www.cnblogs.com/luoluoluoD/p/7261513.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值