码迷,mamicode.com
首页 > Windows程序 > 详细

关于ASP.NET Web API 客户端的请求报文中添加 Authorization

时间:2014-09-18 13:12:03      阅读:204      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   color   io   os   使用   ar   div   

当你使用客户端发送请求 Web API 的时候,因为API 有验证,所以你的请求报文中必须有”Authorization“,那么就需要手动添加了!

HttpClient client = new HttpClient();
client.BaseAddress = new Uri("http://localhost:9014/");
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
//设置请求  Authorization: Basic eXN0Omp1bGk=      Base64 加密的     (yst:juli)
//System.Net.Http.Headers.AuthenticationHeaderValue authValue = new AuthenticationHeaderValue("Basic", "eXN0Omp1bGk=");
//13e6ba0ee6f8559324efe6a3c51909f1      自定义加密的
System.Net.Http.Headers.AuthenticationHeaderValue authValue = new AuthenticationHeaderValue("ystJS", "13e6ba0ee6f8559324efe6a3c51909f1");
client.DefaultRequestHeaders.Authorization = authValue;       

 

服务器端进行验证

bubuko.com,布布扣
public class ReqAuthorizeAttribute:System.Web.Http.AuthorizeAttribute
{
        /// <summary>
        /// 进行验证
        /// </summary>
        /// <param name="actionContext"></param>
        public override void OnAuthorization(System.Web.Http.Controllers.HttpActionContext actionContext)
        {
            if (actionContext.Request.Headers.Authorization != null)
            {
                //获取请求的 认证信息(解密)  13e6ba0ee6f8559324efe6a3c51909f1
                string authPa = (actionContext.Request.Headers.Authorization.Parameter).Decrypt();

                string userInfo = "yst:juli";
                //判断认证信息是否正确
                if (string.Equals(authPa, userInfo))
                {
                    IsAuthorized(actionContext);
                }
                else
                {
                    HandleUnauthorizedRequest(actionContext);
                }
            }
            else
            {
                HandleUnauthorizedRequest(actionContext);
            }
        }

        /// <summary>
        /// 验证不通过 返回401
        /// </summary>
        /// <param name="actionContext"></param>
        protected override void HandleUnauthorizedRequest(System.Web.Http.Controllers.HttpActionContext actionContext)
        {
            var challengeMsg = new System.Net.Http.HttpResponseMessage(System.Net.HttpStatusCode.Unauthorized);
            challengeMsg.Headers.Add("WWW-Authenticate", "Basic");
            throw new System.Web.Http.HttpResponseException(challengeMsg);
        }

}
View Code

 

关于ASP.NET Web API 客户端的请求报文中添加 Authorization

标签:style   blog   http   color   io   os   使用   ar   div   

原文地址:http://www.cnblogs.com/yougmi/p/3978958.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!