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 自定义身份验证的更多相关文章

  1. asp.net mvc 自定义身份验证 2

    控制成员角色 [Authorize(Rroles="Administator,SuperAdmin")] public class StoreManagerController:C ...

  2. ASP.NET MVC Cookie 身份验证

    1 创建一个ASP.NET MVC 项目 添加一个 AccountController 类. public class AccountController : Controller { [HttpGe ...

  3. asp.net webapi 自定义身份验证

    /// <summary> /// 验证 /// </summary> /// Account API账号 /// TimeStamp 请求时间 /// Sign 所有请求参数 ...

  4. ASP.NET MVC自定义验证Authorize Attribute(包含cookie helper)

    前几天Insus.NET有在数据库实现过对某一字段进行加密码与解密<使用EncryptByPassPhrase和DecryptByPassPhrase对MS SQLServer某一字段时行加密和 ...

  5. ASP.NET WEBAPI 的身份验证和授权

    定义 身份验证(Authentication):确定用户是谁. 授权(Authorization):确定用户能做什么,不能做什么. 身份验证 WebApi 假定身份验证发生在宿主程序称中.对于 web ...

  6. ASP.NET Web API身份验证和授权

    英语原文地址:http://www.asp.net/web-api/overview/security/authentication-and-authorization-in-aspnet-web-a ...

  7. 使用JWT的ASP.NET CORE令牌身份验证和授权(无Cookie)——第1部分

    原文:使用JWT的ASP.NET CORE令牌身份验证和授权(无Cookie)--第1部分 原文链接:https://www.codeproject.com/Articles/5160941/ASP- ...

  8. 采用Asp.Net的Forms身份验证时,非持久Cookie的过期时间会自动扩展

    问题描述 之前没有使用Forms身份验证时,如果在登陆过程中把HttpOnly的Cookie过期时间设为半个小时,总会收到很多用户的抱怨,说登陆一会就过期了. 所以总是会把Cookie过期时间设的长一 ...

  9. 也谈Asp.net 中的身份验证

    钱李峰 的这篇博文<Asp.net中的认证与授权>已对Asp.net 中的身份验证进行了不错实践.而我这篇博文,是从初学者的角度补充了一些基础的概念,以便能有个清晰的认识. 一.配置安全身 ...

随机推荐

  1. Linux压缩打包命令

    tar命令 [root@linux ~]# tar [-cxtzjvfpPN] 文件与目录 .... 参数 -c :建立一个压缩文件的参数指令(create 的意思): -x :解开一个压缩文件的参数 ...

  2. MS - 2 - 设计包含 min 函数的栈

    定义栈的数据结构,要求添加一个 min 函数,能够得到栈的最小元素. 要求函数 min.push 以及 pop 的时间复杂度都是 O(1). template<typename T> st ...

  3. HTTP 错误500.19 -Internal Server Error 错误代码 0x80070021

    转自:http://blog.csdn.net/goux_s/article/details/5676689 错误摘要 HTTP 错误500.19 -Internal Server Error 无法访 ...

  4. 学习一下mef

    微软 http://msdn.microsoft.com/zh-cn/magazine/ee291628.aspx mef http://biancheng.dnbcw.info/net/370552 ...

  5. 解决linux yum无法安装mysql

    yum源中默认好像是没有mysql的.为了解决这个问题,我们要先下载mysql的repo源. 1. 下载mysql的repo源 wget http://repo.mysql.com/mysql-com ...

  6. 游戏笔记之《Fez》

    FEZ 游戏名称:菲斯 英文名称:Fez 游戏类型:ACT(动作游戏),AVG(冒险游戏) 游戏制作:Polytron Corporation 游戏发行:Trapdoor 游戏平台:PC 游戏画面: ...

  7. 如何设置Java开发环境

    傻瓜式 设置Java开发环境 跟我来. 对与win7操作系统.有两种方法. 第一种: 1.下载JDK,完成安装. 2.右键我的电脑,选择属性,在左边找到高级系统设置左键单击打开,在高级选项中找到 环境 ...

  8. 原生js操作dom备忘

    <!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="utf-8& ...

  9. webdriver对象定位方法

    webdriver提供了一系列的对象定位方法,常用的有以下几种 · id · name · class name · link text · partial link text · tag name ...

  10. [delphi]极域学生端解除键盘鼠标锁定退出全屏广播-强制窗口化-源代码

    v2.0  2015-07-11 更新了V2.0 版本 发布在吾爱破解论坛 欢迎下载使用 http://www.52pojie.cn/thread-382769-1-1.html ---------- ...