I am looking to authenticate a user from a client application while using the ASP.NET Web API. I have watched all the videos on the site and also read this forum post.
Putting the [Authorize] attribute correctly returns a 401 Unauthorized status. However, I need to know how to allow a user to log in to the API.
I want to provide user credentials from an Android application to the API, get the user logged in, and then have all subsequent API calls pre-authenticated.
You need to send a valid Forms Authentication cookie along with the request. This cookie is usually sent by the server when authenticating (
LogOnaction) by calling the[FormsAuthentication.SetAuthCookiemethod (see MSDN).So the client needs to perform 2 steps:
LogOnaction by sending the username and password. In turns this action will call theFormsAuthentication.SetAuthCookiemethod (in case the credentials are valid) which in turn will set the forms authentication cookie in the response.[Authorize]protected action by sending along the forms authentication cookie it retrieved in the first request.Let’s take an example. Suppose that you have 2 API controllers defined in your web application:
The first one responsible for handling authentication:
and the second one containing protected actions that only authorized users can see:
Now we could write a client application consuming this API. Here’s a trivial console application example (make sure you have installed the
Microsoft.AspNet.WebApi.ClientandMicrosoft.Net.HttpNuGet packages):And here’s how the 2 HTTP requests look on the wire:
Authentication request:
Authentication response:
Request for protected data:
Response for protected data: