0

I have an API secured by a bearer token. The API has two controllers, one is the default WeatherForecast and the second one is for handling CRUD operations for player model. I decided to get my token from WeatherForecast and use it to call player in my MVC project.

But when I start debugging, it shows Unauthorized for response in every MVC action. It's ok on using postman though.

Here are the controller methods for HttpGet and HttpPost:

namespace MyMVCProject.Controllers
{
    public class HomeController : Controller
    {
        private readonly ILogger<HomeController> _logger;
        private readonly IHttpClientFactory _clientFactory;
        
        public HomeController(ILogger<HomeController> logger, IHttpClientFactory clientFactory)
        {
            _logger = logger;
            _clientFactory = clientFactory;
        }
        
        public async Task<IActionResult> Index()
        {
            var request = new HttpRequestMessage(HttpMethod.Get, "http://localhost:42045/weatherforecast/");
            var client = _clientFactory.CreateClient();
            HttpResponseMessage response = await client.SendAsync(request);

            if (response.StatusCode == System.Net.HttpStatusCode.OK)
            {
                string token = await response.Content.ReadAsStringAsync();
                HttpContext.Session.SetString("JwtToken", token);
            }
        
            return View();
        }

        public async Task<IActionResult> GetAllPlayers()
        {
            var accessToken = HttpContext.Session.GetString("JwtToken");
            List<Player> players = new List<Player>();
            var request = new HttpRequestMessage(HttpMethod.Get, "http://localhost:42045/api/player");

            var client = _clientFactory.CreateClient();

            request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
            HttpResponseMessage response = await client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead);

            if (response.StatusCode == System.Net.HttpStatusCode.OK)
            {
                var apiString = await response.Content.ReadAsStringAsync();
                players = JsonConvert.DeserializeObject<List<Player>>(apiString);
            }

            return View(players);
        }

        [HttpPost]
        public async Task<IActionResult> AddPlayer(Player player)
        {
            var accessToken = HttpContext.Session.GetString("JwtToken");
            var request = new HttpRequestMessage(HttpMethod.Post, "http://localhost:42045/api/player/");

            if (player != null)
            {
                request.Content = new StringContent(JsonConvert.SerializeObject(player), System.Text.Encoding.UTF8, "application/json");
                request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
            }
            else
            {
                return BadRequest();
            }

            var client = _clientFactory.CreateClient();

            HttpResponseMessage response = await client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead);

            if (response.StatusCode == System.Net.HttpStatusCode.Created)
            {
                var apiString = await response.Content.ReadAsStringAsync();
                player = JsonConvert.DeserializeObject<Player>(apiString);
                TempData["success"] = "Player Added Successfully!";
            }
            else if (response.StatusCode == System.Net.HttpStatusCode.BadRequest)
            {
                TempData["badrequest"] = "Player with the same name already exists";
            }

            return View(player);
        }
    }
}
2
  • Are you sure you are getting the token correctly? Perhaps you are not parsing the JWT correctly and consequently not passing the correct Bearer token. Commented Feb 20, 2022 at 7:59
  • using breakpoint, the value of accessToken is the same as the token saved by session previously in Index action. value of headers in request.Headers.Authorization is correct (Authorization: Bearer+ token, but without space between them) and after that the response value is UnAuthorized! Commented Feb 20, 2022 at 13:28

2 Answers 2

2

HttpRequestMessage has a Headers property of type HttpRequestHeaders. This class has two Add methods you can use.

You can add headers like this:

request.Headers.Add("Authorization", "Bearer " + YourToken);
Sign up to request clarification or add additional context in comments.

4 Comments

I used your sample code, But after I ran a debugger, It showed me Bearer+ token value without any space! It must be something like Bearer token, Right? I used string.PadRight but It's still the same! I was wondering if this is the real problem for the action to reach the API
That may be because you are not passing the string correctly
What do you mean by that? I'm sure that there's something wrong with MVC-side actions, Because it works well using Postman on API as I said. What's your suggestion?
Pass Bearer with a space. That's why there is no space
0

I am using this syntax

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.