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 Cookie 身份验证


下一篇:MySQL 常用命令大全