MVC Form验证 登陆和退出Cookies的设定和消除
红色部分为重点
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"); }
MVC Form验证 登陆和退出Cookies的设定和消除的更多相关文章
- ASP.NET MVC Form验证
一.前言 关于表单验证,园子里已经有不少的文章,相信Web开发人员也都基本写过,最近在一个个人项目中刚好用到,在这里与大家分享一下.本来想从用户注册开始写起,但发现东西比较多,涉及到界面.前端验证.前 ...
- tornado web高级开发项目之抽屉官网的页面登陆验证、form验证、点赞、评论、文章分页处理、发送邮箱验证码、登陆验证码、注册、发布文章、上传图片
本博文将一步步带领你实现抽屉官网的各种功能:包括登陆.注册.发送邮箱验证码.登陆验证码.页面登陆验证.发布文章.上传图片.form验证.点赞.评论.文章分页处理以及基于tornado的后端和ajax的 ...
- ASP.NET MVC Form表单验证与Authorize特性
一.Form表单验证 1.基本概念 表单验证是一个基于票据(ticket-based)[也称为基于令牌(token-based)]的系统.当用户登录系统以后,会得到一个包含基于用户信息的票据(tick ...
- 本博文将一步步带领你实现抽屉官网的各种功能:包括登陆、注册、发送邮箱验证码、登陆验证码、页面登陆验证、发布文章、上传图片、form验证、点赞、评论、文章分页处理以及基于tronado的后端和ajax的前端数据处理。
本博文将一步步带领你实现抽屉官网的各种功能:包括登陆.注册.发送邮箱验证码.登陆验证码.页面登陆验证.发布文章.上传图片.form验证.点赞.评论.文章分页处理以及基于tronado的后端和ajax的 ...
- 【MVC】ASP.NET MVC Forms验证机制
http://www.cnblogs.com/bomo/p/3309766.html 随笔 - 121 文章 - 0 评论 - 92 [MVC]ASP.NET MVC Forms验证机制 ASP. ...
- Asp.Net MVC 身份验证-Forms
Asp.Net MVC 身份验证-Forms 在MVC中对于需要登录才可以访问的页面,只需要在对应的Controller或Action上添加特性[Authorize]就可以限制非登录用户访问该页面.那 ...
- ajax实现用户登陆,退出,java做后端
最近http老师布置了个任务,用cookie完成登陆,退出.Http老师讲的是node.js写后端,由于自己还是擅长java些,还是用Java做了. 以前跟着教程写过一个网站,当初是用jsp+serv ...
- MVC身份验证.MVC过滤器.MVC6关键字Task,Async.前端模拟表单验证,提交.自定义匿名集合.Edge导出到Excel.BootstrapTree树状菜单的全选和反选.bootstrap可搜索可多选可全选下拉框
1.MVC身份验证. 有两种方式.一个是传统的所有控制器继承自定义Control,然后再里面用MVC的过滤器拦截.所以每次网站的后台被访问时.就会先走入拦截器.进行前端和后端的验证 一个是利用(MVC ...
- MVC用户验证
MVC提供了四种Filter(钩子),用于在Action执行之前或者之后,我们能够做一些事情,比如说判断有没有登录,比如说判断有没有权限. IAuthorizationFilter:在所有Filter ...
随机推荐
- 在iOS9 中使用3D Touch
iOS9提供了四类API( Home Screen Quick Action . UIKit Peek & Pop . WebView Peek & Pop 和 UITouch For ...
- Unbuntu18.04通过apt源方式安装mysql5.7.22
Ubuntu18.04在今年4月底发布了,喜欢尝鲜的小伙伴肯定是第一时间就更新了系统版本,那么在Ubuntu18.04中怎么安装msyql5.7(mysql8.0因为新出,再观望一段时间)呢? * 带 ...
- Python爬虫利器:BeautifulSoup库
Beautiful Soup parses anything you give it, and does the tree traversal stuff for you. BeautifulSoup ...
- Activiti源码:StandaloneInMemProcessEngineConfiguration与SpringProcessEngineConfiguration
activiti-engine-5.22.0-sources.jar package org.activiti.engine.impl.cfg; StandaloneInMemProcessEngin ...
- How to delete deployed process definition in activiti?
https://community.alfresco.com/thread/219767-how-to-delete-deployed-process
- vue 请求后台数据 (copy)
https://www.cnblogs.com/calledspeed001/p/7094494.html var that=this get请求 that.$http.get("1.txt ...
- maven的pom.xml举例
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://mave ...
- 我为什么放弃MySQL?选择了MongoDB
最近有个项目的功能模块,为了处理方便,需要操作集合类型的数据以及其他原因.考虑再三最终决定放弃使用MySQL,而选择MongoDB. 两个数据库,大家应该都不陌生.他们最大的区别就是MySQL为关系型 ...
- pgm1
很遗憾前面只看过 Michael Jordan 写的一部分,这次打算把 Daphne Koller 和 Nir Friedman 合著的 Probabilistic Graphical Models: ...
- 【题解】 bzoj1503: [NOI2004]郁闷的出纳员 (Splay)
bzoj1503,懒得复制,戳我戳我 Solution: 我知不知道我是那根筋抽了突然来做splay,调了起码\(3h+\),到第二天才改出来(我好菜啊),当做训练调错吧 一个裸的splay,没啥好说 ...