locked
Web API from code behind needing to Authenticate RRS feed

  • Question

  • User1595993364 posted

    I am calling a web api with this code:

    using (var client = new HttpClient())
    {
         client.BaseAddress = new Uri(URL);
         client.DefaultRequestHeaders.Accept.Clear();
         client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
    
         HttpResponseMessage response = await client.GetAsync(api + Param);
         if (response.IsSuccessStatusCode)
         {
              Incident inc = await response.Content.ReadAsAsync<Incident>();
              Console.WriteLine("{0}\t${1}", inc.ID, inc.Desc);
         }
    }

    I need to be able to authenticate, can someone please assist with showing me the proper process of authenticating from code behind without User Input?

    Thanks,

    Monday, June 22, 2015 11:23 AM

Answers

  • User-782957977 posted

    Please refer following links, if you are using Web Api Individual Account Authentication

    http://forums.asp.net/t/2037968.aspx?UI+for+Login+and+Registration
    http://forums.asp.net/t/2052185.aspx?WebAPI+individual+account+register+and+authent+works+get+fails

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Monday, June 22, 2015 8:05 PM
  • User438962230 posted

    Hi Robert,

    If you mean you've already had a WebAPI application which needs authentication for the client to access the resources, and now you want to use HttpClient to authenticate to get some information from it, you need to firstly figure out what kind of authentication does this WebAPI support.

    1. If the client application and the WebAPI are in the same domain, and the WebAPI uses Windows Authentication, you just need to use the default credentials:

    var httpClientHandler = new HttpClientHandler() { 
                    UseDefaultCredentials=true;
                };
                var httpClient = new HttpClient(httpClientHandler);

    Integrated Windows Authentication

    2. If the WebAPI uses Basic Authentication, then you need to set the Authorization header in the HttpClient's request:

    using (var client = new HttpClient())
    {
        var authHeader = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(System.Text.ASCIIEncoding.GetBytes(string.format("{0}:{1}", "username", "password"))));
        client.DefaultRequestHeaders.Authorization = authHeader;
    }
    

    For more information about Basic Authentication, please see:

    Basic Authentication in ASP.NET Web API

    Authentication Filters in ASP.NET Web API 2

    3. If the WebAPI uses token-based oauth authentication, then you need to follow the oauth convensions, post the related information to the authorization server firstly to get the access_token, then set this access_token to the Authorization header in the HttpClient's request to get the information you want from the WebAPI.

    For example, use this code snippet to get the access_token:

    using (var client = new HttpClient())
                {
                    client.BaseAddress = new Uri("http://localhost:8080");
                    var content = new FormUrlEncodedContent(new[] 
                    {
                        new KeyValuePair<string, string>("grant_type", "password"),
                        new KeyValuePair<string, string>("username", "username"),
                        new KeyValuePair<string, string>("password", "password")
                    });
                    var result = client.PostAsync("/Token", content).Result;
                    string resultContent = result.Content.ReadAsStringAsync().Result;
                    //resolve the access_token here for the later use
                }

    To get the resources from the WebAPI, set the access_token in the request header of HttpClient like this:

    client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);

    For more information about token-based authentication, please see this article:

    Secure a Web API with Individual Accounts and Local Login in ASP.NET Web API 2.2

    4. Forms Authentication is usually used in the web application as the client, see the article here:

    Forms Authentication in ASP.NET Web API

    If you want to firstly build the authorization server, the above links in my reply can also help you.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Wednesday, June 24, 2015 8:51 AM

All replies

  • User2024324573 posted

    You can use authentication filters within your action i.e. before the start of the actions.

    See details at: http://www.asp.net/web-api/overview/security/authentication-filters

    Hope this will help.

    Monday, June 22, 2015 4:19 PM
  • User-782957977 posted

    Please refer following links, if you are using Web Api Individual Account Authentication

    http://forums.asp.net/t/2037968.aspx?UI+for+Login+and+Registration
    http://forums.asp.net/t/2052185.aspx?WebAPI+individual+account+register+and+authent+works+get+fails

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Monday, June 22, 2015 8:05 PM
  • User438962230 posted

    Hi Robert,

    If you mean you've already had a WebAPI application which needs authentication for the client to access the resources, and now you want to use HttpClient to authenticate to get some information from it, you need to firstly figure out what kind of authentication does this WebAPI support.

    1. If the client application and the WebAPI are in the same domain, and the WebAPI uses Windows Authentication, you just need to use the default credentials:

    var httpClientHandler = new HttpClientHandler() { 
                    UseDefaultCredentials=true;
                };
                var httpClient = new HttpClient(httpClientHandler);

    Integrated Windows Authentication

    2. If the WebAPI uses Basic Authentication, then you need to set the Authorization header in the HttpClient's request:

    using (var client = new HttpClient())
    {
        var authHeader = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(System.Text.ASCIIEncoding.GetBytes(string.format("{0}:{1}", "username", "password"))));
        client.DefaultRequestHeaders.Authorization = authHeader;
    }
    

    For more information about Basic Authentication, please see:

    Basic Authentication in ASP.NET Web API

    Authentication Filters in ASP.NET Web API 2

    3. If the WebAPI uses token-based oauth authentication, then you need to follow the oauth convensions, post the related information to the authorization server firstly to get the access_token, then set this access_token to the Authorization header in the HttpClient's request to get the information you want from the WebAPI.

    For example, use this code snippet to get the access_token:

    using (var client = new HttpClient())
                {
                    client.BaseAddress = new Uri("http://localhost:8080");
                    var content = new FormUrlEncodedContent(new[] 
                    {
                        new KeyValuePair<string, string>("grant_type", "password"),
                        new KeyValuePair<string, string>("username", "username"),
                        new KeyValuePair<string, string>("password", "password")
                    });
                    var result = client.PostAsync("/Token", content).Result;
                    string resultContent = result.Content.ReadAsStringAsync().Result;
                    //resolve the access_token here for the later use
                }

    To get the resources from the WebAPI, set the access_token in the request header of HttpClient like this:

    client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);

    For more information about token-based authentication, please see this article:

    Secure a Web API with Individual Accounts and Local Login in ASP.NET Web API 2.2

    4. Forms Authentication is usually used in the web application as the client, see the article here:

    Forms Authentication in ASP.NET Web API

    If you want to firstly build the authorization server, the above links in my reply can also help you.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Wednesday, June 24, 2015 8:51 AM