Ios 如何通过http头使用基本身份验证从ipad应用程序调用web api服务?

Ios 如何通过http头使用基本身份验证从ipad应用程序调用web api服务?,ios,objective-c,ipad,http-headers,Ios,Objective C,Ipad,Http Headers,请给我一个示例代码来设置web api服务的http头 我开发了基本的身份验证 public class BasicAuthenticationFilter : AuthorizationFilterAttribute { bool Active = true; public BasicAuthenticationFilter() { } /// <summary> /// Overriden

请给我一个示例代码来设置web api服务的http头

我开发了基本的身份验证

public class BasicAuthenticationFilter : AuthorizationFilterAttribute
    {
        bool Active = true;

        public BasicAuthenticationFilter()
        { }

        /// <summary>
        /// Overriden constructor to allow explicit disabling of this
        /// filter's behavior. Pass false to disable (same as no filter
        /// but declarative)
        /// </summary>
        /// <param name="active"></param>
        public BasicAuthenticationFilter(bool active)
        {
            Active = active;
        }


        /// <summary>
        /// Override to Web API filter method to handle Basic Auth check
        /// </summary>
        /// <param name="actionContext"></param>
        public override void OnAuthorization(HttpActionContext actionContext)
        {
            if (Active)
            {
                var identity = ParseAuthorizationHeader(actionContext);
                if (identity == null)
                {
                    //Challenge(actionContext);
                   actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized);
                    return;
                }


                if (!OnAuthorizeUser(identity.Name, identity.Password, actionContext))
                {
                    Challenge(actionContext);
                    return;
                }

                var principal = new GenericPrincipal(identity, null);

                Thread.CurrentPrincipal = principal;

                // inside of ASP.NET this is required
                //if (HttpContext.Current != null)
                //    HttpContext.Current.User = principal;

                base.OnAuthorization(actionContext);
            }
        }

        /// <summary>
        /// Base implementation for user authentication - you probably will
        /// want to override this method for application specific logic.
        /// 
        /// The base implementation merely checks for username and password
        /// present and set the Thread principal.
        /// 
        /// Override this method if you want to customize Authentication
        /// and store user data as needed in a Thread Principle or other
        /// Request specific storage.
        /// </summary>
        /// <param name="username"></param>
        /// <param name="password"></param>
        /// <param name="actionContext"></param>
        /// <returns></returns>
        protected virtual bool OnAuthorizeUser(string username, string password, HttpActionContext actionContext)
        {
            if (string.IsNullOrEmpty(username) || string.IsNullOrEmpty(password))
                return false;

            return true;
        }

        /// <summary>
        /// Parses the Authorization header and creates user credentials
        /// </summary>
        /// <param name="actionContext"></param>
        protected virtual BasicAuthenticationIdentity ParseAuthorizationHeader(HttpActionContext actionContext)
        {
            string authHeader = null;
            var auth = actionContext.Request.Headers.Authorization;
            if (auth != null && auth.Scheme == "Basic")
                authHeader = auth.Parameter;

            if (string.IsNullOrEmpty(authHeader))
                return null;

            authHeader = Encoding.Default.GetString(Convert.FromBase64String(authHeader));

            var tokens = authHeader.Split(':');
            if (tokens.Length < 2)
                return null;

            return new BasicAuthenticationIdentity(tokens[0], tokens[1]);
        }


        /// <summary>
        /// Send the Authentication Challenge request
        /// </summary>
        /// <param name="message"></param>
        /// <param name="actionContext"></param>
        void Challenge(HttpActionContext actionContext)
        {
            var host = actionContext.Request.RequestUri.DnsSafeHost;
            actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized);
            actionContext.Response.Headers.Add("WWW-Authenticate", string.Format("Basic realm=\"{0}\"", host));
        }
    }
    public class BasicAuthenticationIdentity : GenericIdentity
    {
        public BasicAuthenticationIdentity(string name, string password)
            : base(name, "Basic")
        {
            this.Password = password;
        }

        /// <summary>
        /// Basic Auth Password for custom authentication
        /// </summary>
        public string Password { get; set; }
    }
    public class BasicAuthCredentials
    {
        public string Username { get; set; }
        public string Password { get; set; }
    }

[BasicAuthenticationFilter]
public class SampleController : ApiController
    {

      public string Get()
      {
           return "Hai Authentication successfully done!";
      }

   }
公共类基本身份验证筛选器:AuthorizationFilterAttribute
{
bool Active=true;
公共基本身份验证筛选器()
{ }
/// 
///重写构造函数以允许显式禁用此
///过滤器的行为。传递false以禁用(与无过滤器相同
///但是声明性的)
/// 
/// 
公共基本身份验证筛选器(bool活动)
{
主动=主动;
}
/// 
///重写Web API筛选器方法以处理基本身份验证检查
/// 
/// 
授权时的公共覆盖无效(HttpActionContext actionContext)
{
如果(活动)
{
var identity=ParseAuthorizationHeader(actionContext);
if(identity==null)
{
//挑战(行动背景);
actionContext.Response=actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized);
返回;
}
如果(!OnAuthorizeUser(identity.Name、identity.Password、actionContext))
{
挑战(行动背景);
返回;
}
var principal=新的GenericPrincipal(标识,null);
Thread.CurrentPrincipal=主体;
//在ASP.NET内部,这是必需的
//if(HttpContext.Current!=null)
//HttpContext.Current.User=主体;
基于授权(actionContext);
}
}
/// 
///用户身份验证的基本实现-您可能会
///要为特定于应用程序的逻辑重写此方法。
/// 
///基本实现仅检查用户名和密码
///呈现并设置线程主体。
/// 
///如果要自定义身份验证,请重写此方法
///并根据需要以线程原理或其他方式存储用户数据
///请求特定存储。
/// 
/// 
/// 
/// 
/// 
受保护的虚拟bool OnAuthorizeUser(字符串用户名、字符串密码、HttpActionContext actionContext)
{
if(string.IsNullOrEmpty(用户名)| | string.IsNullOrEmpty(密码))
返回false;
返回true;
}
/// 
///解析授权标头并创建用户凭据
/// 
/// 
受保护的虚拟基本身份验证身份解析授权标头(HttpActionContext actionContext)
{
字符串authHeader=null;
var auth=actionContext.Request.Headers.Authorization;
if(auth!=null&&auth.Scheme==“基本”)
authHeader=auth.Parameter;
if(string.IsNullOrEmpty(authHeader))
返回null;
authHeader=Encoding.Default.GetString(Convert.FromBase64String(authHeader));
var-tokens=authHeader.Split(“:”);
如果(标记长度<2)
返回null;
返回新的基本身份验证身份(令牌[0],令牌[1]);
}
/// 
///发送身份验证质询请求
/// 
/// 
/// 
无效挑战(HttpActionContext-actionContext)
{
var host=actionContext.Request.RequestUri.DnsSafeHost;
actionContext.Response=actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized);
actionContext.Response.Headers.Add(“WWW-Authenticate”,string.Format(“基本领域=\”{0}\”,主机));
}
}
公共类基本身份验证身份:GenericEntity
{
公共基本身份验证身份(字符串名称、字符串密码)
:base(名称“Basic”)
{
this.Password=密码;
}
/// 
///自定义身份验证的基本身份验证密码
/// 
公共字符串密码{get;set;}
}
公共类基本凭据
{
公共字符串用户名{get;set;}
公共字符串密码{get;set;}
}
[基本身份验证筛选器]
公共类采样控制器:ApiController
{
公共字符串Get()
{
返回“Hai身份验证成功完成!”;
}
}
所以我需要使用基本http头(objective c)从ipad应用程序调用web api服务


提前谢谢。

我想这可以帮助你更好地理解它

    NSString *soapMessage=[NSString stringWithFormat:@"<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"
                           "<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">\n"
                           "<soap:Body>\n"
                           "</soap:Body>\n"
                           "</soap:Envelope>\n", URL_Temp,];



    NSURL *tmpURl=[NSURL URLWithString:[NSString stringWithFormat:@"%s/%s", URL_Main, URL_Service]];

    NSMutableURLRequest *theRequest=[NSMutableURLRequest requestWithURL:tmpURl];
    [theRequest addValue:@"text/xml; charset=utf-8" forHTTPHeaderField:@"Content-Type"];

    NSString *msgLength=[NSString stringWithFormat:@"%i",[soapMessage length]];
    [theRequest addValue:msgLength forHTTPHeaderField:@"Content-Length"];
    [theRequest setHTTPMethod:@"POST"];

    [theRequest setHTTPBody:[soapMessage dataUsingEncoding:NSUTF8StringEncoding]];
    con=[[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
    if(con)
    {
        webdata=[[NSMutableData data] retain];
    }
NSString*soapMessage=[NSString stringWithFormat:@“\n”
“\n”
“\n”
“\n”
“\n”,URL_Temp,];
NSURL*tmpURl=[NSURL URLWithString:[NSString stringWithFormat:@“%s/%s”,URL\u Main,URL\u Service]];
NSMutableURLRequest*theRequest=[NSMutableUrlRequestWithURL:tmpURl];
[theRequest addValue:@“text/xml;charset=utf-8”用于HttpHeaderField:@“Content Type”];
NSString*msgLength=[NSString stringWithFormat:@“%i”,[soapMessage length]];
[theRequest addValue:msgLength for HttpHeaderField:@“内容长度”];
[TheRequestSetHttpMethod:@“POST”];
[TheRequestSetHttpBody:[soapMessage数据使用编码:NSUTF8StringEncoding];
con=[[NSURLConnection alloc]initWithRequest:theRequest委托:self];
如果(con)
{
webdata=[[NSMutableData]保留];
}

我认为这可以帮助您更好地理解它

    NSString *soapMessage=[NSString stringWithFormat:@"<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"
                           "<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">\n"
                           "<soap:Body>\n"
                           "</soap:Body>\n"
                           "</soap:Envelope>\n", URL_Temp,];



    NSURL *tmpURl=[NSURL URLWithString:[NSString stringWithFormat:@"%s/%s", URL_Main, URL_Service]];

    NSMutableURLRequest *theRequest=[NSMutableURLRequest requestWithURL:tmpURl];
    [theRequest addValue:@"text/xml; charset=utf-8" forHTTPHeaderField:@"Content-Type"];

    NSString *msgLength=[NSString stringWithFormat:@"%i",[soapMessage length]];
    [theRequest addValue:msgLength forHTTPHeaderField:@"Content-Length"];
    [theRequest setHTTPMethod:@"POST"];

    [theRequest setHTTPBody:[soapMessage dataUsingEncoding:NSUTF8StringEncoding]];
    con=[[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
    if(con)
    {
        webdata=[[NSMutableData data] retain];
    }
NSString*soapMessage=[NSString stringWithFormat:@“\n”
“\n”
“\n”
“\n”
“\n”,URL_Temp,];
NSURL