Web用户的身份验证及WebApi权限验证流程的设计和实现

5. WebApi 服务端代码示例

5.1 控制器基类ApiControllerBase

[csharp] view plaincopy
 
  1. ///
  2. /// Controller的基类,用于实现适合业务场景的基础功能
  3. ///
  4. ///
  5. [BasicAuthentication]
  6. public abstract class ApiControllerBase : ApiController
  7. {
  8. }

5.2
权限属性BaseAuthenticationAttribute

[csharp] view
plain
copy
 
  1. ///
  2. /// 基本验证Attribtue,用以Action的权限处理
  3. ///
  4. public class
    BasicAuthenticationAttribute :
    ActionFilterAttribute
  5. {
  6. ///
  7. /// 检查用户是否有该Action执行的操作权限
  8. ///
  9. ///
  10. public override void
    OnActionExecuting(HttpActionContext
    actionContext)
  11. {
  12. //检验用户ticket信息,用户ticket信息来自调用发起方
  13. if
    (actionContext.Request.Headers.Authorization != null)
  14. {
  15. //解密用户ticket,并校验用户名密码是否匹配
  16. var encryptTicket =
    actionContext.Request.Headers.Authorization.Parameter;
  17. if
    (ValidateUserTicket(encryptTicket))
  18. base.OnActionExecuting(actionContext);
  19. else
  20. actionContext.Response = new
    HttpResponseMessage(HttpStatusCode.Unauthorized);
  21. }
  22. else
  23. {
  24. //检查web.config配置是否要求权限校验
  25. bool
    isRquired =
    (WebConfigurationManager.AppSettings["WebApiAuthenticatedFlag"].ToString()
    == "true");
  26. if
    (isRquired)
  27. {
  28. //如果请求Header不包含ticket,则判断是否是匿名调用
  29. var attr =
    actionContext.ActionDescriptor.GetCustomAttributes().OfType();
  30. bool
    isAnonymous = attr.Any(a => a is
    AllowAnonymousAttribute);
  31. //是匿名用户,则继续执行;非匿名用户,抛出“未授权访问”信息
  32. if
    (isAnonymous)
  33. base.OnActionExecuting(actionContext);
  34. else
  35. actionContext.Response = new
    HttpResponseMessage(HttpStatusCode.Unauthorized);
  36. }
  37. else
  38. {
  39. base.OnActionExecuting(actionContext);
  40. }
  41. }
  42. }
  43. ///
  44. /// 校验用户ticket信息
  45. ///
  46. ///
  47. ///
  48. private bool
    ValidateUserTicket(string
    encryptTicket)
  49. {
  50. var userTicket =
    FormsAuthentication.Decrypt(encryptTicket);
  51. var userTicketData =
    userTicket.UserData;
  52. string
    userName = userTicketData.Substring(0,
    userTicketData.IndexOf(":"));
  53. string
    password =
    userTicketData.Substring(userTicketData.IndexOf(":")
    + 1);
  54. //检查用户名、密码是否正确,验证是合法用户
  55. //var isQuilified = CheckUser(userName,
    password);
  56. return true;
  57. }
  58. }

5.3
api服务Controller实例

[csharp] view
plain
copy
 
  1. public class
    ProductController : ApiControllerBase
  2. {
  3. [HttpGet]
  4. public object
    Find(string
    id)
  5. {
  6. return
    ProductServiceInstance.Find(2);
  7. }
  8. // GET api/product/5
  9. [HttpGet]
  10. [AllowAnonymous]
  11. public
    Product Get(string
    id)
  12. {
  13. var headers =
    Request.Headers;
  14. var p =
    ProductServiceInstance.GetById(long.Parse(id));
  15. if
    (p == null)
  16. {
  17. throw new
    HttpResponseException(new
    HttpResponseMessage(HttpStatusCode.BadRequest)
  18. Content = new
    StringContent("id3 not found"),
    ReasonPhrase = "product id not exist."
    });
  19. }
  20. return
    p;
  21. }
  22. }

6.
其它配置说明

6.1
Mvc前端Web.Config 配置

[html] view
plain
copy
 
  1. <</SPAN>system.web>
  2. <</SPAN>compilation debug="true" targetFramework="4.5">
  3. <</SPAN>assemblies>
  4. <</SPAN>add assembly="System.Web.Http.Data.Helpers,
    Version=4.0.0.0, Culture=neutral,
    PublicKeyToken=31bf3856ad364e35" />
  5. </</SPAN>assemblies>
  6. </</SPAN>compilation>
  7. <</SPAN>httpRuntime targetFramework="4.5" />
  8. <</SPAN>authentication mode="Forms">
  9. <</SPAN>forms loginUrl="~/Account/Login" defaultUrl="~/Home/Index" protection="All" timeout="90" name=".AuthCookie"></</SPAN>forms>
  10. </</SPAN>authentication>
  11. <</SPAN>machineKey validationKey="3FFA12388DDF585BA5D35E7BC87E3F0AB47FBBEBD12240DD3BEA2BEAEC4ABA213F22AD27E8FAD77DCFEE306219691434908D193A17C1FC8DCE51B71A4AE54920"
    decryptionKey="ECB6A3AF9ABBF3F16E80685ED68DC74B0B13CCEE538EBBA97D0B893139683B3B"
    validation="SHA1" decryption="AES" />
  12. </</SPAN>system.web>

machineKey节点配置,是应用于对用户ticket数据加密和解密。

6.2
WebApi服务端Web.Config配置

[html] view
plain
copy
 
  1. <</SPAN>system.web>
  2. <</SPAN>machineKey validationKey="3FF112388DDF585BA5D35E7BC87E3F0AB47FBBEBD12240DD3BEA2BEAEC4ABA213F22AD27E8FAD77DCFEE306219691434908D193A17C1FC8DCE51B71A4AE54920"
    decryptionKey="ECB6A3AF9ABBF3F16E80685ED68DC74B0B13CCEE538EBBA97D0B893139683B3B"
    validation="SHA1" decryption="AES" />
  3. </</SPAN>system.web>

machineKey节点配置,是应用于对用户ticket数据加密和解密。

7.
总结

Web系统的用户登录及页面操作权限验证在处理逻辑上比较复杂,需要考虑到Form认证、匿名访问,Session和Cookie存储,以及Session和Cookie的过期处理,本文实现了整个权限验证框架的基本功能,供系统架构设计人员以及Web开发人员参考。

Demo项目代码地址:
https://github.com/lgsky/DemoUserAuthorization/

上一篇:2018CCPC女生赛(树上莫队)


下一篇:微信H5支付.NET版本备忘