WebApi 登录身份验证
前言: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
- {
- //
- // GET: /Logon/
- 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))
- {
- //创建用户ticket信息
- accountModel.CreateLoginUserTicket(strUserName, strPassword);
- //读取用户权限数据
- accountModel.GetUserAuthorities(strUserName);
- return new RedirectResult(returnUrl);
- }
- else
- {
- return RedirectToAction("Index", "Home");
- }
- }
- else
- {
- throw new ApplicationException("无效登录用户!");
- }
- }
- /// <summary>
- /// 用户注销,注销之前,清除用户ticket
- /// </summary>
- /// <returns></returns>
- [HttpPost]
- public ActionResult Logout()
- {
- var accountModel = new AccountModel();
- accountModel.Logout();
- return RedirectToAction("Login", "Account");
- }
- }</span>
- <span style="font-size:18px;"> </span><span style="font-size:14px;">public class AccountController : Controller
- {
- //
- // GET: /Logon/
- 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))
- {
- //创建用户ticket信息
- accountModel.CreateLoginUserTicket(strUserName, strPassword);
- //读取用户权限数据
- accountModel.GetUserAuthorities(strUserName);
- return new RedirectResult(returnUrl);
- }
- else
- {
- return RedirectToAction("Index", "Home");
- }
- }
- else
- {
- throw new ApplicationException("无效登录用户!");
- }
- }
- /// <summary>
- /// 用户注销,注销之前,清除用户ticket
- /// </summary>
- /// <returns></returns>
- [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
- {
- /// <summary>
- /// 创建登录用户的票据信息
- /// </summary>
- /// <param name="strUserName"></param>
- internal void CreateLoginUserTicket(string strUserName, string strPassword)
- {
- //构造Form验证的票据信息
- 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);
- //把票据信息写入Cookie和Session
- //SetAuthCookie方法用于标识用户的Identity状态为true
- HttpContext.Current.Response.Cookies.Add(new HttpCookie(FormsAuthentication.FormsCookieName, ticString));
- FormsAuthentication.SetAuthCookie(strUserName, true);
- HttpContext.Current.Session["USER_LOGON_TICKET"] = ticString;
- //重写HttpContext中的用户身份,可以封装自定义角色数据;
- //判断是否合法用户,可以检查:HttpContext.User.Identity.IsAuthenticated的属性值
- string[] roles = ticket.UserData.Split(',');
- IIdentity identity = new FormsIdentity(ticket);
- IPrincipal principal = new GenericPrincipal(identity, roles);
- HttpContext.Current.User = principal;
- }
- /// <summary>
- /// 获取用户权限列表数据
- /// </summary>
- /// <param name="userName"></param>
- /// <returns></returns>
- internal string GetUserAuthorities(string userName)
- {
- //从WebApi 访问用户权限数据,然后写入Session
- 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;
- }
- /// <summary>
- /// 读取数据库用户表数据,判断用户密码是否匹配
- /// </summary>
- /// <param name="name"></param>
- /// <param name="password"></param>
- /// <returns></returns>
- internal bool ValidateUserLogin(string name, string password)
- {
- //bool isValid = password == passwordInDatabase;
- return true;
- }
- /// <summary>
- /// 用户注销执行的操作
- /// </summary>
- internal void Logout()
- {
- FormsAuthentication.SignOut();
- }
- }</span>
- <span style="font-size:14px;">public class AccountModel
- {
- /// <summary>
- /// 创建登录用户的票据信息
- /// </summary>
- /// <param name="strUserName"></param>
- internal void CreateLoginUserTicket(string strUserName, string strPassword)
- {
- //构造Form验证的票据信息
- 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);
- //把票据信息写入Cookie和Session
- //SetAuthCookie方法用于标识用户的Identity状态为true
- HttpContext.Current.Response.Cookies.Add(new HttpCookie(FormsAuthentication.FormsCookieName, ticString));
- FormsAuthentication.SetAuthCookie(strUserName, true);
- HttpContext.Current.Session["USER_LOGON_TICKET"] = ticString;
- //重写HttpContext中的用户身份,可以封装自定义角色数据;
- //判断是否合法用户,可以检查:HttpContext.User.Identity.IsAuthenticated的属性值
- string[] roles = ticket.UserData.Split(',');
- IIdentity identity = new FormsIdentity(ticket);
- IPrincipal principal = new GenericPrincipal(identity, roles);
- HttpContext.Current.User = principal;
- }
- /// <summary>
- /// 获取用户权限列表数据
- /// </summary>
- /// <param name="userName"></param>
- /// <returns></returns>
- internal string GetUserAuthorities(string userName)
- {
- //从WebApi 访问用户权限数据,然后写入Session
- 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;
- }
- /// <summary>
- /// 读取数据库用户表数据,判断用户密码是否匹配
- /// </summary>
- /// <param name="name"></param>
- /// <param name="password"></param>
- /// <returns></returns>
- internal bool ValidateUserLogin(string name, string password)
- {
- //bool isValid = password == passwordInDatabase;
- return true;
- }
- /// <summary>
- /// 用户注销执行的操作
- /// </summary>
- internal void Logout()
- {
- FormsAuthentication.SignOut();
- }
- }</span>
4.3 控制器基类WebControllerBase
- <span style="font-size: 14px;">/// <summary>
- /// 前端Mvc控制器基类
- /// </summary>
- [Authorize]
- public abstract class WebControllerBase : Controller
- {
- /// <summary>
- /// 对应api的Url
- /// </summary>
- public string ApiUrl
- {
- get;
- protected set;
- }
- /// <summary>
- /// 用户权限列表
- /// </summary>
- public UserAuthModel[] UserAuthList
- {
- get
- {
- return AuthorizedUser.Current.UserAuthList;
- }
- }
- /// <summary>
- /// 登录用户票据
- /// </summary>
- public string UserLoginTicket
- {
- get
- {
- return AuthorizedUser.Current.UserLoginTicket;
- }
- }
- }</span>
- <span style="font-size:14px;">/// <summary>
- /// 前端Mvc控制器基类
- /// </summary>
- [Authorize]
- public abstract class WebControllerBase : Controller
- {
- /// <summary>
- /// 对应api的Url
- /// </summary>
- public string ApiUrl
- {
- get;
- protected set;
- }
- /// <summary>
- /// 用户权限列表
- /// </summary>
- public UserAuthModel[] UserAuthList
- {
- get
- {
- return AuthorizedUser.Current.UserAuthList;
- }
- }
- /// <summary>
- /// 登录用户票据
- /// </summary>
- public string UserLoginTicket
- {
- get
- {
- return AuthorizedUser.Current.UserLoginTicket;
- }
- }
- }</span>
4.4 权限属性RequireAuthorizationAttribute
- <span style="font-size: 14px;">/// <summary>
- /// 权限验证属性类
- /// </summary>
- public class RequireAuthorizeAttribute : AuthorizeAttribute
- {
- /// <summary>
- /// 用户权限列表
- /// </summary>
- public UserAuthModel[] UserAuthList
- {
- get
- {
- return AuthorizedUser.Current.UserAuthList;
- }
- }
- /// <summary>
- /// 登录用户票据
- /// </summary>
- 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))
- //有效登录用户,有权限访问此Action,则写入Cookie信息
- filterContext.HttpContext.Response.Cookies[FormsAuthentication.FormsCookieName].Value = UserLoginTicket;
- else
- //用户的Session, Cookie都过期,需要重新登录
- filterContext.HttpContext.Response.Redirect("~/Account/Login", false);
- else
- //虽然是登录用户,但没有该Action的权限,跳转到“未授权访问”页面
- 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);
- }
- }
- /// <summary>
- /// 从权限列表验证用户是否有权访问Action
- /// </summary>
- /// <param name="actionName"></param>
- /// <param name="controllerName"></param>
- /// <returns></returns>
- private bool HasActionQulification(string actionName, string controllerName, string userName)
- {
- //从该用户的权限数据列表中查找是否有当前Controller和Action的item
- 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;
- });
- //此处可以校验用户的其它权限条件
- //var notAllowed = HasOtherLimition(userName);
- //var result = (auth != null) && notAllowed;
- //return result;
- return (auth != null);
- }
- }</span>
- <span style="font-size:14px;">/// <summary>
- /// 权限验证属性类
- /// </summary>
- public class RequireAuthorizeAttribute : AuthorizeAttribute
- {
- /// <summary>
- /// 用户权限列表
- /// </summary>
- public UserAuthModel[] UserAuthList
- {
- get
- {
- return AuthorizedUser.Current.UserAuthList;
- }
- }
- /// <summary>
- /// 登录用户票据
- /// </summary>
- 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))
- //有效登录用户,有权限访问此Action,则写入Cookie信息
- filterContext.HttpContext.Response.Cookies[FormsAuthentication.FormsCookieName].Value = UserLoginTicket;
- else
- //用户的Session, Cookie都过期,需要重新登录
- filterContext.HttpContext.Response.Redirect("~/Account/Login", false);
- else
- //虽然是登录用户,但没有该Action的权限,跳转到“未授权访问”页面
- 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);
- }
- }
- /// <summary>
- /// 从权限列表验证用户是否有权访问Action
- /// </summary>
- /// <param name="actionName"></param>
- /// <param name="controllerName"></param>
- /// <returns></returns>
- private bool HasActionQulification(string actionName, string controllerName, string userName)
- {
- //从该用户的权限数据列表中查找是否有当前Controller和Action的item
- 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;
- });
- //此处可以校验用户的其它权限条件
- //var notAllowed = HasOtherLimition(userName);
- //var result = (auth != null) && notAllowed;
- //return result;
- return (auth != null);
- }
- }</span>
4.5 业务Controller示例
- <span style="font-size: 14px;">
- public class ProductController : WebControllerBase
- {
- [AllowAnonymous]
- public ActionResult Query()
- {
- return View("ProductQuery");
- }
- [HttpGet]
- //[AllowAnonymous]
- [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>
- <span style="font-size:14px;">public class ProductController : WebControllerBase
- {
- [AllowAnonymous]
- public ActionResult Query()
- {
- return View("ProductQuery");
- }
- [HttpGet]
- //[AllowAnonymous]
- [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
- /// <summary>
- /// Controller的基类,用于实现适合业务场景的基础功能
- /// </summary>
- /// <typeparam name="T"></typeparam>
- [BasicAuthentication]
- public abstract class ApiControllerBase : ApiController
- {
- }
- /// <summary>
- /// Controller的基类,用于实现适合业务场景的基础功能
- /// </summary>
- /// <typeparam name="T"></typeparam>
- [BasicAuthentication]
- public abstract class ApiControllerBase : ApiController
- {
- }
5.2 权限属性BaseAuthenticationAttribute
- /// <summary>
- /// 基本验证Attribtue,用以Action的权限处理
- /// </summary>
- public class BasicAuthenticationAttribute : ActionFilterAttribute
- {
- /// <summary>
- /// 检查用户是否有该Action执行的操作权限
- /// </summary>
- /// <param name="actionContext"></param>
- public override void OnActionExecuting(HttpActionContext actionContext)
- {
- //检验用户ticket信息,用户ticket信息来自调用发起方
- if (actionContext.Request.Headers.Authorization != null)
- {
- //解密用户ticket,并校验用户名密码是否匹配
- var encryptTicket = actionContext.Request.Headers.Authorization.Parameter;
- if (ValidateUserTicket(encryptTicket))
- base.OnActionExecuting(actionContext);
- else
- actionContext.Response = new HttpResponseMessage(HttpStatusCode.Unauthorized);
- }
- else
- {
- //检查web.config配置是否要求权限校验
- bool isRquired = (WebConfigurationManager.AppSettings["WebApiAuthenticatedFlag"].ToString() == "true");
- if (isRquired)
- {
- //如果请求Header不包含ticket,则判断是否是匿名调用
- 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);
- }
- }
- }
- /// <summary>
- /// 校验用户ticket信息
- /// </summary>
- /// <param name="encryptTicket"></param>
- /// <returns></returns>
- 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);
- //检查用户名、密码是否正确,验证是合法用户
- //var isQuilified = CheckUser(userName, password);
- return true;
- }
- }
- /// <summary>
- /// 基本验证Attribtue,用以Action的权限处理
- /// </summary>
- public class BasicAuthenticationAttribute : ActionFilterAttribute
- {
- /// <summary>
- /// 检查用户是否有该Action执行的操作权限
- /// </summary>
- /// <param name="actionContext"></param>
- public override void OnActionExecuting(HttpActionContext actionContext)
- {
- //检验用户ticket信息,用户ticket信息来自调用发起方
- if (actionContext.Request.Headers.Authorization != null)
- {
- //解密用户ticket,并校验用户名密码是否匹配
- var encryptTicket = actionContext.Request.Headers.Authorization.Parameter;
- if (ValidateUserTicket(encryptTicket))
- base.OnActionExecuting(actionContext);
- else
- actionContext.Response = new HttpResponseMessage(HttpStatusCode.Unauthorized);
- }
- else
- {
- //检查web.config配置是否要求权限校验
- bool isRquired = (WebConfigurationManager.AppSettings["WebApiAuthenticatedFlag"].ToString() == "true");
- if (isRquired)
- {
- //如果请求Header不包含ticket,则判断是否是匿名调用
- 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);
- }
- }
- }
- /// <summary>
- /// 校验用户ticket信息
- /// </summary>
- /// <param name="encryptTicket"></param>
- /// <returns></returns>
- 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);
- //检查用户名、密码是否正确,验证是合法用户
- //var isQuilified = CheckUser(userName, password);
- return true;
- }
- }
5.3 api服务Controller实例
- public class ProductController : ApiControllerBase
- {
- [HttpGet]
- public object Find(string id)
- {
- return ProductServiceInstance.Find(2);
- }
- // GET api/product/5
- [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;
- }
- }
- public class ProductController : ApiControllerBase
- {
- [HttpGet]
- public object Find(string id)
- {
- return ProductServiceInstance.Find(2);
- }
- // GET api/product/5
- [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>
- <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>
- <system.web>
- <machineKey validationKey="3FF112388DDF585BA5D35E7BC87E3F0AB47FBBEBD12240DD3BEA2BEAEC4ABA213F22AD27E8FAD77DCFEE306219691434908D193A17C1FC8DCE51B71A4AE54920" decryptionKey="ECB6A3AF9ABBF3F16E80685ED68DC74B0B13CCEE538EBBA97D0B893139683B3B" validation="SHA1" decryption="AES" />
- </system.web>
machineKey节点配置,是应用于对用户ticket数据加密和解密。
7. 总结
Web系统的用户登录及页面操作权限验证在处理逻辑上比较复杂,需要考虑到Form认证、匿名访问,Session和Cookie存储,以及Session和Cookie的过期处理,本文实现了整个权限验证框架的基本功能,供系统架构设计人员以及Web开发人员参考。
Demo项目代码地址:点击打开链接