asp.net mvc 自定义身份验证
1.定义身份实体对象
/// <summary>
/// 网站用户实体对象
/// </summary>
public class DDTPrincipal : IPrincipal
{
public int? OrgCode { get; set; }
public string RoleName { get; set; }
public string OrgName { get; set; }
private IIdentity _identity; public DDTPrincipal(string orgcode, string roleName, string orgName, IIdentity identity)
{
int _orgCode;
int.TryParse(orgcode, out _orgCode);
OrgCode = _orgCode;
OrgName = orgName;
RoleName = roleName;
_identity = identity;
} public IIdentity Identity
{
get { return _identity; }
} public bool IsInRole(string role)
{
return RoleName.IndexOf(role)>=;
}
}
2.验证身份
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult LoginView(LoginModel model, string returnUrl)
{ if (ModelState.IsValid)
{
Account a = DataRepository.AccountProvider.GetByAccountName(model.UserName);
DataRepository.AccountProvider.DeepLoad(a,false, DeepLoadType.IncludeChildren,typeof(Org));
TList<AccountRole> arList = DataRepository.AccountRoleProvider.GetByAccountName(a.AccountName);
DataRepository.AccountRoleProvider.DeepLoad(arList, false, DeepLoadType.IncludeChildren, typeof(Role)); string roleName=string.Empty;
if (arList.Count > )
{
foreach (var item in arList)
{
roleName += item.RoleNoSource.RoleName + ",";
}
}
else { roleName = "无"; } if (a!=null&&a.AccountPassword==model.Password)
{
// return RedirectToLocal(returnUrl);
FormsAuthentication.RedirectFromLoginPage(a.UserName, false);
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(, a.UserName, DateTime.Now,
DateTime.Now.AddMinutes(), false,
string.Format("{0}|{1}|{2}", a.OrgCode.Value.ToString(),roleName,a.OrgCodeSource.OrgName));
string encryptedTicket = FormsAuthentication.Encrypt(ticket);
HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);
Response.Cookies.Add(cookie);
return Redirect(returnUrl);
}
}
// 如果我们进行到这一步时某个地方出错,则重新显示表单
ModelState.AddModelError("", "提供的用户名或密码不正确。");
return View(model); //if (ModelState.IsValid && WebSecurity.Login(model.UserName, model.Password, persistCookie: model.RememberMe))
//{
// return RedirectToLocal(returnUrl);
//}
//// 如果我们进行到这一步时某个地方出错,则重新显示表单
//ModelState.AddModelError("", "提供的用户名或密码不正确。");
//return View(model);
}
3.自定义验证属性获取验证信息
public class CustomAuthorizeAttribute:AuthorizeAttribute
{
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
httpContext.User = App_Codes.WebUtility.GetUser(httpContext);
return base.AuthorizeCore(httpContext);
}
}
4.从验证信息生成验证对象
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Security.Principal; namespace XXX.App_Codes
{
public static class WebUtility
{
public static DDTPrincipal GetUser(HttpContextBase httpContext)
{
if (httpContext.Request.IsAuthenticated)
{
FormsIdentity fi = httpContext.User.Identity as FormsIdentity;
if (fi != null)
{
string[] userData = fi.Ticket.UserData.Split('|');
if (userData.Length == )
{
DDTPrincipal newPrincipal = new DDTPrincipal(userData[],
userData[],userData[],
httpContext.User.Identity);
return newPrincipal;
}
return null;
}
return null;
}
return null;
}
}
}
5.应用验证属性
[CustomAuthorize]
public class CompanyManageController : Controller{}
6.配置窗体验证
<authentication mode="Forms">
<forms loginUrl="~/Account/Login" timeout="2880" />
</authentication>
asp.net mvc 自定义身份验证的更多相关文章
- asp.net mvc 自定义身份验证 2
控制成员角色 [Authorize(Rroles="Administator,SuperAdmin")] public class StoreManagerController:C ...
- ASP.NET MVC Cookie 身份验证
1 创建一个ASP.NET MVC 项目 添加一个 AccountController 类. public class AccountController : Controller { [HttpGe ...
- asp.net webapi 自定义身份验证
/// <summary> /// 验证 /// </summary> /// Account API账号 /// TimeStamp 请求时间 /// Sign 所有请求参数 ...
- ASP.NET MVC自定义验证Authorize Attribute(包含cookie helper)
前几天Insus.NET有在数据库实现过对某一字段进行加密码与解密<使用EncryptByPassPhrase和DecryptByPassPhrase对MS SQLServer某一字段时行加密和 ...
- ASP.NET WEBAPI 的身份验证和授权
定义 身份验证(Authentication):确定用户是谁. 授权(Authorization):确定用户能做什么,不能做什么. 身份验证 WebApi 假定身份验证发生在宿主程序称中.对于 web ...
- ASP.NET Web API身份验证和授权
英语原文地址:http://www.asp.net/web-api/overview/security/authentication-and-authorization-in-aspnet-web-a ...
- 使用JWT的ASP.NET CORE令牌身份验证和授权(无Cookie)——第1部分
原文:使用JWT的ASP.NET CORE令牌身份验证和授权(无Cookie)--第1部分 原文链接:https://www.codeproject.com/Articles/5160941/ASP- ...
- 采用Asp.Net的Forms身份验证时,非持久Cookie的过期时间会自动扩展
问题描述 之前没有使用Forms身份验证时,如果在登陆过程中把HttpOnly的Cookie过期时间设为半个小时,总会收到很多用户的抱怨,说登陆一会就过期了. 所以总是会把Cookie过期时间设的长一 ...
- 也谈Asp.net 中的身份验证
钱李峰 的这篇博文<Asp.net中的认证与授权>已对Asp.net 中的身份验证进行了不错实践.而我这篇博文,是从初学者的角度补充了一些基础的概念,以便能有个清晰的认识. 一.配置安全身 ...
随机推荐
- What's going on in background?
Did you know that mobile phone manufacturer collect your info without notifying you? Did you know yo ...
- lnmp下启动mysql报错 The server quit without updating PID file
启动时候错误代码:Starting MySQL[FAIL.] The server quit without updating PID file (/var/run/mysqld/mysqld.pid ...
- 移动端自动化环境搭建-stuptools和pip的安装
安装stuptools和pip A.安装依赖 setuptools 和 pip 并非必须安装的两个包,但安装之后,后续再安装 Python 的库将变得非常简单. B.安装过程
- spring 事务问题
今天碰到一个奇怪的问题,在service中执行方法,调用了两次dao,前面是save,在save后面抛错,竟然没回滚,难道不是一个事务? 后来网上查资料,发现spring的事务回滚必须是运行时异常Ru ...
- Fiddler测试WebApi的Post方法报错
标题头要加 Content-Type: application/json,Request Body中写json数组.
- ios硬件编码
video-videoToolbox: http://www.cnblogs.com/sunminmin/p/4976418.html audio-AudioToolbox: http://blog. ...
- Windows转到linux中,文件乱码,文件编码转换 & 解决sqlplus连接oracle乱码
转载:http://www.cnblogs.com/wanyao/p/3399269.html 最近,学习又重新开始Linux学习,所以一直在Centos中,昨天一朋友把他在Windows下写的C程序 ...
- VUE 入门基础(7)
八,事件处理器 监听事件 可以用v-on 指令监听DOM 事件来触发一些javaScript <div id="example-1"> <button v-on: ...
- HTML DOM 对象简单介绍
文档对象模型(Document Object Model,DOM)是DHTML的基础. 常用对象:1)window对象:表示对象浏览器窗口(选项卡)对象.2)document对象:代表整个网页,是客户 ...
- [转帖]FPGA开发工具汇总
原帖:http://blog.chinaaet.com/yocan/p/5100017074 ----------------------------------------------------- ...