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.
Use this code and access database
I take android as example.
Attention please: i.localhost cannot be used. Android device look localhost as itself host. ii.If deploy the web API in IIS, the Form authentication must be opened.
You need to send a valid Forms Authentication cookie along with the request. This cookie is usually sent by the server when authenticating (
LogOn
action) by calling the[FormsAuthentication.SetAuthCookie
method (see MSDN).So the client needs to perform 2 steps:
LogOn
action by sending the username and password. In turns this action will call theFormsAuthentication.SetAuthCookie
method (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.Client
andMicrosoft.Net.Http
NuGet 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: