C # - Error Basic Authentication WebServices REST and POST method

0

I am currently working with NetFramework 4.0 and also assigning basic authorization and I must use the following Dll System.Web.Http.Cors but I do not locate it or in the package manager of Visual Studio 2012.

The class that authenticates is the following:

using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Net.Http.Headers;
using System.Security.Principal;
using System.Text;
using System.Threading;
using System.Web;
using System.Configuration;

namespace WebAPISample.Modules
{
    public class BasicAuthHttpModule : IHttpModule
    {
        private const string Realm = "sample.local";

        public void Init(HttpApplication context)
        {
            // Register event handlers
            context.AuthenticateRequest += OnApplicationAuthenticateRequest;
            context.EndRequest += OnApplicationEndRequest;
        }

        private static void SetPrincipal(IPrincipal principal)
        {
            Thread.CurrentPrincipal = principal;
            if (HttpContext.Current != null)
            {
                HttpContext.Current.User = principal;
            }
        }

        // TODO: Here is where you would validate the username and password.
        private static bool CheckPassword(string username, string password)
        {
            bool validUser = false;

            // put your database or authentication calls here

            validUser = username == "test" && password == "test";

            return validUser;
        }

        private static bool AuthenticateUser(string credentials)
        {
            bool validated = false;
            try
            {
                var encoding = Encoding.GetEncoding("iso-8859-1");
                credentials = encoding.GetString(Convert.FromBase64String(credentials));

                int separator = credentials.IndexOf(':');
                string name = credentials.Substring(0, separator);
                string password = credentials.Substring(separator + 1);

                validated = CheckPassword(name, password);
                if (validated)
                {
                    var identity = new GenericIdentity(name);
                    SetPrincipal(new GenericPrincipal(identity, null));
                }
            }
            catch (FormatException)
            {
                // Credentials were not formatted correctly.
                validated = false;

            }
            return validated;
        }

        private static void OnApplicationAuthenticateRequest(object sender, EventArgs e)
        {
            var request = HttpContext.Current.Request;
            var authHeader = request.Headers["Authorization"];
            if (authHeader != null)
            {
                var authHeaderVal = AuthenticationHeaderValue.Parse(authHeader);

                // RFC 2617 sec 1.2, "scheme" name is case-insensitive
                if (authHeaderVal.Scheme.Equals("basic",
                        StringComparison.OrdinalIgnoreCase) &&
                    authHeaderVal.Parameter != null)
                {
                    AuthenticateUser(authHeaderVal.Parameter);
                }
            }
        }

        // If the request was unauthorized, add the WWW-Authenticate header 
        // to the response.
        private static void OnApplicationEndRequest(object sender, EventArgs e)
        {
            var response = HttpContext.Current.Response;

            // see if the request sent an X-Requested-With header (Non-Browser request - 
            // used by jQuery and Angular implementations to prevent the browser from 
            // presenting the default Login dialog)
            var request = HttpContext.Current.Request;

            string authType = "Basic";

            if (response.StatusCode == 401)
            {
                if (request.Headers.AllKeys.Contains("X-Requested-With"))
                {
                    if (request.Headers["X-Requested-With"] == "XMLHttpRequest")
                    {
                        authType = "xBasic";
                    }
                }

                response.Headers.Add("WWW-Authenticate",
                    string.Format("{0} realm=\"{1}\"", authType, Realm));
            }
        }

        public void Dispose()
        {
        }
    }
}

My configuration in web.config is:

<system.webServer>
    <modules>
      <add name="BasicAuthHttpModule" type="WebAPISample.Modules.BasicAuthHttpModule, WebAPISample"/>
    </modules>
  </system.webServer>

Finally he called from another layer with the following one with the following code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Net.Http;
using System.Web.Http;
//using System.Web.Http.Cors;

namespace AppWS
{
    [Authorize]
    //[EnableCors(origins: "*", headers: "*", methods: "*")]
    public class myService:IServicio
    {
        public EPlaca ListarVehicles(string sUsuario)
        {
            oService = new mHost.ServicioClient("Binding_IServicio");
            var rpta = oService.ListarVehicles(sUsuario);
            oService.Close();
            return rpta;
        }  
    }
}

What can I do to solve this error that only works for the GET method and not with POST, which is my case?

    
asked by DAES 22.01.2017 в 22:03
source

1 answer

1

You can add it through Nuget ... in Visual Studio, first locate in the project you want to add the dll, then go to:

  

Tools - > Nuget package manager - > Package Manager Console .

When the console opens, you write:

Install-Package Microsoft.AspNet.WebApi.Cors

Press enter. And with that the DLL would already be added to your project.

Package reference Nuget

Translated from the English site: How to include System.Web.Http.Cors reference dll in .Net Web API

    
answered by 25.01.2017 в 18:12