asp.net mvc 自定义身份验证

1.定义身份实体对象

 1     /// <summary>
 2     /// 网站用户实体对象
 3     /// </summary>
 4     public class DDTPrincipal : IPrincipal
 5     {
 6         public int? OrgCode { get; set; }
 7         public string RoleName { get; set; }
 8         public string OrgName { get; set; }
 9         private IIdentity _identity;
10 
11         public DDTPrincipal(string orgcode, string roleName, string orgName, IIdentity identity)
12         {
13             int _orgCode;
14             int.TryParse(orgcode, out _orgCode);
15             OrgCode =  _orgCode;
16             OrgName = orgName;
17             RoleName = roleName;
18             _identity = identity;
19         }
20 
21         public IIdentity Identity
22         {
23             get { return _identity; }
24         }
25 
26         public bool IsInRole(string role)
27         {
28             return RoleName.IndexOf(role)>=0;
29         }
30     }
View Code

2.验证身份

 1         [HttpPost]
 2         [AllowAnonymous]
 3         [ValidateAntiForgeryToken]
 4         public ActionResult LoginView(LoginModel model, string returnUrl)
 5         {
 6             
 7             if (ModelState.IsValid)
 8             {
 9                 Account a = DataRepository.AccountProvider.GetByAccountName(model.UserName);
10                 DataRepository.AccountProvider.DeepLoad(a,false, DeepLoadType.IncludeChildren,typeof(Org));
11                 TList<AccountRole> arList = DataRepository.AccountRoleProvider.GetByAccountName(a.AccountName);
12                 DataRepository.AccountRoleProvider.DeepLoad(arList, false, DeepLoadType.IncludeChildren, typeof(Role));
13                 
14                 string roleName=string.Empty;
15                 if (arList.Count > 0)
16                 {
17                     foreach (var item in arList)
18                     {
19                         roleName += item.RoleNoSource.RoleName + ",";
20                     }
21                 }
22                 else { roleName = ""; }
23 
24                 if (a!=null&&a.AccountPassword==model.Password)
25                 {
26                    // return RedirectToLocal(returnUrl);
27                     FormsAuthentication.RedirectFromLoginPage(a.UserName, false);
28                     FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, a.UserName, DateTime.Now,
29                         DateTime.Now.AddMinutes(120), false,
30                         string.Format("{0}|{1}|{2}", a.OrgCode.Value.ToString(),roleName,a.OrgCodeSource.OrgName));
31                     string encryptedTicket = FormsAuthentication.Encrypt(ticket);
32                     HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);
33                     Response.Cookies.Add(cookie);
34                     return Redirect(returnUrl);
35                 }
36             }
37             // 如果我们进行到这一步时某个地方出错,则重新显示表单
38             ModelState.AddModelError("", "提供的用户名或密码不正确。");
39             return View(model);
40 
41 
42             //if (ModelState.IsValid && WebSecurity.Login(model.UserName, model.Password, persistCookie: model.RememberMe))
43             //{
44             //    return RedirectToLocal(returnUrl);
45             //}
46             //// 如果我们进行到这一步时某个地方出错,则重新显示表单
47             //ModelState.AddModelError("", "提供的用户名或密码不正确。");
48             //return View(model);
49         }
View Code

3.自定义验证属性获取验证信息

1     public class CustomAuthorizeAttribute:AuthorizeAttribute
2     {
3         protected override bool AuthorizeCore(HttpContextBase httpContext)
4         {
5             httpContext.User = App_Codes.WebUtility.GetUser(httpContext);
6             return base.AuthorizeCore(httpContext);
7         }
8     }
View Code

4.从验证信息生成验证对象

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Web;
 5 using System.Web.Security;
 6 using System.Security.Principal;
 7 
 8 namespace XXX.App_Codes
 9 {
10     public static class WebUtility
11     {
12         public static DDTPrincipal GetUser(HttpContextBase httpContext)
13         {
14             if (httpContext.Request.IsAuthenticated)
15             {
16                 FormsIdentity fi = httpContext.User.Identity as FormsIdentity;
17                 if (fi != null)
18                 {
19                     string[] userData = fi.Ticket.UserData.Split('|');
20                     if (userData.Length == 3)
21                     {
22                         DDTPrincipal newPrincipal = new DDTPrincipal(userData[0],
23                             userData[1],userData[2],
24                             httpContext.User.Identity);
25                         return newPrincipal;
26                     }
27                     return null;
28                 }
29                 return null;
30             }
31             return null;
32         }
33     }
34 }
View Code

5.应用验证属性

1     [CustomAuthorize]
2     public class CompanyManageController : Controller{}
View Code

6.配置窗体验证

<authentication mode="Forms">
<forms loginUrl="~/Account/Login" timeout="2880" />
</authentication>

原文地址:https://www.cnblogs.com/lgxtry/p/4333995.html