Restful風格wcf調用4——權限認證


寫在前面

在前面的三篇文章,已經介紹了restful風格wcf,如何實現增刪改查以及文件的上傳下載操作。本篇文章將介紹一下,調用restful的權限認證的內容。在調用的接口,為了安全,總會需要對請求進行權限認證的。以防一些非法的操作。

系列文章

Restful風格wcf調用

Restful風格wcf調用2——增刪改查

Restful風格wcf調用3——Stream

一個例子

在REST WCF中,我們可以利用 HttpHeader 來完成這一目標。

首先我們添加一個校驗身份的一個方法。

        /// <summary>
        /// 校驗是否有權限訪問
        /// </summary>
        /// <returns></returns>
        private bool CheckIsCheckAuthorization()
        {
            //獲得當前web操作上下文
            WebOperationContext woc = WebOperationContext.Current;
            //獲得當前請求頭中的Authorization
            var auth = woc.IncomingRequest.Headers[System.Net.HttpRequestHeader.Authorization];
            //如果auth為空,或者不等於admin/123,則響應405 MethodNotAllowed 
            if (string.IsNullOrEmpty(auth) || auth != "admin/123")
            {
                woc.OutgoingResponse.StatusCode = System.Net.HttpStatusCode.MethodNotAllowed;
                return false;
            }
            return true;

        }

 然后,在每個接口中,加上權限認證的語句。

        /// <summary>
        /// 獲得所有的用戶信息
        /// </summary>
        /// <returns>json或者xml</returns>
        public List<UserInfo> QueryList()
        {
            if (CheckIsCheckAuthorization())
            {
                return new List<UserInfo>() 
                { 
                    new UserInfo() { ID = 1, Name = "wofly", Age = 22, Birthday = DateTime.Now, Gender = true }, 
                    new UserInfo() { ID = 2, Name = "san zhang", Age = 21, Birthday = DateTime.Now, Gender = true }, 
                    new UserInfo() { ID = 3, Name = "wukong sun", Age = 23, Birthday = DateTime.Now, Gender = false }, 
                    new UserInfo() { ID = 4, Name = "zi ma", Age = 45, Birthday = DateTime.Now, Gender = true }
                 };
            }
            else
            {
                return null;
            }
        }

在瀏覽器中瀏覽,http://localhost:21074/userInfo/api/users

我們現在使用postman模擬請求,進行驗證,如圖所示:

這樣,就對可以控制對接口的訪問,只有有權限的用戶才可以訪問。但是,問題來了,有那么多的方法,每個方法都要加上那么一句權限的認證,看起來相當的繁瑣。這里介紹一種高大上的方式。通過在WebServiceHostFactory中的攔截請求上下文中Authorization可以做到。

    public class SecureWebServiceHostFactory : System.ServiceModel.Activation.WebServiceHostFactory
    {
        public override System.ServiceModel.ServiceHostBase CreateServiceHost(string constructorString, Uri[] baseAddresses)
        {
            var host= base.CreateServiceHost(constructorString, baseAddresses);
            //在這里,攔截驗證
            host.Authorization.ServiceAuthorizationManager = new MyServiceAuthorizationManager();  
            return host;
        }
        protected override System.ServiceModel.ServiceHost CreateServiceHost(Type serviceType, Uri[] baseAddresses)
        {
            var host = base.CreateServiceHost(serviceType, baseAddresses);
            //在這里,攔截驗證
            host.Authorization.ServiceAuthorizationManager = new MyServiceAuthorizationManager();
            return host;
        }
    }
    /// <summary>
    /// 自定義驗證方式
    /// </summary>
    public class MyServiceAuthorizationManager : ServiceAuthorizationManager
    {
        protected override bool CheckAccessCore(OperationContext operationContext)
        {
            var woc = System.ServiceModel.Web.WebOperationContext.Current;
            var auth = woc.IncomingRequest.Headers[HttpRequestHeader.Authorization];
            if (string.IsNullOrEmpty(auth) || auth != "admin/123")
            {
                woc.OutgoingResponse.StatusCode = HttpStatusCode.MethodNotAllowed;
                return false;
            }
            return true;
        }
    }

然后,在注冊路由的時候,做一下修改:

    public class Global : System.Web.HttpApplication
    {
        protected void Application_Start(object sender, EventArgs e)
        {
            //注冊路由
            System.Web.Routing.RouteTable.Routes.Add(
                new System.ServiceModel.Activation.ServiceRoute(
                    "userInfo",
                    new SecureWebServiceHostFactory(), typeof(UserService)
                ));
            //注冊路由
            System.Web.Routing.RouteTable.Routes.Add(new System.ServiceModel.Activation.ServiceRoute(
                "imageService", new System.ServiceModel.Activation.WebServiceHostFactory(), typeof(ImageService)));
        }
    }

上面代碼中,紅色的部分,就是自定義的認證的類。
現在我們使用postman模擬請求,進行一下驗證,

總結

好了,關於restful風格wcf的使用方式,就介紹到這里,希望對你有所幫助。

參考文章:

http://blog.csdn.net/fangxing80/article/details/6263780


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM