前言: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开发人员参考。
转 Web用户的身份验证及WebApi权限验证流程的设计和实现的更多相关文章
-
[置顶] Web用户的身份验证及WebApi权限验证流程的设计和实现 (不是Token驗證!!!不是Token驗證!!!都是基於用户身份的票据信息驗證!!!)
转发 http://blog.csdn.net/besley/article/details/8516894 不是Token驗證!!!不是Token驗證!!!都是基於用户身份的票据信息驗證!!! [ ...
-
Web用户的身份验证及WebApi权限验证流程的设计和实现 asp.net mvc AllowAnonymous 不起作用, asp.net mvc 匿名访问
原文地址: https://blog.csdn.net/zjlovety/article/details/17095627 前言:Web 用户的身份验证,及页面操作权限验证是B/S系统的基础功能,一个 ...
-
Web用户的身份验证及WebApi权限验证流程的设计和实现
5. WebApi 服务端代码示例 5.1 控制器基类ApiControllerBase [csharp] view plaincopy /// /// Controller的基类,用于实现适合业 ...
-
Web用户的身份验证及WebApi权限验证流程的设计和实现(尾)
5. WebApi 服务端代码示例 5.1 控制器基类ApiControllerBase [csharp] view plaincopy /// /// Controller的基类,用于实现适合业 ...
-
Web用户的身份验证及WebApi权限验证流程的设计和实现(续)
4.4 权限属性RequireAuthorizationAttribute [csharp] view plaincopy "font-size:14px;">/// / ...
-
SpringAOP01 利用AOP实现权限验证、利用权限验证服务实现权限验证
1 编程范式 1.1 面向过程 1.2 面向对象 1.3 面向切面编程 1.4 函数式编程 1.5 事件驱动编程 2 什么是面向切面编程 2.1 是一种编程范式,而不是一种编程语言 2.2 解决一些特 ...
-
学习总结之 WebApi 用户登录和匿名登录,及权限验证
近些天,看了一些博客园大牛关于webApi项目的的文章,也有请教师兄一些问题,自己做了个Demo试了试,收获甚多.感谢感谢,下面是我一些学习的总结,如若有错的地方请多多指教!! WebApi登陆与身份 ...
-
简单两步快速实现shiro的配置和使用,包含登录验证、角色验证、权限验证以及shiro登录注销流程(基于spring的方式,使用maven构建)
前言: shiro因为其简单.可靠.实现方便而成为现在最常用的安全框架,那么这篇文章除了会用简洁明了的方式讲一下基于spring的shiro详细配置和登录注销功能使用之外,也会根据惯例在文章最后总结一 ...
-
[Abp 源码分析]十二、多租户体系与权限验证
0.简介 承接上篇文章我们会在这篇文章详细解说一下 Abp 是如何结合 IPermissionChecker 与 IFeatureChecker 来实现一个完整的多租户系统的权限校验的. 1.多租户的 ...
随机推荐
-
spring xmlns 记录
spring xmlns 命名空间可从: http://www.springframework.org/schema/ 根据需求选择 如: 1.选择 : aop ...
-
一些Layout的坑。坑死我自己了
iOS这个东西,初学感觉,还好还好,然后一年之后再来修复一下初学的时候的代码,我只是感觉头很晕- - 别扶我. AutoLayout的坑,明明以前都没有的!!!升了iOS10就突然发现了这个坑,其实也 ...
-
单片网络接口芯片W5100的原理与应用
随着计算机网络技术的发展,作为全球最大计算机网络——I n t e r ac t已成为当今信息社会重要的基础信息设施.在工业测控.智能仪器.智能家庭等领域,大量应用嵌入式设备接人 I n t e r ...
-
SQL Server存储过程多角度介绍
什么是存储过程: 存储过程(Procedure)类似于C#语言中的方法,它是SQL语句和控制流语句的预编译集合.存储过程存储在数据库内,可由应用程序通过一个调用执行,而且允许用户声明变量.逻辑控制语句 ...
-
什么是闭包(closure),为什么要用它?
闭包是指有权访问另一个函数作用域中变量的函数,创建闭包的最常见的方式就是在一个函数内创建另一个函数,通过另一个函数访问这个函数的局部变量,利用闭包可以突破作用链域,将函数内部的变量和方法传递到外部. ...
-
taglib
thinkphp中 taglib标签应用 原文出处:http://blog.csdn.net/a11085013/article/details/38172653 1.配置文件中加上: 'APP_AU ...
-
CodeForces Round 192 Div2
This is the first time I took part in Codeforces Competition.The only felt is that my IQ was contemp ...
-
MySQL(24):事务的隔离级别
1. 事务的隔离级别引入: 数据库是多线程并发访问的,所以很容易出现多个线程同时开启事务的情况,这样的就会出现脏读.重复读以及幻读的情况.在数据库操作中,为了有效保证并发读取数据的正确性,需要为事务设 ...
-
JVM 掌握要点
重读JVM jvm系列:jvm知识点总览 1. 认识Java虚拟机 默认Hotspot实现 2. 类加载机制 知道双亲委派模型 编译为class javac → 装载 class ClassLoade ...
-
LeetCode 867 Transpose Matrix 解题报告
题目要求 Given a matrix A, return the transpose of A. The transpose of a matrix is the matrix flipped ov ...