4

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 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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.

2 Comments

Technically, this might work, but only because instantiating a controller like a regular class (rather than going through the request-pipeline) skirts around some attributes like Authorize (since it works in the context of the request-pipeline). However, doing it in this way, you're going to have issues if you rely on authentication (i.e User) in the action at all.
It would be far better to factor out the code in the Web Api actions into a class library, which then both the Web Api and the MVC project can utilize, rather than trying to use the Web Api directly outside of the request pipeline.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.