标签:pil ipa 创建用户 存储 edit rda any 脚本 query
前言:Web 用户的身份验证,及页面操作权限验证是B/S系统的基础功能,一个功能复杂的业务应用系统,通过角色授权来控制用户访问,本文通过Form认证,Mvc的Controller基类及Action的权限验证来实现Web系统登录,Mvc前端权限校验以及WebApi服务端的访问校验功能。
1. Web Form认证介绍
Web应用的访问方式因为是基于浏览器的Http地址请求,所以需要验证用户身份的合法性。目前常见的方式是Form认证,其处理逻辑描述如下:
1. 用户首先要在登录页面输入用户名和密码,然后登录系统,获取合法身份的票据,再执行后续业务处理操作;
2. 用户在没有登录的情况下提交Http页面访问请求,如果该页面不允许匿名访问,则直接跳转到登录页面;
3. 对于允许匿名访问的页面请求,系统不做权限验证,直接处理业务数据,并返回给前端;
4. 对于不同权限要求的页面Action操作,系统需要校验用户角色,计算权限列表,如果请求操作在权限列表中,则正常访问,如果不在权限列表中,则提示“未授权的访问操作”到异常处理页面。
2. WebApi 服务端Basic 方式验证
WebApi服务端接收访问请求,需要做安全验证处理,验证处理步骤如下:
1. 如果是合法的Http请求,在Http请求头中会有用户身份的票据信息,服务端会读取票据信息,并校验票据信息是否完整有效,如果满足校验要求,则进行业务数据的处理,并返回给请求发起方;
2. 如果没有票据信息,或者票据信息不是合法的,则返回“未授权的访问”异常消息给前端,由前端处理此异常。
3. 登录及权限验证流程
流程处理步骤说明:
1. 用户打开浏览器,并在地址栏中输入页面请求地址,提交;
2. 浏览器解析Http请求,发送到Web服务器;Web服务器验证用户请求,首先判断是否有登录的票据信息;
3. 用户没有登录票据信息,则跳转到登录页面;
4. 用户输入用户名和密码信息;
5. 浏览器提交登录表单数据给Web服务器;
6. Web服务需要验证用户名和密码是否匹配,发送api请求给api服务器;
7. api用户账户服务根据用户名,读取存储在数据库中的用户资料,判断密码是否匹配;
1)如果用户名和密码不匹配,则提示密码错误等信息,然该用户重新填写登录资料;
2)如果验证通过,则保存用户票据信息;
8. 接第3步,如果用户有登录票据信息,则跳转到用户请求的页面;
9. 验证用户对当前要操作的页面或页面元素是否有权限操作,首先需要发起api服务请求,获取用户的权限数据;
10. api用户权限服务根据用户名,查找该用户的角色信息,并计算用户权限列表,封装为Json数据并返回;
11. 当用户有权限操作页面或页面元素时,跳转到页面,并由页面Controller提交业务数据处理请求到api服务器;
如果用户没有权限访问该页面或页面元素时,则显示“未授权的访问操作”,跳转到系统异常处理页面。
12. api业务服务处理业务逻辑,并将结果以Json 数据返回;
13. 返回渲染后的页面给浏览器前端,并呈现业务数据到页面;
14. 用户填写业务数据,或者查找业务数据;
15. 当填写或查找完业务数据后,用户提交表单数据;
16. 浏览器脚本提交get,post等请求给web服务器,由web服务器再次解析请求操作,重复步骤2的后续流程;
17. 当api服务器验证用户身份是,没有可信用户票据,系统提示“未授权的访问操作”,跳转到系统异常处理页面。
4. Mvc前端代码示例
4.1 用户登录AccountController
- <span style="font-size: 18px;"> </span><span style="font-size:14px;">public class AccountController : Controller
- {
-
-
-
- public ActionResult Login(string returnUrl)
- {
- ViewBag.ReturnUrl = returnUrl;
- return View();
- }
-
- [HttpPost]
- public ActionResult Logon(LoginUser loginUser, string returnUrl)
- {
- string strUserName = loginUser.UserName;
- string strPassword = loginUser.Password;
- var accountModel = new AccountModel();
-
-
- if (accountModel.ValidateUserLogin(strUserName, strPassword))
- {
- if (Url.IsLocalUrl(returnUrl))
- {
-
- accountModel.CreateLoginUserTicket(strUserName, strPassword);
-
-
- accountModel.GetUserAuthorities(strUserName);
-
- return new RedirectResult(returnUrl);
- }
- else
- {
- return RedirectToAction("Index", "Home");
- }
- }
- else
- {
- throw new ApplicationException("无效登录用户!");
- }
- }
-
-
-
-
-
- [HttpPost]
- public ActionResult Logout()
- {
- var accountModel = new AccountModel();
- accountModel.Logout();
-
- return RedirectToAction("Login", "Account");
- }
- }</span>
4.2 用户模型AccountModel
- <span style="font-size:14px;">public class AccountModel
- {
-
-
-
-
- internal void CreateLoginUserTicket(string strUserName, string strPassword)
- {
-
- FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, strUserName, DateTime.Now, DateTime.Now.AddMinutes(90),
- true, string.Format("{0}:{1}", strUserName, strPassword), FormsAuthentication.FormsCookiePath);
-
- string ticString = FormsAuthentication.Encrypt(ticket);
-
-
-
- HttpContext.Current.Response.Cookies.Add(new HttpCookie(FormsAuthentication.FormsCookieName, ticString));
- FormsAuthentication.SetAuthCookie(strUserName, true);
- HttpContext.Current.Session["USER_LOGON_TICKET"] = ticString;
-
-
-
- string[] roles = ticket.UserData.Split(‘,‘);
- IIdentity identity = new FormsIdentity(ticket);
- IPrincipal principal = new GenericPrincipal(identity, roles);
- HttpContext.Current.User = principal;
- }
-
-
-
-
-
-
- internal string GetUserAuthorities(string userName)
- {
-
- string jsonAuth = "[{\"Controller\": \"SampleController\", \"Actions\":\"Apply,Process,Complete\"}, {\"Controller\": \"Product\", \"Actions\": \"List,Get,Detail\"}]";
- var userAuthList = ServiceStack.Text.JsonSerializer.DeserializeFromString(jsonAuth, typeof(UserAuthModel[]));
- HttpContext.Current.Session["USER_AUTHORITIES"] = userAuthList;
-
- return jsonAuth;
- }
-
-
-
-
-
-
-
- internal bool ValidateUserLogin(string name, string password)
- {
-
- return true;
- }
-
-
-
-
- internal void Logout()
- {
- FormsAuthentication.SignOut();
- }
- }</span>
4.3 控制器基类WebControllerBase
- <span style="font-size:14px;">
-
-
- [Authorize]
- public abstract class WebControllerBase : Controller
- {
-
-
-
- public string ApiUrl
- {
- get;
- protected set;
- }
-
-
-
-
- public UserAuthModel[] UserAuthList
- {
- get
- {
- return AuthorizedUser.Current.UserAuthList;
- }
- }
-
-
-
-
- public string UserLoginTicket
- {
- get
- {
- return AuthorizedUser.Current.UserLoginTicket;
- }
- }
- }</span>
4.4 权限属性RequireAuthorizationAttribute
- <span style="font-size:14px;">
-
-
- public class RequireAuthorizeAttribute : AuthorizeAttribute
- {
-
-
-
- public UserAuthModel[] UserAuthList
- {
- get
- {
- return AuthorizedUser.Current.UserAuthList;
- }
- }
-
-
-
-
- public string UserLoginTicket
- {
- get
- {
- return AuthorizedUser.Current.UserLoginTicket;
- }
- }
-
- public override void OnAuthorization(AuthorizationContext filterContext)
- {
- base.OnAuthorization(filterContext);
-
-
- var identity = filterContext.HttpContext.User.Identity;
- if (identity.IsAuthenticated)
- {
- var actionName = filterContext.ActionDescriptor.ActionName;
- var controllerName = filterContext.ActionDescriptor.ControllerDescriptor.ControllerName;
-
-
- if (HasActionQulification(actionName, controllerName, identity.Name))
- if (!string.IsNullOrEmpty(UserLoginTicket))
-
- filterContext.HttpContext.Response.Cookies[FormsAuthentication.FormsCookieName].Value = UserLoginTicket;
- else
-
- filterContext.HttpContext.Response.Redirect("~/Account/Login", false);
- else
-
- filterContext.HttpContext.Response.Redirect("~/Home/UnAuthorized", true);
- }
- else
- {
-
- var attr = filterContext.ActionDescriptor.GetCustomAttributes(true).OfType<AllowAnonymousAttribute>();
- bool isAnonymous = attr.Any(a => a is AllowAnonymousAttribute);
-
- if (!isAnonymous)
-
- filterContext.HttpContext.Response.Redirect("~/Account/Login", true);
- }
- }
-
-
-
-
-
-
-
- private bool HasActionQulification(string actionName, string controllerName, string userName)
- {
-
- var auth = UserAuthList.FirstOrDefault(a =>
- {
- bool rightAction = false;
- bool rightController = a.Controller == controllerName;
- if (rightController)
- {
- string[] actions = a.Actions.Split(‘,‘);
- rightAction = actions.Contains(actionName);
- }
- return rightAction;
- });
-
-
-
-
-
-
- return (auth != null);
- }
- }</span>
4.5 业务Controller示例
- <span style="font-size:14px;">public class ProductController : WebControllerBase
- {
-
- [AllowAnonymous]
- public ActionResult Query()
- {
- return View("ProductQuery");
- }
-
- [HttpGet]
-
- [RequireAuthorize]
- public ActionResult Detail(string id)
- {
- var cookie = HttpContext.Request.Cookies;
- string url = base.ApiUrl + "/Get/" + id;
- HttpClient httpClient = HttpClientHelper.Create(url, base.UserLoginTicket);
-
- string result = httpClient.GetString();
- var model = JsonSerializer.DeserializeFromString<Product>(result);
- ViewData["PRODUCT_ADD_OR_EDIT"] = "E";
- return View("ProductForm", model);
- }
- }</span>
5. WebApi 服务端代码示例
5.1 控制器基类ApiControllerBase
- [BasicAuthentication]
- public abstract class ApiControllerBase : ApiController
- {
-
- }
5.2 权限属性BaseAuthenticationAttribute
-
-
- public class BasicAuthenticationAttribute : ActionFilterAttribute
- {
-
-
-
-
- public override void OnActionExecuting(HttpActionContext actionContext)
- {
-
- if (actionContext.Request.Headers.Authorization != null)
- {
-
- var encryptTicket = actionContext.Request.Headers.Authorization.Parameter;
- if (ValidateUserTicket(encryptTicket))
- base.OnActionExecuting(actionContext);
- else
- actionContext.Response = new HttpResponseMessage(HttpStatusCode.Unauthorized);
- }
- else
- {
-
- bool isRquired = (WebConfigurationManager.AppSettings["WebApiAuthenticatedFlag"].ToString() == "true");
- if (isRquired)
- {
-
- var attr = actionContext.ActionDescriptor.GetCustomAttributes<AllowAnonymousAttribute>().OfType<AllowAnonymousAttribute>();
- bool isAnonymous = attr.Any(a => a is AllowAnonymousAttribute);
-
-
- if (isAnonymous)
- base.OnActionExecuting(actionContext);
- else
- actionContext.Response = new HttpResponseMessage(HttpStatusCode.Unauthorized);
- }
- else
- {
- base.OnActionExecuting(actionContext);
- }
- }
- }
-
-
-
-
-
-
- private bool ValidateUserTicket(string encryptTicket)
- {
- var userTicket = FormsAuthentication.Decrypt(encryptTicket);
- var userTicketData = userTicket.UserData;
-
- string userName = userTicketData.Substring(0, userTicketData.IndexOf(":"));
- string password = userTicketData.Substring(userTicketData.IndexOf(":") + 1);
-
-
-
- return true;
- }
- }
5.3 api服务Controller实例
- public class ProductController : ApiControllerBase
- {
-
- [HttpGet]
- public object Find(string id)
- {
- return ProductServiceInstance.Find(2);
- }
-
-
- [HttpGet]
- [AllowAnonymous]
- public Product Get(string id)
- {
- var headers = Request.Headers;
- var p = ProductServiceInstance.GetById<Product, EPProduct>(long.Parse(id));
- if (p == null)
- {
- throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.BadRequest)
- Content = new StringContent("id3 not found"), ReasonPhrase = "product id not exist." });
- }
- return p;
- }
- }
6. 其它配置说明
6.1 Mvc前端Web.Config 配置
- <system.web>
- <compilation debug="true" targetFramework="4.5">
- <assemblies>
- <add assembly="System.Web.Http.Data.Helpers, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
- </assemblies>
- </compilation>
- <httpRuntime targetFramework="4.5" />
- <authentication mode="Forms">
- <forms loginUrl="~/Account/Login" defaultUrl="~/Home/Index" protection="All" timeout="90" name=".AuthCookie"></forms>
- </authentication>
- <machineKey validationKey="3FFA12388DDF585BA5D35E7BC87E3F0AB47FBBEBD12240DD3BEA2BEAEC4ABA213F22AD27E8FAD77DCFEE306219691434908D193A17C1FC8DCE51B71A4AE54920" decryptionKey="ECB6A3AF9ABBF3F16E80685ED68DC74B0B13CCEE538EBBA97D0B893139683B3B" validation="SHA1" decryption="AES" />
- </system.web>
machineKey节点配置,是应用于对用户ticket数据加密和解密。
6.2 WebApi服务端Web.Config配置
- <system.web>
- <machineKey validationKey="3FF112388DDF585BA5D35E7BC87E3F0AB47FBBEBD12240DD3BEA2BEAEC4ABA213F22AD27E8FAD77DCFEE306219691434908D193A17C1FC8DCE51B71A4AE54920" decryptionKey="ECB6A3AF9ABBF3F16E80685ED68DC74B0B13CCEE538EBBA97D0B893139683B3B" validation="SHA1" decryption="AES" />
- </system.web>
machineKey节点配置,是应用于对用户ticket数据加密和解密。
7. 总结
Web系统的用户登录及页面操作权限验证在处理逻辑上比较复杂,需要考虑到Form认证、匿名访问,Session和Cookie存储,以及Session和Cookie的过期处理,本文实现了整个权限验证框架的基本功能,供系统架构设计人员以及Web开发人员参考。
Demo项目代码地址:
https://github.com/besley/DemoUserAuthorization/
8. 春风吹又起--后记
由于项目的需要,彻底打造了登录及权限验证的一个新开源项目SlickSafe.NET,欢迎大家挪步。
GitHub:
http://github.com/besley/slicksafe
博客文章
http://www.cnblogs.com/slickflow/p/6478887.html
在线DEMO地址:
http://demo.slickflow.com//ssweb/
(用户名密码:admin/123456, jack/123456)
Web用户的身份验证及WebApi权限验证流程的设计和实现
标签:pil ipa 创建用户 存储 edit rda any 脚本 query
原文地址:http://www.cnblogs.com/webenh/p/7499802.html