简体   繁体   中英

Why my web api return Status code 401 when i use WebClient class and Status code 200 when i use HttpWebResponse?

So i am fairly new to this word, so excuse me if i am missing something.

I've wrote a Web Api in Asp.Net.Core 2.2 which use jwt token for authorizazion. My Authenticate method looks like this:

    [AllowAnonymous]
    [HttpGet("auth")]
    public ActionResult<SecurityToken> Auth([FromHeader] string identity)
    {
        // authentication successful so generate jwt token
        //if (HwKeyManager.MASTER_KEY.KEY_NOT_PRESENT)
        //{
        //    //hasLicense = HwKeyManager.product_license_get();
        //}
        var tokenHandler = new JwtSecurityTokenHandler();
        var key = Encoding.ASCII.GetBytes(someKey);
        var tokenDescriptor = new SecurityTokenDescriptor
        {
            Subject = new ClaimsIdentity(new Claim[]
            {
                new Claim(ClaimTypes.Name, identity)
            }),
            Expires = DateTime.Now.AddMinutes(10),
            SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
        };
        try
        {
            SecurityToken token = tokenHandler.CreateToken(tokenDescriptor);
            string returnToken = tokenHandler.WriteToken(token);
            return Ok(returnToken);
        }
        catch(Exception ex)
        {
            logger.Error("Error while creating token : " + ex.Message);
            return StatusCode(500);
        }
    }

this works and give me a token which i used with success in a request like the following:

 HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url + "status");
 request.Timeout = 15000;
 request.Headers.Add("Authorization", "Bearer " + token);
 using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
 {
    if (response.StatusCode == HttpStatusCode.OK)
    {
       return true;
    }
    else
    {
       return false;
    }

 }

However for another method i was trying to use the WebClient class to create a POST request, but for the life of me i can't make the following piece of code to work (i get a 401 status code, Unauthorized)

WebClient wcl = new WebClient();
wcl.Headers.Add(HttpRequestHeader.ContentType, "application/json");
wcl.Headers.Add("Authorization", "Bearer" + token);
wcl.Encoding = System.Text.Encoding.UTF8;
string pippo = wcl.UploadString(url + "doSomething", "POST", Data.ToJson());

if i switch to HttpWebResponse however everything work

byte[] bytes = Encoding.ASCII.GetBytes(Data.ToJson());
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url + "doSomething");
request.Timeout = 15000;
request.Headers.Add("Authorization", "Bearer " + token);
request.Method = "POST";
request.ContentType = "application/json";
Stream dataStream = request.GetRequestStream();
dataStream.Write(bytes, 0, bytes.Length);
dataStream.Close();
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
    if (response.StatusCode == HttpStatusCode.OK)
    {

    }
    else
    {

    }

}

Can someone clarify me why this happen and if there is a way to solve it?

You have forgoten a space between bearer.

wcl.Headers.Add("Authorization", "Bearer" + token);

So just change it to this

wcl.Headers.Add("Authorization", "Bearer " + token);

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