4
votes

I have a Web Api and Mvc 5 on same project. That Web Api is protected with bearer token (but I commented the SuppressDefaultHostAuthentication line, so I can access the api from browser when I am authenticated with cookie mvc)

Now I´m trying to access the api from a mvc controller without sending the token, is that possible with SuppressDefaultHostAuthentication off?

Tried that without success (401 error):

HttpClientHandler handler = new HttpClientHandler()
{
     PreAuthenticate = true,
     UseDefaultCredentials = true
};

using (var client = new HttpClient(handler))
{
     client.BaseAddress = new Uri("http://localhost:11374/");
     client.DefaultRequestHeaders.Accept.Clear();
     client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

     var response = client.GetAsync("api/MyApi").Result;
     if (response.IsSuccessStatusCode)
     {  }
}      

If its not possible, how is the best way to handle that problem?

2

2 Answers

4
votes

WebApi adheres to REST, which among other things, dictates that requests are stateless. That means with WebApi, or any REST-compatible API, there's no concept of anything such as cookies, sessions, etc. Each request to the API must contain all information needed to service the request. Therefore, if you have an endpoint that requires authentication, you must authenticate the request to access it. Period. If you're doing auth via bearer tokens, then you must pass the bearer token.

2
votes

Since the WebAPI and the MVC app are in the same project you don't need to go through HTTP and make a request in order to access a method of each one - they're neighbors :)

You can treat the WebAPI as an ordinary class and instantiate it in the MVC controller. Afterwards you call the methods on the instance as you do with any other object in your application.

However it isn't possible to avoid tokens and/or other security mechanisms the WebAPI is designed with IF you leverage a request through HTTP to access it.