Language

Individual Accounts in ASP.NET Web API

By Mike Wasson|

This tutorial shows how to authenticate a web API using individual user accounts that are managed in a local database. By default, user profiles are stored in a SQL Server LocalDB database, which you can deploy to SQL Server or Windows Azure SQL Database for the production site.

For this tutorial we will use the Fiddler web debugging tool to send HTTP requests to the web API. That way, you can see the raw HTTP messages for authenticating and authorizing the user. When you write a client application, you will use the appropriate HTTP cliennt library to create the HTTP requests -- XMLHttpRequest (AJAX) for a web client, HttpClient for .NET client, and so forth.

Prerequisites

Create the Web API Project

Start Visual Studio 2013. From the File menu, click New Project. In the New Project dialog, click Web in the left pane and ASP.NET Web Application in the middle pane. Enter a name for the project and click OK.

In the New ASP.NET Project dialog, select the "Web API" template.

Click Change Authentication. In the Change Authentication dialog, select Individual User Accounts. Click OK.

Click OK in the New ASP.NET Project dialog to create the project.

Press F5 to start debugging the application. The application contains a basic home page, which is implemented using ASP.NET MVC 5.

When Visual Studio runs a web project, a random port is used for the web server. In the image above, the port number is 49436.

Send an HTTP Request to the Web API

First, let's see what happens if you send an anonymous request to the web API. Lauch Fiddler and select the Composer tab. Type the following address into the address bar:

http://localhost:port/api/values

For "port" use the actual port number that Visual Studio is using. Click Execute.

When you click Execute, Fiddler sends a GET request to the specified URL. When the request completes, the response appears in the HTTP session list in the left pane.

The response code is 401, Unauthorized. That's because the ValuesController is marked with the [Authorize] attribute. This attribute means that all requests for this controller must be from an authenticated user. Because we did not provide any credentials with the request, the method returns 401.

To see the details of the response, double-click the response in the sessions list. The response details are shown in the Inspector tab.

In the detailed view, click the Raw tab to see the raw HTTP reponse. It should look similar to the following:

HTTP/1.1 401 Unauthorized
Cache-Control: no-cache
Pragma: no-cache
Content-Type: application/json; charset=utf-8
Expires: -1
Server: Microsoft-IIS/8.0
X-AspNet-Version: 4.0.30319
WWW-Authenticate: Bearer
X-Powered-By: ASP.NET
Date: Tue, 15 Oct 2013 16:31:28 GMT
Content-Length: 61

{"Message":"Authorization has been denied for this request."}

The Www-Authenticate header has the value "Bearer", indicating that the client must authenticate using a bearer token.

A bearer token is a particular type of access token. An access token is a credential string that authorizes a client to access a protected resource. (See RFC 6749.) A bearer token is an access token that can be used by any client. In other words, a client can use the token without proving that the token was issued to that particular client. (See RFC 6750.) For tis reason, bearer tokens must be used with SSL. If you transmit a bearer token as plaintext, anyone can intercept it and get access to the protected resource.

Register a User

To access the web API, we need to sign in as a registered user. So the first step is to register a new user. In the Fiddler Composer tab, use the dropdown next to the URI to select "POST".

In the URI text box, type the following URI: http://localhost:port/api/Account/Register. Under Request Headers, add the following header: Content-Type: application/json. Under Request Body, paste the following:

{
  "UserName": "Alice",
  "Password": "password123",
  "ConfirmPassword": "password123"
}

The following screenshot shows the request in Fiddler.

Here is what the raw HTTP request will look like:

POST http://localhost:49436/api/Account/Register HTTP/1.1
User-Agent: Fiddler
Host: localhost:49436
Content-Type: application/json
Content-Length: 106

{
  "UserName": "Alice",
  "Password": "password123",
  "ConfirmPassword": "password123"
}

Press Execute to send the request. The response status code should be 200, indicating that the user was successfully added to the membership database.

On the server, this request is handled by the AccountController.Register method, which is defined in Controllers/AccountController.cs. This method uses ASP.NET Identity to add the user to the database. In the following screenshot, I put a breakpoint in the Register method. You can see that the JSON payload was deserialized to a RegisterBindingModel instance.

Authenticate and Get a Bearer Token

Next, let's sign in as "Alice" and get a bearer token. To do so, we must send an HTTP request to the token endpoint.

In the Fiddler Composer tab, enter the following URL (remember to change "port" to the actual port number):

http://localhost:port/Token

Leave the request method as POST. Change the Content-Type header to application/x-www-form-urlencoded. Replace the request body with the following:

grant_type=password&username=Alice&password=password123

Click Execute to send the request. Here is the raw HTTP request:

POST http://localhost:49436/Token HTTP/1.1
User-Agent: Fiddler
Host: localhost:49436
Content-Type: application/x-www-form-urlencoded
Content-Length: 55

grant_type=password&username=Alice&password=password123

Assuming the request succeeds, the response body should look like the following:

{
    "access_token":"boQtj0SCGz2GFGz[...]",
    "token_type":"bearer",
    "expires_in":1209599,
    "userName":"Alice",
    ".issued":"Mon, 14 Oct 2013 06:53:32 GMT",
    ".expires":"Mon, 28 Oct 2013 06:53:32 GMT"
}

(For readability, I truncated the access token and added indentation.)

The response is a JSON payload that contains the access token. The client can use this token to access the web API. Note that the request to the token endpoint authenticates the user. It's the bearer token that authorizes the client to access protected resources.

Copy the access token to somewhere convenient like Notepad. You will use the token in the next part of the tutorial.

Also, notice that that the bearer token has an expiration. The expiration time is configured in Startup.Auth.cs, in the Startup class static constructor.

static Startup()
{
    // ...
    OAuthOptions = new OAuthAuthorizationServerOptions
    {
        TokenEndpointPath = new PathString("/Token"),
        Provider = new ApplicationOAuthProvider(PublicClientId, UserManagerFactory),
        AuthorizeEndpointPath = new PathString("/api/Account/ExternalLogin"),
        AccessTokenExpireTimeSpan = TimeSpan.FromDays(14),
        AllowInsecureHttp = true
    };
}

Send an Authorized Request

Now we are ready to send another GET request to the web API. This time, the request will include the bearer token.

In the Fiddler Composer tab, change the request method from POST back to GET. Delete the request body, and delete the Content-Type header. Add the following header:

Authorization: Bearer boQtj0SCGz2GFGz[...]

... where the string after "Bearer" is the access token from the previous step. The actual token string is several hundred characters long.

Click Execute to send the request. This time, the request should succeed and return a 200 status code.

HTTP/1.1 200 OK
Cache-Control: no-cache
Pragma: no-cache
Content-Type: application/json; charset=utf-8
Expires: -1
Server: Microsoft-IIS/8.0
X-AspNet-Version: 4.0.30319
X-Powered-By: ASP.NET
Date: Tue, 15 Oct 2013 17:02:40 GMT
Content-Length: 19

["value1","value2"]

Next Steps

In this tutorial, you've learned how to authenticate with an individual account using raw HTTP requests. To create a client web application, you can start with the ASP.NET "Single Page Application" template in Visual Studio 2013.

You can also add external authentication services such as Microsoft Accounts, Twitter, Facebook, and Google. For more information, see External Authentication Services.

Author Information

Mike Wasson

Mike Wasson – Mike Wasson is a programmer-writer at Microsoft.