5

I'm trying to configure authentication for an MVC Web API that is accessed by another MVC site. I have tried many things in the web.config, many suggestions from SO. However all to no avail.

I am using the following code from the MVC website:

var web = new WebClient();
web.UseDefaultCredentials = false;
web.Credentials = new NetworkCredential(username, password);

I then use that web client to invoke methods on the other MVC site that only contains API controllers. Without authentication everything works like it should but I can't get authentication to work. When making the request I get an exception that a 401 is returned (which is a good thing if you ask me but it doesn't appear to send the credentials).

I also tried to put the username and password in the URL but that didn't work either.

Here is the relevant section of the web.config file of the Web API site:

    <authentication>
      <forms 
        cookieless="UseUri"
        enableCrossAppRedirects="false">
        <credentials passwordFormat="Clear">
          <user name="site" password="XYZ123!"/>
        </credentials>
      </forms>
    </authentication>
    <authorization>
      <deny users="?"/>
    </authorization>

I want to put a single username/password there just to make sure that it is the website that is invoking methods. My API controllers have the 'Authorize' attribute btw.

My question is: how can I add authentication to the Web API site so that I can invoke methods on it using authentication?

Ron Deijkers
  • 2,791
  • 2
  • 22
  • 28

2 Answers2

5

Use Basic authentication. You can create a AuthorizationAttribute that validates the username/password in the Authorization header and returns a 401 response when not authorized.

See this post for more information.

Carles Company
  • 7,118
  • 5
  • 49
  • 75
1

You could use basic authentication instead of forms authentication as I illustrated in this answer. There are also other ways of authentication possible. For example token based authentication as shown in this blog post.

Community
  • 1
  • 1
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928