/*******************web.config*****************************************/
<system.web>
<compilation debug="true" targetFramework="4.7.2" />
<httpRuntime targetFramework="4.7.2" />
<authentication mode="Forms">
<forms
name="loginName"
loginUrl="/UserInfo/Login"
cookieless="UseCookies"
path="/" protection="All"
timeout="30"
></forms>
</authentication>
</system.web>
/****************************Global.asax***********************************/
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Principal;
using System.Web;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;
using System.Web.Security;
using WebApplication7.Models;
namespace WebApplication7
{
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
}
protected void Application_AuthenticateRequest(object sender, EventArgs e)
{
//1、通过sender获取http请求
// HttpApplication app = new HttpApplication();//实例化
HttpApplication app = sender as HttpApplication;
//2、拿到http上下文
HttpContext context = app.Context;
//3、根据FormsAuthe,来获取cookie
var cookie = context.Request.Cookies[FormsAuthentication.FormsCookieName];
if (cookie != null)
{
//获取cookie的值
var ticket = FormsAuthentication.Decrypt(cookie.Value);
if (!string.IsNullOrWhiteSpace(ticket.UserData))
{
//把一个字符串类别变成实体模型
var model = JsonConvert.DeserializeObject<UserInfo>(ticket.UserData);
context.User = new MyFormsPrincipal<UserInfo>(ticket, model);
}
}
}
}
public class MyFormsPrincipal<TUserData> : IPrincipal where TUserData : class, new()
{
private IIdentity _identity;
private TUserData _userData;
public MyFormsPrincipal(FormsAuthenticationTicket ticket, TUserData userData)
{
if (ticket == null)
throw new ArgumentNullException("ticket");
if (userData == null)
throw new ArgumentNullException("userData");
_identity = new FormsIdentity(ticket);
_userData = userData;
}
public TUserData UserData
{
get { return _userData; }
}
public IIdentity Identity
{
get { return _identity; }
}
public bool IsInRole(string role)//这里暂时不实现
{
return false;
}
}
}
/**************************UserInfoController ***************************************/
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using WebApplication7.Models;
namespace WebApplication7.Controllers
{
public class UserInfoController : Controller
{
private UserInfoDb db = new UserInfoDb();
// GET: UserInfo
[Authorize]
public ActionResult Index()
{
return View(db.Users.ToList());
}
public ActionResult Login()
{
ViewBag.ReturnUrl = "http://www.baidu.com";
return View();
}
[HttpPost]
public ActionResult login(UserInfo login)
{
if (ModelState.IsValid)
{
var LoginUser = db.Users.FirstOrDefault(a => a.Name == login.Name && a.Password == login.Password);
if (LoginUser != null)
{
//存入票据(用户登录的时候去存信息,如果有信息直接去登录)
SetAuthCookie(LoginUser);
//获取登录地址
var returnUrl = Request["ReturnUrl"];
//判断登录地址是不是空值
if (!string.IsNullOrWhiteSpace(returnUrl))
{
return Redirect(returnUrl);
}
else
{
return Redirect("/Home/index");
}
}
else
{
ModelState.AddModelError("", "账号密码不对");
return View(login);
}
}
else
{
ModelState.AddModelError("", "输入的信息有误");
return View(login);
}
}
public ActionResult Loginout()
{
//删除票据
FormsAuthentication.SignOut();
//清除cookie
Response.Cookies[FormsAuthentication.FormsCookieName].Expires = DateTime.Now.AddDays(-1);
Response.Cookies.Remove(FormsAuthentication.FormsCookieName);
return RedirectToAction("Index", "Home");
}
public void SetAuthCookie(UserInfo loginModel)
{
//1、将对象转换成json
//var userdata = loginModel.ToJson();
var userdata = JsonConvert.SerializeObject(loginModel);
//2、创建票据FormsAuthenticationTicket
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(2, "loginUser", DateTime.Now, DateTime.Now.AddDays(1), false, userdata);
//对票据进行加密
var tickeEncrypt = FormsAuthentication.Encrypt(ticket);
//创建Cookie,定义
HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, tickeEncrypt);
cookie.HttpOnly = true;
cookie.Secure = FormsAuthentication.RequireSSL;
cookie.Domain = FormsAuthentication.CookieDomain;
cookie.Path = FormsAuthentication.FormsCookiePath;
cookie.Expires = DateTime.Now.Add(FormsAuthentication.Timeout);
//先移除cookie,在添加cookie
Response.Cookies.Remove(FormsAuthentication.FormsCookieName);
Response.Cookies.Add(cookie);
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
db.Dispose();
}
base.Dispose(disposing);
}
}
}
/****************************UserInfo**************************************/
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Web;
namespace WebApplication7.Models
{
[Table("user")]
public class UserInfo
{
[Key]
public int Id { get; set; }
[Required]
public string Name { get; set; }
[Required]
public string Password { get; set; }
}
}
/***************************Login.cshtml***************************************/
@model WebApplication7.Models.UserInfo
@{
ViewBag.Title = "Login";
}
/**************************Loginout*********************************/
@{
ViewBag.Title = "Loginout";
}
<h2>Loginout</h2>
<h2>Login</h2>
@using (Html.BeginForm("Login", "UserInfo", new { ReturnUrl = ViewBag.ReturnUrl }, FormMethod.Post, new { @class = "form-horizontal", role = "form" }))
{
@Html.AntiForgeryToken()
@Html.EditorForModel()
<input type="submit" value="submit" />
}