How to use authentication with MVC Web API?

13,069

Solution 1

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.

Solution 2

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.

Share:
13,069

Related videos on Youtube

Ron Deijkers
Author by

Ron Deijkers

Freelance .NET software engineer & practical software architect

Updated on July 08, 2022

Comments

  • Ron Deijkers
    Ron Deijkers almost 2 years

    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?