简体   繁体   English

如何通过HTTP标头使用基本身份验证从ipad应用程序调用Web api服务?

[英]how to call web api service from ipad application using basic authentication through http headers?

Please give me a sample code to set http headers for web api service. 请给我一个示例代码来设置Web api服务的http标头。

i developed basic authentication. 我开发了基本身份验证。

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!";
      }

   }

so i need to call web api service from ipad application using basic http headers (objective c). 因此,我需要使用基本的HTTP标头(目标c)从ipad应用程序调用Web api服务。

Advance Thanks. 提前谢谢。

I think this can help you understand it well. 我认为这可以帮助您很好地理解它。

    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];
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 具有基本身份验证的iOS快速Web服务调用 - iOS swift web service call with basic authentication 使用基本HTTP身份验证访问Web服务器? - Accessing web server using Basic HTTP authentication? iOS 7上的Web应用程序中的HTTP基本身份验证损坏了吗 - Broken HTTP basic authentication in web apps on iOS 7? 如何使用基本身份验证保护Android / ios应用程序的Web API - How to secure Web API for android/ios apps with basic authentication 我有一个Objective-C iPad应用程序,该应用程序进行Web服务调用失败,如下所示: - I have an Objective-C iPad application that makes a web service call which is failing as follows: 如何判断HTTP API请求是否来自iPad - How to determine whether HTTP API request came from iPad iPad应用程序-如何使用手指滑动来终止服务器呼叫 - iPad application - how to kill server call using finger swipe iOS如何使用RESTFUL API从Web服务检索数据 - IOS how to retrieve data from web service using RESTFUL API 如何在AVURLAsset中处理HTTP基本身份验证? - How to handle HTTP Basic Authentication in AVURLAsset? 如何从 Web 服务调用解释 json - how to interpret json from web service call
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM