asp.net-mvc-3 – 用于基本身份验证的asp mvc 3 ActionFilter

前端之家收集整理的这篇文章主要介绍了asp.net-mvc-3 – 用于基本身份验证的asp mvc 3 ActionFilter前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个使用基本身份验证的ASP MVC3 restful服务.搜索堆栈溢出后,我创建了以下代码.
  1. public class BasicAuthentication : ActionFilterAttribute
  2. {
  3. public override void OnActionExecuting(ActionExecutingContext filterContext)
  4. {
  5. var req = filterContext.HttpContext.Request;
  6. if (String.IsNullOrEmpty(req.Headers["Authorization"]))
  7. {
  8. filterContext.Result = new HttpNotFoundResult();
  9. }
  10. else
  11. {
  12. var credentials = System.Text.ASCIIEncoding.ASCII
  13. .GetString(Convert.FromBase64String(req.Headers["Authorization"].Substring(6)))
  14. .Split(':');
  15. var user = new { Name = credentials[0],Password = credentials[1] };
  16. if(!(user.Name == "username" && user.Password == "passwords"))
  17. {
  18. filterContext.Result = new HttpNotFoundResult();
  19. }
  20. }
  21. }
  22. }

1)ActionFilterAttribute是最好的方法吗?

2)设置filterContext.Result是否正确拒绝访问控制器方法

3)我有什么问题吗?

谢谢.

-缺口

解决方法

1)ActionFilterAttribute是最好的方法吗?
我想是这样.此方法反映了内置Authorize属性的实现.

2)设置filterContext.Result是否正确拒绝访问控制器方法
是.多数民众赞成在那里. (1)

3)我有什么问题吗?

>您假设Authorization标头的内容位于
格式正确,编码正确.
>您认为该请求是用于基本身份验证而不是任何请求
其他认证方案.
>我更愿意使用HttpUnauthorizedResult()发送一个http
通过HttpNotFoundResult()发生401错误而不是http 404错误.

下面是我的代码实现(我肯定也有它的问题).

  1. public override void OnActionExecuting(ActionExecutingContext filterContext)
  2. {
  3. try
  4. {
  5. if (String.IsNullOrEmpty(filterContext.HttpContext.Request.Headers["Authorization"]))
  6. {
  7. filterContext.Result = new HttpUnauthorizedResult();
  8. }
  9. else
  10. {
  11. if (filterContext.HttpContext.Request.Headers["Authorization"].StartsWith("Basic ",StringComparison.InvariantCultureIgnoreCase))
  12. {
  13. string[] credentials = ASCIIEncoding.ASCII.GetString(Convert.FromBase64String(filterContext.HttpContext.Request.Headers["Authorization"].Substring(6))).Split(':');
  14.  
  15. if (credentials.Length == 2)
  16. {
  17. if (String.IsNullOrEmpty(credentials[0]))
  18. {
  19. filterContext.Result = new HttpUnauthorizedResult();
  20. }
  21. else if (!(credentials[0] == "username" && credentials[1] == "passwords"))
  22. {
  23. filterContext.Result = new HttpUnauthorizedResult();
  24. }
  25. }
  26. else
  27. {
  28. filterContext.Result = new HttpUnauthorizedResult();
  29. }
  30. }
  31. else
  32. {
  33. filterContext.Result = new HttpUnauthorizedResult();
  34. }
  35. }
  36.  
  37. base.OnActionExecuting(filterContext);
  38. }
  39. catch
  40. {
  41. filterContext.Result = new HttpUnauthorizedResult();
  42. }
  43. }

笔记

>我没有包含用户名和密码的非法字符检查.
>我无法解决如何实现异常处理的问题,所以我简单易行.

参考

(1)http://msdn.microsoft.com/en-us/magazine/gg232768.aspx

猜你在找的asp.Net相关文章