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. ReactNative win10初体验

    根据RN中文网上的文档搭建环境,有的地方说的不是很清楚,所以小白的我搞了很久,终于搭建成功,这里分享一下 1. java: jdk和jre,我下载的是1.8(因为官方文档上说AndroidStudio ...

  2. 解压版mysql安装

    步骤如下: 1.下载安装包 2.在环境变量中配置安装包的bin路径 3.修改安装包下的my-default.ini. 修改basedir和datadir的值为解压文件对应的路径,port和 serve ...

  3. RabbitMQ学习: 介绍

    1. 介绍 RabbitMQ是一个由erlang开发的基于AMQP(Advanced Message Queue )协议的开源实现.用于在分布式系统中存储转发消息,在易用性.扩展性.高可用性等方面都非 ...

  4. sql2000添加表注释,列注释 及修改 删除 注释

    --创建表--create table 表(a1 varchar(10),a2 char(2)) --为表添加描述信息EXECUTE sp_addextendedproperty 'MS_Descri ...

  5. Gson运用

    输出对象或者对象的list时,我们一般都是重写toString,和遍历list,但是使用Gson输出对象或者对象的list会非常方便. Gson输出list或者对象.Gson数据没有格式化. impo ...

  6. C# 小例子

    数组冒泡排序(升序排序): , , , , , , , , , , , }; //第一种 ; i < num.Length - ; i++) { ; j < num.Length - i ...

  7. vue-cli webpack 引入jquery

    首先在package.json里的dependencies加入"jquery" : "^2.2.3",然后install 在webpack.base.conf. ...

  8. VMware 安装CentOS7.0

    最后 1 2 q yes 就这样,我的可以了

  9. Java编写最大公约数和最小公倍数

    package javaapplication24; class NegativeIntegerException extends Exception{ String message; public ...

  10. Solving “Dynamic Web Module 3.0 requires Java 1.6 or newer” in Maven Projects

    不一定是在Maven Projects里才有这种情况,但解决方法是一样的. 转自:http://qussay.com/2013/09/13/solving-dynamic-web-module-3-0 ...