0

I'm trying to setting my Jwt token in C# code.

 [HttpPost]
    public IActionResult TestPOST ()
    {
        var token = "myExampleJwtTokenNormallyIGrabItFromOtherFunction";
        var client = new HttpClient();
        client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", token);
        return Ok();
    }

This method just return Ok(), but Authorization is not setting. And I still have 401 http error. I cannot figured out what can be wrong here. I read that should I use

client.DefaultRequestHeaders.TryAddWithoutValidation("Authorization", "Bearer " + token);

but it still does not work. How should I set header? Have anyone any idea?

  • just to be clear Are you trying to send back generated JWT to a client – Mihir Dave Jan 15 '19 at 14:05
  • @MihirDave I just want to set this token in authorization like I do that during testing API with Postman (here is screenshot imgur.com/a/c4YHn36). Am I totally wrong with what I want to accomplish? – user10523325 Jan 15 '19 at 14:11
  • so you set URL in postman like what's your endpoint E.g.(https://abx.com/api/GetData) but I don't see you are setting this in your code so is there any reason you are doing this or I am not understanding your purpose – Mihir Dave Jan 15 '19 at 14:17
  • I just want to add authorization in my App, I'm pretty newbie so I do not exactly know how I can do that. During testing API in postman I just paste my before generated token in header and it works fine. Here I have no idea, How I can using generated token in my App to get access to others controllers which are Authorizated. Apologize my English I'm not a native speaker. This code above it just something like pseudocode. – user10523325 Jan 15 '19 at 14:27
  • so You create a token for user when request comes in. you copy this token manually somehow and put that in postman and your controllers answer. am i right? – Mihir Dave Jan 15 '19 at 14:30
  • Yes exactly like you said – user10523325 Jan 15 '19 at 14:32
  • Then you are going on the wrong path buddy. you don't have to add authorization header on webapi side. you have to add that on client side. whether you are using plain ajax request or you are using angular or vue. – Mihir Dave Jan 15 '19 at 14:34
  • @MihirDave I understand, thank you so much I really appreciated. – user10523325 Jan 15 '19 at 14:38

0 Answers0