Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use authentication with MVC Web API?

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?

like image 472
Ron Deijkers Avatar asked Nov 24 '13 15:11

Ron Deijkers


2 Answers

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.

like image 58
Carles Company Avatar answered Sep 30 '22 19:09

Carles Company


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.

like image 40
Darin Dimitrov Avatar answered Sep 30 '22 21:09

Darin Dimitrov