1. 程式人生 > >WebApi實現驗證授權Token,WebApi生成文件等(轉)

WebApi實現驗證授權Token,WebApi生成文件等(轉)

using System;
using System.Linq;
using System.Web;
using System.Web.Http;
using System.Web.Security;
 
namespace OtherApi.Auth
{
 
    public class AuthFilterOutside : AuthorizeAttribute
    {
        //重寫基類的驗證方式,加入我們自定義的Ticket驗證
        public override void OnAuthorization(System.Web.Http.Controllers.HttpActionContext actionContext)
        {
            
//url獲取token var content = actionContext.Request.Properties["MS_HttpContext"] as HttpContextBase; var token = content.Request.Headers["Token"]; if (!string.IsNullOrEmpty(token)) { //解密使用者ticket,並校驗使用者名稱密碼是否匹配 if (ValidateTicket(token)) {
base.IsAuthorized(actionContext); } else { HandleUnauthorizedRequest(actionContext); } } //如果取不到身份驗證資訊,並且不允許匿名訪問,則返回未驗證401 else { var attributes = actionContext.ActionDescriptor.GetCustomAttributes<AllowAnonymousAttribute>().OfType<AllowAnonymousAttribute>();
bool isAnonymous = attributes.Any(a => a is AllowAnonymousAttribute); if (isAnonymous) base.OnAuthorization(actionContext); else HandleUnauthorizedRequest(actionContext); } } //校驗票據(資料庫資料匹配) private bool ValidateTicket(string encryptToken) { bool flag = false; try { //獲取資料庫Token Dec.Models.TicketAuth model = Dec.BLL.TicketAuth.GetTicketAuthByToken(encryptToken); if (model.Token == encryptToken) //存在 { //未超時 flag = (DateTime.Now <= model.ExpireDate) ? true : false; } } catch (Exception ex) { } return flag; } } }
using System;
using System.Web;
using System.Web.Http;
using System.Web.Security;
using System.Net.Http;
using System.Collections.Generic;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Text;
using OtherApi.Auth;  //引用驗證
 
namespace SpiderApi.Controllers
{
    /// <summary>
    /// 使用者授權介面
    /// </summary>
    public class AccountController : ApiController
    {
        #region 使用者登入授權
        /// <summary>
        /// 使用者登入授權
        /// </summary>
        /// <param name="username">使用者名稱</param>
        /// <param name="password">密碼</param>
        /// <returns></returns>
        [Route("api/account/login")]
        [HttpGet]
        public HttpResponseMessage Login(string username, string password)
        {
            //定義
            ResponseResult obj = new ResponseResult();
            var model = GetLoginModel(username, password);
            if (model != null)
            {
                int userId = model.UserId;
                string Token = UntilHelper.Md5Encode(UntilHelper.GetExtGuidID(), 32);
                var dtNow = DateTime.Now;
 
                #region 將身份資訊儲存票據表中,驗證當前請求是否是有效請求
                //判斷此使用者是否存在票據資訊
                if (Dec.BLL.TicketAuth.GetTicketAuthByUserId(userId) != null)
                {
                    //清空重置
                    Dec.BLL.TicketAuth.DeleteByUserId(userId);
                }
                Dec.Models.TicketAuth ticket = new Dec.Models.TicketAuth();
                ticket.UserID = userId;
                ticket.Token = Token;
                ticket.CreateDate = dtNow;
                ticket.ExpireDate = dtNow.AddMinutes(30); //30分鐘過期
                Dec.BLL.TicketAuth.Add(ticket);
                #endregion
 
                //返回資訊            
                obj.status = true;
                obj.message = "使用者登入成功";
                JObject jo = new JObject();
                jo.Add("userid", userId);
                jo.Add("loginname", model.LoginName);
                jo.Add("nickname", model.NickName);
                jo.Add("usertype", model.UserType); //(int)UserTypeEnum.Seller
                jo.Add("token", Token);
                obj.info = jo;
            }
            else
            {
                obj.status = false;
                obj.message = "使用者登入失敗";
            }
            var resultObj = JsonConvert.SerializeObject(obj, Formatting.Indented);
            HttpResponseMessage result = new HttpResponseMessage { Content = new StringContent(resultObj, Encoding.GetEncoding("UTF-8"), "application/json") };
            return result;
        }
        #endregion
 
        #region 使用者退出登入,清空Token
        /// <summary>
        /// 使用者退出登入,清空Token
        /// </summary>
        /// <param name="userId">使用者ID</param>
        /// <returns></returns>
        [Route("api/account/loginout")]
        [HttpGet]
        public HttpResponseMessage LoginOut(int userId)
        {
            //定義
            ResponseResult obj = new ResponseResult();
            try
            {
                //清空資料庫該使用者票據資料
                Dec.BLL.TicketAuth.DeleteByUserId(userId);
            }
            catch (Exception ex) { }
            //返回資訊            
            obj.status = true;
            obj.message = "成功退出";
            var resultObj = JsonConvert.SerializeObject(obj);
            HttpResponseMessage result = new HttpResponseMessage { Content = new StringContent(resultObj, Encoding.GetEncoding("UTF-8"), "application/json") };
            return result;
        }
        #endregion
 
        #region 查詢Token是否有效
        /// <summary>
        /// 查詢Token是否有效
        /// </summary>
        /// <param name="token">token</param>
        /// <returns></returns>
        [Route("api/account/validatetoken")]
        [HttpGet]
        public HttpResponseMessage ValidateToken(string token)
        {
            //定義
            ResponseResult obj = new ResponseResult();
            bool flag = ValidateTicket(token);
            if (flag)
            {
                //返回資訊            
                obj.status = true;
                obj.message = "token有效";
            }
            else
            {
                obj.status = false;
                obj.message = "token無效";
            }
            var resultObj = JsonConvert.SerializeObject(obj);
            HttpResponseMessage result = new HttpResponseMessage { Content = new StringContent(resultObj, Encoding.GetEncoding("UTF-8"), "application/json") };
            return result;
        }
        #endregion
 
        #region 獲取使用者賬戶餘額
        /// <summary>
        /// 獲取使用者賬戶餘額
        /// </summary>
        /// <param name="userId">使用者ID</param>
        /// <returns></returns>
        [Route("api/account/amount")]
        [HttpGet]
        [AuthFilterOutside] //新增驗證
        public HttpResponseMessage GetAmount(int userId)
        {
            //定義
            ResponseResult obj = new ResponseResult();
            //獲取資料庫資料
            Dec.Models.UserInfo model = Dec.BLL.UserInfo.GetUserInfoByUserId(userId);
            if (model != null)
            {
                //返回資訊            
                obj.status = true;
                obj.message = "獲取使用者賬戶餘額成功";
                JObject jo = new JObject();
                jo.Add("userid", model.UserId);
                jo.Add("amount", model.Amount);
                obj.info = jo;
            }
            else
            {
                obj.status = false;
                obj.message = "獲取使用者賬戶餘額失敗";
            }
 
            var resultObj = JsonConvert.SerializeObject(obj);
            HttpResponseMessage result = new HttpResponseMessage { Content = new StringContent(resultObj, Encoding.GetEncoding("UTF-8"), "application/json") };
            return result;
        }
        #endregion
 
        /// <summary>
        /// 使用者充值介面
        /// </summary>
        /// <param name="userid">使用者ID</param>
        /// <param name="amount">充值金額</param>
        /// <returns></returns>
        [Route("api/account/recharge")]
        [HttpGet]
        [AuthFilterInside]
        public HttpResponseMessage Recharge(string userid, double amount)
        {
            //定義
            ResponseResult obj = new ResponseResult();
            //獲取資料庫資料
 
            //返回資訊            
            obj.status = true;
            obj.message = "操作成功,請等待第三方支付平臺返回通知核實是否到賬";
            JObject jo = new JObject();
            jo.Add("userid", "123456789");
            jo.Add("amount", 125.80);
            obj.info = jo;
 
            var resultObj = JsonConvert.SerializeObject(obj);
            HttpResponseMessage result = new HttpResponseMessage { Content = new StringContent(resultObj, Encoding.GetEncoding("UTF-8"), "application/json") };
            return result;
        }
 
         #region 驗證票據是否有效
        /// <summary>
        /// 驗證票據是否有效
        /// </summary>
        /// <param name="encryptToken">token</param>
        /// <returns></returns>
        private bool ValidateTicket(string encryptToken)
        {
            bool flag = false;
            try
            {
                //獲取資料庫Token
                Dec.Models.TicketAuth model = Dec.BLL.TicketAuth.GetTicketAuthByToken(encryptToken);
                if (model.Token == encryptToken) //存在
                {
                    //未超時
                    flag = (DateTime.Now <= model.ExpireDate) ? true : false;
                }
            }
            catch (Exception ex) { }
            return flag;
        }
        #endregion
 
        #region 使用者登入
        /// <summary>
        /// 使用者登入
        /// </summary>
        /// <param name="userName">使用者名稱</param>
        /// <param name="userPwd">密碼</param>
        /// <returns></returns>
        private Dec.Models.UserInfo GetLoginModel(string userName, string userPwd)
        {
            Dec.Models.UserInfo model = new Dec.Models.UserInfo();
            try
            {
                if (!string.IsNullOrWhiteSpace(userName) && !string.IsNullOrWhiteSpace(userPwd))
                {
                    //資料庫比對
                    model = Dec.BLL.UserInfo.GetUserInfoByUserNamePwd(userName, UntilHelper.Md5Encode(userPwd, 32));
                }
            }
            catch (Exception ex) { }
            return model;
        }
        #endregion
    }
}
//////////////////////////////////////////////////////////////////
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Http;
using System.Web.Mvc;
using System.Web.Routing;
 
namespace SpiderApi
{
    public class WebApiApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            //WebApi文件
            AreaRegistration.RegisterAllAreas();
            GlobalConfiguration.Configure(WebApiConfig.Register);
        }
 
        protected void Application_PostAuthorizeRequest()
        {
            //Enable Session
            HttpContext.Current.SetSessionStateBehavior(System.Web.SessionState.SessionStateBehavior.Required);
        }
    }
}
// Uncomment the following to provide samples for PageResult<T>. Must also add the Microsoft.AspNet.WebApi.OData
// package to your project. 先安裝Help Page包  HelpPage=>App_start=>HelpPageConfig.cs
////#define Handle_PageResultOfT
 
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Net.Http.Headers;
using System.Reflection;
using System.Web;
using System.Web.Http;
using SpiderApi.Models;
#if Handle_PageResultOfT
using System.Web.Http.OData;
#endif
 
namespace SpiderApi.Areas.HelpPage
{
    /// <summary>
    /// Use this class to customize the Help Page.
    /// For example you can set a custom <see cref="System.Web.Http.Description.IDocumentationProvider"/> to supply the documentation
    /// or you can provide the samples for the requests/responses.
    /// </summary>
    public static class HelpPageConfig
    {
        [SuppressMessage("Microsoft.Globalization", "CA1303:Do not pass literals as localized parameters",
            MessageId = "SpiderApi.Areas.HelpPage.TextSample.#ctor(System.String)",
            Justification = "End users may choose to merge this string with existing localized resources.")]
        [SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly",
            MessageId = "bsonspec",
            Justification = "Part of a URI.")]
        public static void Register(HttpConfiguration config)
        {
            //// Uncomment the following to use the documentation from XML documentation file.
            //開啟解析
            config.SetDocumentationProvider(new XmlDocumentationProvider(HttpContext.Current.Server.MapPath("~/Bin/SpiderApi.XML")));
 
            //// Uncomment the following to use "sample string" as the sample for all actions that have string as the body parameter or return type.
            //// Also, the string arrays will be used for IEnumerable<string>. The sample objects will be serialized into different media type 
            //// formats by the available formatters.
            //config.SetSampleObjects(new Dictionary<Type, object>
            //{
            //    {typeof(string), "sample string"},
            //    {typeof(IEnumerable<string>), new string[]{"sample 1", "sample 2"}}
            //});
            //新增對映
            config.SetSampleResponse(Sample.BatchSendMessageResponse(), new MediaTypeHeaderValue("text/json"), "MessageQueue", "BatchSendMessage");
            config.SetSampleResponse(Sample.BatchReceiveMessageResponse(), new MediaTypeHeaderValue("text/json"), "MessageQueue", "BatchReceiveMessage");
            config.SetSampleResponse(Sample.DeleteMessageResponse(), new MediaTypeHeaderValue("text/json"), "MessageQueue", "DeleteMessage");
            config.SetSampleResponse(Sample.BatchDeleteMessageResponse(), new MediaTypeHeaderValue("text/json"), "MessageQueue", "BatchDeleteMessage");
            config.SetSampleResponse(Sample.ChangeMessageVisibilityResponse(), new MediaTypeHeaderValue("text/json"), "MessageQueue", "ChangeMessageVisibility");
 
            // Extend the following to provide factories for types not handled automatically (those lacking parameterless
            // constructors) or for which you prefer to use non-default property values. Line below provides a fallback
            // since automatic handling will fail and GeneratePageResult handles only a single type.
#if Handle_PageResultOfT
            config.GetHelpPageSampleGenerator().SampleObjectFactories.Add(GeneratePageResult);
#endif
 
            // Extend the following to use a preset object directly as the sample for all actions that support a media
            // type, regardless of the body parameter or return type. The lines below avoid display of binary content.
            // The BsonMediaTypeFormatter (if available) is not used to serialize the TextSample object.
            config.SetSampleForMediaType(
                new TextSample("Binary JSON content. See http://bsonspec.org for details."),
                new MediaTypeHeaderValue("application/bson"));
 
            //// Uncomment the following to use "[0]=foo&[1]=bar" directly as the sample for all actions that support form URL encoded format
            //// and have IEnumerable<string> as the body parameter or return type.
            //config.SetSampleForType("[0]=foo&[1]=bar", new MediaTypeHeaderValue("application/x-www-form-urlencoded"), typeof(IEnumerable<string>));
 
            //// Uncomment the following to use "1234" directly as the request sample for media type "text/plain" on the controller named "Values"
            //// and action named "Put".
            //config.SetSampleRequest("1234", new MediaTypeHeaderValue("text/plain"), "Values", "Put");
 
            //// Uncomment the following to use the image on "../images/aspNetHome.png" directly as the response sample for media type "image/png"
            //// on the controller named "Values" and action named "Get" with parameter "id".
            //config.SetSampleResponse(new ImageSample("../images/aspNetHome.png"), new MediaTypeHeaderValue("image/png"), "Values", "Get", "id");
 
            //// Uncomment the following to correct the sample request when the action expects an HttpRequestMessage with ObjectContent<string>.
            //// The sample will be generated as if the controller named "Values" and action named "Get" were having string as the body parameter.
            //config.SetActualRequestType(typeof(string), "Values", "Get");
 
            //// Uncomment the following to correct the sample response when the action returns an HttpResponseMessage with ObjectContent<string>.
            //// The sample will be generated as if the controller named "Values" and action named "Post" were returning a string.
            //config.SetActualResponseType(typeof(string), "Values", "Post");
        }
 
#if Handle_PageResultOfT
        private static object GeneratePageResult(HelpPageSampleGenerator sampleGenerator, Type type)
        {
            if (type.IsGenericType)
            {
                Type openGenericType = type.GetGenericTypeDefinition();
                if (openGenericType == typeof(PageResult<>))
                {
                    // Get the T in PageResult<T>
                    Type[] typeParameters = type.GetGenericArguments();
                    Debug.Assert(typeParameters.Length == 1);
 
                    // Create an enumeration to pass as the first parameter to the PageResult<T> constuctor
                    Type itemsType = typeof(List<>).MakeGenericType(typeParameters);
                    object items = sampleGenerator.GetSampleObject(itemsType);
 
                    // Fill in the other information needed to invoke the PageResult<T> constuctor
                    Type[] parameterTypes = new Type[] { itemsType, typeof(Uri), typeof(long?), };
                    object[] parameters = new object[] { items, null, (long)ObjectGenerator.DefaultCollectionSize, };
 
                    // Call PageResult(IEnumerable<T> items, Uri nextPageLink, long? count) constructor
                    ConstructorInfo constructor = type.GetConstructor(parameterTypes);
                    return constructor.Invoke(parameters);
                }
            }
 
            return null;
        }
#endif
    }
}
/*
API介面測試工具 - WebApiTestClient使用--Nuget引入元件 
--A Simple Test Client for ASP.NET Web API
*/
/*
1、修改Api.cshtml檔案
通過上述步驟,就能將元件WebAPITestClient引入進來。下面我們只需要做一件事:開啟檔案 (根據 Areas\HelpPage\Views\Help) Api.cshtml 並新增以下內容:
@Html.DisplayForModel("TestClientDialogs")
@Html.DisplayForModel("TestClientReferences")
新增後Api.cshtml檔案的程式碼如下
*/
 
 
@using System.Web.Http
@using WebApiTestClient.Areas.HelpPage.Models
@model HelpPageApiModel
 
@{
    var description = Model.ApiDescription;
    ViewBag.Title = description.HttpMethod.Method + " " + description.RelativePath;
}
 
<link type="text/css" href="~/Areas/HelpPage/HelpPage.css" rel="stylesheet" />
<div id="body" class="help-page">
    <section class="featured">
        <div class="content-wrapper">
            <p>
                @Html.ActionLink("Help Page Home", "Index")
            </p>
        </div>
    </section>
    <section class="content-wrapper main-content clear-fix">
        @Html.DisplayForModel()
    </section>
</div>
 
@Html.DisplayForModel("TestClientDialogs")
@section Scripts{
    <link href="~/Areas/HelpPage/HelpPage.css" rel="stylesheet" />
    @Html.DisplayForModel("TestClientReferences")
}

源自:https://blog.csdn.net/smartsmile2012/article/details/52936011/