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

.net mvc结合微软提供的FormsAuthenticationTicket登陆

时间:2015-06-04 15:12:26      阅读:150      评论:0      收藏:0      [点我收藏+]

标签:

一、Web.config

技术分享
  <system.web>
    <compilation debug="true" targetFramework="4.5" />
    <httpRuntime targetFramework="4.5" />
    <authentication mode="Forms">
      <forms loginUrl="/Sign/SignIn" defaultUrl="/Home/Index" />
    </authentication>
  </system.web>
View Code

二、SignController(主要实现)

技术分享
    /// <summary>
    /// 登陆、注销功能
    /// </summary>
    public class SignController : Controller
    {
        /// <summary>
        /// 登陆页面
        /// </summary>
        /// <returns></returns>
        [AllowAnonymous]
        public ActionResult SignIn()
        {
            var isAuthenticated = System.Web.HttpContext.Current.User.Identity.IsAuthenticated;
            if (isAuthenticated) //已经验证用户
            {
                return Redirect(FormsAuthentication.DefaultUrl);
            }
            var reUrl = FormsAuthentication.GetRedirectUrl(HttpContext.User.Identity.Name, false);
            ViewBag.RedirectUrl = reUrl;

            return View();
        }

        /// <summary>
        /// 登陆功能
        /// </summary>
        /// <param name="userName">用户名</param>
        /// <param name="pwd">密码</param>
        /// <returns></returns>
        [HttpPost]
        [AllowAnonymous]
        public JsonResult LogIn(string userName, string pwd)
        {
            if (!string.IsNullOrEmpty(userName) && !string.IsNullOrEmpty(pwd))
            {
                var ticket = new FormsAuthenticationTicket(2, userName, DateTime.Now, DateTime.Now.AddMinutes(1), false, userName + pwd);
                string hashTicket = FormsAuthentication.Encrypt(ticket);
                var userCookie = new HttpCookie(FormsAuthentication.FormsCookieName, hashTicket);
                HttpContext.Response.Cookies.Add(userCookie);        //添加cookies

                var identity = new FormsIdentity(ticket);
                HttpContext.User = new CustomPrincipal(identity);       //获取请求信息,通过自定义标志(重点)

                return Json(1);
            }
            else
                return Json(0);
        }

        /// <summary>
        /// 注销
        /// </summary>
        /// <returns></returns>
        [AllowAnonymous]
        public ActionResult SignOut()
        {
            FormsAuthentication.SignOut();
            return Redirect(FormsAuthentication.LoginUrl);
        }
    }
View Code

model

技术分享
    /// <summary>
    /// 定义用户对象的基本功能(自定义)
    /// </summary>
    public class CustomPrincipal : IPrincipal
    {
        #region 字段
        private IIdentity _identity;
        #endregion

        #region 属性
        public IIdentity Identity
        {
            get { return _identity; }
        }
        #endregion

        #region 构造函数
        public CustomPrincipal(IIdentity identity)
        {
            _identity = identity;
        }
        #endregion

        #region 方法
        public bool IsInRole(string role)
        {
            throw new NotImplementedException();
        }
        #endregion
    }
View Code

view

技术分享
@{
    ViewBag.Title = "SignIn";
}

<h2>SignIn</h2>
<a href="@Url.Action("Index", "Home")">主页</a>
<a href="@Url.Action("SignIn", "Sign")"> 登陆</a>
<a href="@Url.Action("SignOut", "Sign")"> 注销</a>
<a href="@Url.Action("Detail", "Home")"> 详细</a>
<h2>name:@HttpContext.Current.User.Identity.Name</h2>
<br />
<div>用户名:<input id="user_name" /></div>
<div>密  码:<input id="user_pwd" /></div>
<div><input id="btnSumbit" type="button" value="提交" /></div>
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script>
    $(function () {
        $(#btnSumbit).click(function () {
            var data = {
                userName: $(#user_name).val(),
                pwd: $(#user_pwd).val()
            }
            $.post(@Url.Action("LogIn", "Sign"), data, function (result) {
                if (result == 1)
                    location.href = @ViewBag.RedirectUrl;
                else

                    alert(result);
            });
        })

    })
</script>
View Code

三、需要权限的控制器(调用方式)

技术分享
    [Authorize]
    public class BaseController : Controller
    {
    }
View Code
技术分享
    public class HomeController : BaseController
    {
         /// <summary>
         /// 首页
         /// </summary>
         /// <returns></returns>
         public ActionResult Index()
         {
             return View();
         }
   
        public ActionResult Detail()
        {
            var cidentity = (FormsIdentity)HttpContext.User.Identity;
            var data = cidentity.Ticket.UserData;//获取存储的 数据
            var name = HttpContext.User.Identity.Name;
            var dd = FormsAuthentication.FormsCookieName;
            return View();
        }

    }
View Code
技术分享
@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>
<a href="@Url.Action("Index", "Home")">主页</a>
<a href="@Url.Action("SignIn", "Sign")"> 登陆</a>
<a href="@Url.Action("SignOut", "Sign")"> 注销</a>
<a href="@Url.Action("Detail", "Home")"> 详细</a>
<h2>name:@HttpContext.Current.User.Identity.Name</h2>
View Code
技术分享
@{
    ViewBag.Title = "Detail";
}

<h2>Detail</h2>
<a href="@Url.Action("Index", "Home")">主页</a>
<a href="@Url.Action("SignIn", "Sign")"> 登陆</a>
<a href="@Url.Action("SignOut", "Sign")"> 注销</a>
<a href="@Url.Action("Detail", "Home")"> 详细</a>
<h2>name:@HttpContext.Current.User.Identity.Name</h2>
View Code

 

.net mvc结合微软提供的FormsAuthenticationTicket登陆

标签:

原文地址:http://www.cnblogs.com/liujinwu-11/p/4551647.html

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