MVC Form验证 登陆和退出Cookies的设定和消除

时间:2022-11-06 23:49:10

红色部分为重点

1.webconfig配置

 <system.web>节点下添加
<authentication mode="Forms">
<forms loginUrl="~/Account/Login" timeout="2880" name=".userInfo" protection="All" path="/"></forms>
</authentication>
如果有如下节点则删除

<system.webServer>
<modules>
<remove name="FormsAuthentication" />
</modules>
</system.webServer>

2.<forms loginUrl="~/Account/Login  中的loginUrl的值的~不能省略
        public ActionResult Login(LoginViewModel login)
{
//验证账号密码
AspTaskServiceClient service = new AspTaskServiceClient(); //调用svc服务
if (service.IsLoginOk(login.UserId, Commen.Sha256(login.Password)))
{ AspUser user = service.GetUserInfo(login.UserId);
LoginViewModel userinfo = new LoginViewModel()
{
UserId = login.UserId,
Password = login.Password,
UserName = user.LoginUserName,
AspId = user.AspId,
IsAsp = user.IsAspUser ? "1" : "0"
}; FormsAuthentication.SetAuthCookie(JsonHelper.ToJsonString(userinfo), false); //设置cookies
if (Request.QueryString["ReturnUrl"] != null)
{
if (Request.QueryString["ReturnUrl"].Contains("LogOff"))
{ return RedirectToAction("../Task/TaskList");
}
else
{
return Redirect(Request.QueryString["ReturnUrl"]);
} } else return RedirectToAction("../Task/TaskList");
}
else
{
ModelState.AddModelError("", "正しくユーザー または パスワードを入力ください。");
return View(login);
} }

  

3读取cookies
        protected override bool AuthorizeCore(System.Web.HttpContextBase httpContext)
{
if (string.IsNullOrWhiteSpace(HttpContext.Current.User.Identity.Name)) return false;
LoginViewModel userinfo=JsonHelper.ToObject<LoginViewModel>(HttpContext.Current.User.Identity.Name); AspTaskServiceClient service = new AspTaskServiceClient(); string _userId = userinfo.UserId;
string _password = userinfo.Password;
if (_userId == "" || _password == "") return false;
if (service.IsLoginOk(_userId, Commen.Sha256(_password)))
{
return true;
}
else
{
return false;
} }

  

附:JsonHelper.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Newtonsoft.Json; namespace xxx.Serialization.Json
{
public class JsonHelper
{
public static string ToJsonString(object obj)
{
return JsonConvert.SerializeObject(obj);
} public static T ToObject<T>(string jsonString)
{
return JsonConvert.DeserializeObject<T>(jsonString);
}
}
}

  

sha256.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Web; namespace xxx.Controllers
{
public class Commen
{
public static string Sha256(string plainText)
{
SHA256Managed _sha256 = new SHA256Managed();
byte[] _cipherText = _sha256.ComputeHash(Encoding.Default.GetBytes(plainText));
return Convert.ToBase64String(_cipherText);
}
}
}

  

4.action的cookie值传入到view的js文件

        public ActionResult TaskList()
{
ViewBag.cookies = User.Identity.Name;
return View();
}

  

   view里的js文件

如下

        function getUserInfo() {//获取当前用户
user = new Object();
var arrCookie = @Html.Raw(ViewBag.cookies);
if (arrCookie!=null) {
user.userId =arrCookie["UserId"];
user.userName = arrCookie["UserName"]
user.aspId =arrCookie["AspId"];
user.isAspUser = arrCookie["IsAsp"]== "1" ? true : false;
}
}

  5.退出登陆

1._LoginPartial.cshtml显示设置   必须添加引用

@using xxxx.Serialization.Json;
@using xxx.Models; @if (!string.IsNullOrWhiteSpace(User.Identity.Name))
{ using (Html.BeginForm("LogOff", "Account", FormMethod.Post, new { id = "logoutForm", @class = "navbar-right" }))
{
Html.AntiForgeryToken(); <ul class="nav navbar-nav navbar-right">
<li>
@Html.ActionLink(JsonHelper.ToObject<LoginViewModel>(User.Identity.Name).UserName + " 様", "", "", routeValues: null, htmlAttributes: new { title = "" })
</li>
<li><a href="javascript:document.getElementById('logoutForm').submit()">ログオフ</a></li> </ul>
}
}

  

  2.退出登陆清除cookies

        public ActionResult LogOff()
{ FormsAuthentication.SignOut(); return RedirectToAction("Login", "Account"); }