WebApi实现验证授权Token,WebApi生成文档等

来源:互联网 发布:筛子目的算法 编辑:程序博客网 时间:2024/05/18 20:45
  1. using System;  
  2. using System.Linq;  
  3. using System.Web;  
  4. using System.Web.Http;  
  5. using System.Web.Security;  
  6.   
  7. namespace OtherApi.Auth  
  8. {  
  9.   
  10.     public class AuthFilterOutside : AuthorizeAttribute  
  11.     {  
  12.         //重写基类的验证方式,加入我们自定义的Ticket验证  
  13.         public override void OnAuthorization(System.Web.Http.Controllers.HttpActionContext actionContext)  
  14.         {  
  15.             //url获取token  
  16.             var content = actionContext.Request.Properties["MS_HttpContext"as HttpContextBase;  
  17.             var token = content.Request.Headers["Token"];  
  18.             if (!string.IsNullOrEmpty(token))  
  19.             {  
  20.                 //解密用户ticket,并校验用户名密码是否匹配  
  21.                 if (ValidateTicket(token))  
  22.                 {  
  23.                     base.IsAuthorized(actionContext);  
  24.                 }  
  25.                 else  
  26.                 {  
  27.                     HandleUnauthorizedRequest(actionContext);  
  28.                 }  
  29.             }  
  30.             //如果取不到身份验证信息,并且不允许匿名访问,则返回未验证401  
  31.             else  
  32.             {  
  33.                 var attributes = actionContext.ActionDescriptor.GetCustomAttributes<AllowAnonymousAttribute>().OfType<AllowAnonymousAttribute>();  
  34.                 bool isAnonymous = attributes.Any(a => a is AllowAnonymousAttribute);  
  35.                 if (isAnonymous) base.OnAuthorization(actionContext);  
  36.                 else HandleUnauthorizedRequest(actionContext);  
  37.             }  
  38.         }  
  39.   
  40.         //校验票据(数据库数据匹配)  
  41.         private bool ValidateTicket(string encryptToken)  
  42.         {  
  43.             bool flag = false;  
  44.             try  
  45.             {  
  46.                 //获取数据库Token  
  47.                 Dec.Models.TicketAuth model = Dec.BLL.TicketAuth.GetTicketAuthByToken(encryptToken);  
  48.                 if (model.Token == encryptToken) //存在  
  49.                 {  
  50.                     //未超时  
  51.                     flag = (DateTime.Now <= model.ExpireDate) ? true : false;  
  52.                 }  
  53.             }  
  54.             catch (Exception ex) { }  
  55.             return flag;  
  56.         }  
  57.     }  
  58. }  

[csharp] view plain copy
  1. using System;  
  2. using System.Web;  
  3. using System.Web.Http;  
  4. using System.Web.Security;  
  5. using System.Net.Http;  
  6. using System.Collections.Generic;  
  7. using Newtonsoft.Json;  
  8. using Newtonsoft.Json.Linq;  
  9. using System.Text;  
  10. using OtherApi.Auth;  //引用验证  
  11.   
  12. namespace SpiderApi.Controllers  
  13. {  
  14.     /// <summary>  
  15.     /// 用户授权接口  
  16.     /// </summary>  
  17.     public class AccountController : ApiController  
  18.     {  
  19.         #region 用户登录授权  
  20.         /// <summary>  
  21.         /// 用户登录授权  
  22.         /// </summary>  
  23.         /// <param name="username">用户名</param>  
  24.         /// <param name="password">密码</param>  
  25.         /// <returns></returns>  
  26.         [Route("api/account/login")]  
  27.         [HttpGet]  
  28.         public HttpResponseMessage Login(string username, string password)  
  29.         {  
  30.             //定义  
  31.             ResponseResult obj = new ResponseResult();  
  32.             var model = GetLoginModel(username, password);  
  33.             if (model != null)  
  34.             {  
  35.                 int userId = model.UserId;  
  36.                 string Token = UntilHelper.Md5Encode(UntilHelper.GetExtGuidID(), 32);  
  37.                 var dtNow = DateTime.Now;  
  38.  
  39.                 #region 将身份信息保存票据表中,验证当前请求是否是有效请求  
  40.                 //判断此用户是否存在票据信息  
  41.                 if (Dec.BLL.TicketAuth.GetTicketAuthByUserId(userId) != null)  
  42.                 {  
  43.                     //清空重置  
  44.                     Dec.BLL.TicketAuth.DeleteByUserId(userId);  
  45.                 }  
  46.                 Dec.Models.TicketAuth ticket = new Dec.Models.TicketAuth();  
  47.                 ticket.UserID = userId;  
  48.                 ticket.Token = Token;  
  49.                 ticket.CreateDate = dtNow;  
  50.                 ticket.ExpireDate = dtNow.AddMinutes(30); //30分钟过期  
  51.                 Dec.BLL.TicketAuth.Add(ticket);  
  52.                 #endregion  
  53.   
  54.                 //返回信息              
  55.                 obj.status = true;  
  56.                 obj.message = "用户登录成功";  
  57.                 JObject jo = new JObject();  
  58.                 jo.Add("userid", userId);  
  59.                 jo.Add("loginname", model.LoginName);  
  60.                 jo.Add("nickname", model.NickName);  
  61.                 jo.Add("usertype", model.UserType); //(int)UserTypeEnum.Seller  
  62.                 jo.Add("token", Token);  
  63.                 obj.info = jo;  
  64.             }  
  65.             else  
  66.             {  
  67.                 obj.status = false;  
  68.                 obj.message = "用户登录失败";  
  69.             }  
  70.             var resultObj = JsonConvert.SerializeObject(obj, Formatting.Indented);  
  71.             HttpResponseMessage result = new HttpResponseMessage { Content = new StringContent(resultObj, Encoding.GetEncoding("UTF-8"), "application/json") };  
  72.             return result;  
  73.         }  
  74.         #endregion  
  75.  
  76.         #region 用户退出登录,清空Token  
  77.         /// <summary>  
  78.         /// 用户退出登录,清空Token  
  79.         /// </summary>  
  80.         /// <param name="userId">用户ID</param>  
  81.         /// <returns></returns>  
  82.         [Route("api/account/loginout")]  
  83.         [HttpGet]  
  84.         public HttpResponseMessage LoginOut(int userId)  
  85.         {  
  86.             //定义  
  87.             ResponseResult obj = new ResponseResult();  
  88.             try  
  89.             {  
  90.                 //清空数据库该用户票据数据  
  91.                 Dec.BLL.TicketAuth.DeleteByUserId(userId);  
  92.             }  
  93.             catch (Exception ex) { }  
  94.             //返回信息              
  95.             obj.status = true;  
  96.             obj.message = "成功退出";  
  97.             var resultObj = JsonConvert.SerializeObject(obj);  
  98.             HttpResponseMessage result = new HttpResponseMessage { Content = new StringContent(resultObj, Encoding.GetEncoding("UTF-8"), "application/json") };  
  99.             return result;  
  100.         }  
  101.         #endregion  
  102.  
  103.         #region 查询Token是否有效  
  104.         /// <summary>  
  105.         /// 查询Token是否有效  
  106.         /// </summary>  
  107.         /// <param name="token">token</param>  
  108.         /// <returns></returns>  
  109.         [Route("api/account/validatetoken")]  
  110.         [HttpGet]  
  111.         public HttpResponseMessage ValidateToken(string token)  
  112.         {  
  113.             //定义  
  114.             ResponseResult obj = new ResponseResult();  
  115.             bool flag = ValidateTicket(token);  
  116.             if (flag)  
  117.             {  
  118.                 //返回信息              
  119.                 obj.status = true;  
  120.                 obj.message = "token有效";  
  121.             }  
  122.             else  
  123.             {  
  124.                 obj.status = false;  
  125.                 obj.message = "token无效";  
  126.             }  
  127.             var resultObj = JsonConvert.SerializeObject(obj);  
  128.             HttpResponseMessage result = new HttpResponseMessage { Content = new StringContent(resultObj, Encoding.GetEncoding("UTF-8"), "application/json") };  
  129.             return result;  
  130.         }  
  131.         #endregion  
  132.  
  133.         #region 获取用户账户余额  
  134.         /// <summary>  
  135.         /// 获取用户账户余额  
  136.         /// </summary>  
  137.         /// <param name="userId">用户ID</param>  
  138.         /// <returns></returns>  
  139.         [Route("api/account/amount")]  
  140.         [HttpGet]  
  141.         [AuthFilterOutside] //添加验证  
  142.         public HttpResponseMessage GetAmount(int userId)  
  143.         {  
  144.             //定义  
  145.             ResponseResult obj = new ResponseResult();  
  146.             //获取数据库数据  
  147.             Dec.Models.UserInfo model = Dec.BLL.UserInfo.GetUserInfoByUserId(userId);  
  148.             if (model != null)  
  149.             {  
  150.                 //返回信息              
  151.                 obj.status = true;  
  152.                 obj.message = "获取用户账户余额成功";  
  153.                 JObject jo = new JObject();  
  154.                 jo.Add("userid", model.UserId);  
  155.                 jo.Add("amount", model.Amount);  
  156.                 obj.info = jo;  
  157.             }  
  158.             else  
  159.             {  
  160.                 obj.status = false;  
  161.                 obj.message = "获取用户账户余额失败";  
  162.             }  
  163.   
  164.             var resultObj = JsonConvert.SerializeObject(obj);  
  165.             HttpResponseMessage result = new HttpResponseMessage { Content = new StringContent(resultObj, Encoding.GetEncoding("UTF-8"), "application/json") };  
  166.             return result;  
  167.         }  
  168.         #endregion  
  169.   
  170.         /// <summary>  
  171.         /// 用户充值接口  
  172.         /// </summary>  
  173.         /// <param name="userid">用户ID</param>  
  174.         /// <param name="amount">充值金额</param>  
  175.         /// <returns></returns>  
  176.         [Route("api/account/recharge")]  
  177.         [HttpGet]  
  178.         [AuthFilterInside]  
  179.         public HttpResponseMessage Recharge(string userid, double amount)  
  180.         {  
  181.             //定义  
  182.             ResponseResult obj = new ResponseResult();  
  183.             //获取数据库数据  
  184.   
  185.             //返回信息              
  186.             obj.status = true;  
  187.             obj.message = "操作成功,请等待第三方支付平台返回通知核实是否到账";  
  188.             JObject jo = new JObject();  
  189.             jo.Add("userid""123456789");  
  190.             jo.Add("amount", 125.80);  
  191.             obj.info = jo;  
  192.   
  193.             var resultObj = JsonConvert.SerializeObject(obj);  
  194.             HttpResponseMessage result = new HttpResponseMessage { Content = new StringContent(resultObj, Encoding.GetEncoding("UTF-8"), "application/json") };  
  195.             return result;  
  196.         }  
  197.  
  198.          #region 验证票据是否有效  
  199.         /// <summary>  
  200.         /// 验证票据是否有效  
  201.         /// </summary>  
  202.         /// <param name="encryptToken">token</param>  
  203.         /// <returns></returns>  
  204.         private bool ValidateTicket(string encryptToken)  
  205.         {  
  206.             bool flag = false;  
  207.             try  
  208.             {  
  209.                 //获取数据库Token  
  210.                 Dec.Models.TicketAuth model = Dec.BLL.TicketAuth.GetTicketAuthByToken(encryptToken);  
  211.                 if (model.Token == encryptToken) //存在  
  212.                 {  
  213.                     //未超时  
  214.                     flag = (DateTime.Now <= model.ExpireDate) ? true : false;  
  215.                 }  
  216.             }  
  217.             catch (Exception ex) { }  
  218.             return flag;  
  219.         }  
  220.         #endregion  
  221.  
  222.         #region 用户登录  
  223.         /// <summary>  
  224.         /// 用户登录  
  225.         /// </summary>  
  226.         /// <param name="userName">用户名</param>  
  227.         /// <param name="userPwd">密码</param>  
  228.         /// <returns></returns>  
  229.         private Dec.Models.UserInfo GetLoginModel(string userName, string userPwd)  
  230.         {  
  231.             Dec.Models.UserInfo model = new Dec.Models.UserInfo();  
  232.             try  
  233.             {  
  234.                 if (!string.IsNullOrWhiteSpace(userName) && !string.IsNullOrWhiteSpace(userPwd))  
  235.                 {  
  236.                     //数据库比对  
  237.                     model = Dec.BLL.UserInfo.GetUserInfoByUserNamePwd(userName, UntilHelper.Md5Encode(userPwd, 32));  
  238.                 }  
  239.             }  
  240.             catch (Exception ex) { }  
  241.             return model;  
  242.         }  
  243.         #endregion  
  244.     }  
  245. }  
[csharp] view plain copy
  1. //////////////////////////////////////////////////////////////////  
  2. using System;  
  3. using System.Collections.Generic;  
  4. using System.Linq;  
  5. using System.Web;  
  6. using System.Web.Http;  
  7. using System.Web.Mvc;  
  8. using System.Web.Routing;  
  9.   
  10. namespace SpiderApi  
  11. {  
  12.     public class WebApiApplication : System.Web.HttpApplication  
  13.     {  
  14.         protected void Application_Start()  
  15.         {  
  16.             //WebApi文档  
  17.             AreaRegistration.RegisterAllAreas();  
  18.             GlobalConfiguration.Configure(WebApiConfig.Register);  
  19.         }  
  20.   
  21.         protected void Application_PostAuthorizeRequest()  
  22.         {  
  23.             //Enable Session  
  24.             HttpContext.Current.SetSessionStateBehavior(System.Web.SessionState.SessionStateBehavior.Required);  
  25.         }  
  26.     }  
  27. }  
[csharp] view plain copy
  1. // Uncomment the following to provide samples for PageResult<T>. Must also add the Microsoft.AspNet.WebApi.OData  
  2. // package to your project. 先安装Help Page包  HelpPage=>App_start=>HelpPageConfig.cs  
  3. ////#define Handle_PageResultOfT  
  4.   
  5. using System;  
  6. using System.Collections;  
  7. using System.Collections.Generic;  
  8. using System.Diagnostics;  
  9. using System.Diagnostics.CodeAnalysis;  
  10. using System.Linq;  
  11. using System.Net.Http.Headers;  
  12. using System.Reflection;  
  13. using System.Web;  
  14. using System.Web.Http;  
  15. using SpiderApi.Models;  
  16. #if Handle_PageResultOfT  
  17. using System.Web.Http.OData;  
  18. #endif  
  19.   
  20. namespace SpiderApi.Areas.HelpPage  
  21. {  
  22.     /// <summary>  
  23.     /// Use this class to customize the Help Page.  
  24.     /// For example you can set a custom <see cref="System.Web.Http.Description.IDocumentationProvider"/> to supply the documentation  
  25.     /// or you can provide the samples for the requests/responses.  
  26.     /// </summary>  
  27.     public static class HelpPageConfig  
  28.     {  
  29.         [SuppressMessage("Microsoft.Globalization""CA1303:Do not pass literals as localized parameters",  
  30.             MessageId = "SpiderApi.Areas.HelpPage.TextSample.#ctor(System.String)",  
  31.             Justification = "End users may choose to merge this string with existing localized resources.")]  
  32.         [SuppressMessage("Microsoft.Naming""CA2204:Literals should be spelled correctly",  
  33.             MessageId = "bsonspec",  
  34.             Justification = "Part of a URI.")]  
  35.         public static void Register(HttpConfiguration config)  
  36.         {  
  37.             //// Uncomment the following to use the documentation from XML documentation file.  
  38.             //开启解析  
  39.             config.SetDocumentationProvider(new XmlDocumentationProvider(HttpContext.Current.Server.MapPath("~/Bin/SpiderApi.XML")));  
  40.   
  41.             //// Uncomment the following to use "sample string" as the sample for all actions that have string as the body parameter or return type.  
  42.             //// Also, the string arrays will be used for IEnumerable<string>. The sample objects will be serialized into different media type   
  43.             //// formats by the available formatters.  
  44.             //config.SetSampleObjects(new Dictionary<Type, object>  
  45.             //{  
  46.             //    {typeof(string), "sample string"},  
  47.             //    {typeof(IEnumerable<string>), new string[]{"sample 1", "sample 2"}}  
  48.             //});  
  49.             //添加映射  
  50.             config.SetSampleResponse(Sample.BatchSendMessageResponse(), new MediaTypeHeaderValue("text/json"), "MessageQueue""BatchSendMessage");  
  51.             config.SetSampleResponse(Sample.BatchReceiveMessageResponse(), new MediaTypeHeaderValue("text/json"), "MessageQueue""BatchReceiveMessage");  
  52.             config.SetSampleResponse(Sample.DeleteMessageResponse(), new MediaTypeHeaderValue("text/json"), "MessageQueue""DeleteMessage");  
  53.             config.SetSampleResponse(Sample.BatchDeleteMessageResponse(), new MediaTypeHeaderValue("text/json"), "MessageQueue""BatchDeleteMessage");  
  54.             config.SetSampleResponse(Sample.ChangeMessageVisibilityResponse(), new MediaTypeHeaderValue("text/json"), "MessageQueue""ChangeMessageVisibility");  
  55.   
  56.             // Extend the following to provide factories for types not handled automatically (those lacking parameterless  
  57.             // constructors) or for which you prefer to use non-default property values. Line below provides a fallback  
  58.             // since automatic handling will fail and GeneratePageResult handles only a single type.  
  59. #if Handle_PageResultOfT  
  60.             config.GetHelpPageSampleGenerator().SampleObjectFactories.Add(GeneratePageResult);  
  61. #endif  
  62.   
  63.             // Extend the following to use a preset object directly as the sample for all actions that support a media  
  64.             // type, regardless of the body parameter or return type. The lines below avoid display of binary content.  
  65.             // The BsonMediaTypeFormatter (if available) is not used to serialize the TextSample object.  
  66.             config.SetSampleForMediaType(  
  67.                 new TextSample("Binary JSON content. See http://bsonspec.org for details."),  
  68.                 new MediaTypeHeaderValue("application/bson"));  
  69.   
  70.             //// Uncomment the following to use "[0]=foo&[1]=bar" directly as the sample for all actions that support form URL encoded format  
  71.             //// and have IEnumerable<string> as the body parameter or return type.  
  72.             //config.SetSampleForType("[0]=foo&[1]=bar", new MediaTypeHeaderValue("application/x-www-form-urlencoded"), typeof(IEnumerable<string>));  
  73.   
  74.             //// Uncomment the following to use "1234" directly as the request sample for media type "text/plain" on the controller named "Values"  
  75.             //// and action named "Put".  
  76.             //config.SetSampleRequest("1234", new MediaTypeHeaderValue("text/plain"), "Values", "Put");  
  77.   
  78.             //// Uncomment the following to use the image on "../images/aspNetHome.png" directly as the response sample for media type "image/png"  
  79.             //// on the controller named "Values" and action named "Get" with parameter "id".  
  80.             //config.SetSampleResponse(new ImageSample("../images/aspNetHome.png"), new MediaTypeHeaderValue("image/png"), "Values", "Get", "id");  
  81.   
  82.             //// Uncomment the following to correct the sample request when the action expects an HttpRequestMessage with ObjectContent<string>.  
  83.             //// The sample will be generated as if the controller named "Values" and action named "Get" were having string as the body parameter.  
  84.             //config.SetActualRequestType(typeof(string), "Values", "Get");  
  85.   
  86.             //// Uncomment the following to correct the sample response when the action returns an HttpResponseMessage with ObjectContent<string>.  
  87.             //// The sample will be generated as if the controller named "Values" and action named "Post" were returning a string.  
  88.             //config.SetActualResponseType(typeof(string), "Values", "Post");  
  89.         }  
  90.  
  91. #if Handle_PageResultOfT  
  92.         private static object GeneratePageResult(HelpPageSampleGenerator sampleGenerator, Type type)  
  93.         {  
  94.             if (type.IsGenericType)  
  95.             {  
  96.                 Type openGenericType = type.GetGenericTypeDefinition();  
  97.                 if (openGenericType == typeof(PageResult<>))  
  98.                 {  
  99.                     // Get the T in PageResult<T>  
  100.                     Type[] typeParameters = type.GetGenericArguments();  
  101.                     Debug.Assert(typeParameters.Length == 1);  
  102.   
  103.                     // Create an enumeration to pass as the first parameter to the PageResult<T> constuctor  
  104.                     Type itemsType = typeof(List<>).MakeGenericType(typeParameters);  
  105.                     object items = sampleGenerator.GetSampleObject(itemsType);  
  106.   
  107.                     // Fill in the other information needed to invoke the PageResult<T> constuctor  
  108.                     Type[] parameterTypes = new Type[] { itemsType, typeof(Uri), typeof(long?), };  
  109.                     object[] parameters = new object[] { items, null, (long)ObjectGenerator.DefaultCollectionSize, };  
  110.   
  111.                     // Call PageResult(IEnumerable<T> items, Uri nextPageLink, long? count) constructor  
  112.                     ConstructorInfo constructor = type.GetConstructor(parameterTypes);  
  113.                     return constructor.Invoke(parameters);  
  114.                 }  
  115.             }  
  116.   
  117.             return null;  
  118.         }  
  119. #endif  
  120.     }  
  121. }  
[csharp] view plain copy
  1. /* 
  2. API接口测试工具 - WebApiTestClient使用--Nuget引入组件  
  3. --A Simple Test Client for ASP.NET Web API 
  4. */  
  5. /* 
  6. 1、修改Api.cshtml文件 
  7. 通过上述步骤,就能将组件WebAPITestClient引入进来。下面我们只需要做一件事:打开文件 (根据 Areas\HelpPage\Views\Help) Api.cshtml 并添加以下内容: 
  8.  
  9. @Html.DisplayForModel("TestClientDialogs") 
  10. @Html.DisplayForModel("TestClientReferences") 
  11. 添加后Api.cshtml文件的代码如下 
  12. */  
  13.   
  14.   
  15. @using System.Web.Http  
  16. @using WebApiTestClient.Areas.HelpPage.Models  
  17. @model HelpPageApiModel  
  18.   
  19. @{  
  20.     var description = Model.ApiDescription;  
  21.     ViewBag.Title = description.HttpMethod.Method + " " + description.RelativePath;  
  22. }  
  23.   
  24. <link type="text/css" href="~/Areas/HelpPage/HelpPage.css" rel="stylesheet" />  
  25. <div id="body" class="help-page">  
  26.     <section class="featured">  
  27.         <div class="content-wrapper">  
  28.             <p>  
  29.                 @Html.ActionLink("Help Page Home""Index")  
  30.             </p>  
  31.         </div>  
  32.     </section>  
  33.     <section class="content-wrapper main-content clear-fix">  
  34.         @Html.DisplayForModel()  
  35.     </section>  
  36. </div>  
  37.   
  38. @Html.DisplayForModel("TestClientDialogs")  
  39. @section Scripts{  
  40.     <link href="~/Areas/HelpPage/HelpPage.css" rel="stylesheet" />  
  41.     @Html.DisplayForModel("TestClientReferences")  
  42. }