简体   繁体   中英

Web request to .NET Web Api Service gets 401 unauthorized error

I have a web api service that I want another .Net app to make a web request to, however I'm getting the following error when doing so:

"The remote server returned an error: (401) Unauthorized."

Just to clarify, these are 2 separate .net apps that are trying to communicate.

Here's the code for the client .Net c# app trying to make the web request to the other web api service:

    public string MakeWebRequest()
    {
        var requestUrl = "http://localhost:8081/api/Tests/results";

        var request = WebRequest.Create(requestUrl);
        var username = "test";
        var password = "test";
        SetBasicAuthHeader(request, username, password);

        var postData = "thing1=hello";
        postData += "&thing2=world";
        var data = Encoding.ASCII.GetBytes(postData);

        request.Method = "POST";
        request.ContentType = "application/json";
        request.ContentLength = data.Length;
        //request.Expect = "application/json";

        using (var stream = request.GetRequestStream())
        {
            stream.Write(data, 0, data.Length);
        }

        string text;
        var response = (HttpWebResponse)request.GetResponse();

        using (var sr = new StreamReader(response.GetResponseStream()))
        {
            text = sr.ReadToEnd();
        }

        return null;
    }

    public static void SetBasicAuthHeader(WebRequest request, String userName, String userPassword)
    {
        string authInfo = userName + ":" + userPassword;
        authInfo = Convert.ToBase64String(Encoding.Default.GetBytes(authInfo));
        request.Headers["Authorization"] = "Basic " + authInfo;
    }

And here's the code of the .Net c# web api service that should receive the web request from the other app:

[RoutePrefix("api/Tests")]
public class TestsApiController : ApiController
{
  [POST("results")]
  [AcceptVerbs("POST")]
  [HttpPost]
  [BasicAuthAuthorize(Roles="Admin")]
  public JObject resultsFinished()
  {
    //do something
  }
}

And here's the Basic Auth Attribute I created, which doesn't even get hit from the client service.

public class BasicAuthAuthorizeAttribute : AuthorizeAttribute
{
    private const string BasicAuthResponseHeader = "WWW-Authenticate";
    private const string BasicAuthResponseHeaderValue = "Basic";

    public override void OnAuthorization(HttpActionContext actionContext)
    {
        try
        {
            AuthenticationHeaderValue authValue = actionContext.Request.Headers.Authorization;

            if (authValue != null && !String.IsNullOrWhiteSpace(authValue.Parameter) && authValue.Scheme == BasicAuthResponseHeaderValue)
            {
                var parsedCredentials = ParseAuthorizationHeader(authValue.Parameter);

                if (parsedCredentials != null)
                {
                    if (parsedCredentials.Username == IoC.Username && parsedCredentials.Password == IoC.Password)
                        return;
                }
            }
        }
        catch (Exception)
        {
            //actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized);
            actionContext.Response.Headers.Add(BasicAuthResponseHeader, BasicAuthResponseHeaderValue);
            return;

        }
    }

    private Credentials ParseAuthorizationHeader(string authHeader)
    {
        string[] credentials = Encoding.ASCII.GetString(Convert.FromBase64String(authHeader)).Split(new[] { ':' });

        if (credentials.Length != 2 || string.IsNullOrEmpty(credentials[0]) || string.IsNullOrEmpty(credentials[1]))
            return null;

        return new Credentials() { Username = credentials[0], Password = credentials[1], };
    }
}
//Client credential
public class Credentials
{
    public string Username { get; set; }
    public string Password { get; set; }
}

Try using a tool like fiddler to troubleshoot what is being sent to the web service:

http://www.telerik.com/fiddler

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM