Implementating OAuth access token in ASP.NET Web API2 webservice

13,595

The simplest way would be to start from a new Visual Studio 2013 ASP.NET Web Application template. In the "New ASP.NET Project" dialog select "Web API" and then click "Change Authentication" button and select option "Individual user accounts" like the picture below:

Web API Change authentication

This will create a project that uses the new ASP.NET membership "family member" ASP.NET Identity with a bearer token OAuth implementation.

What you need to look at are the following classes:

App_Start->Startup.Auth.cs

Token authentication is handled by OWIN middleware, here is the code that configures the pipeline. The most important is the call to UseOAuthBearerTokens which will enable 3 OWIN middleware components Authorization Server middleware, Application bearer token middleware, External bearer token middleware. You probably won't need the last one.

App_Start->IdentityConfig.cs

By default ASP.NET Identity is using Entity Framework as a storage provider (user, roles,claims persistance). If you will not use EF, you have to switch to another storage provider or implement it yourself with a couple of interfaces. Overview of Custom Storage Providers for ASP.NET Identity.

Providers->ApplicationOAuthProvider.cs

OWIN middleware will handle every request with the appropriate header. Here is the code that validates username and password provided in the HTTP header against a storage provider and returns the token which you will append to every subsequent HTTP request.

Authentication workflow

  1. First you need to get the security token. This is the task of the OAuth authorization server. The token endpoint is configured to exist at http://yourSite/Token. To get the token you need to compose a special HTTP header (test it with Fiddler). The first 3 lines should go to the POST request header and the last one to request body.

    Host: yoursite
    Content-Type: application/json;charset=UTF-8
    Content-Length: 51
    
    grant_type=password&username=xxxxxx&password=xxxxxx
    

    If the credentials are ok, you will receive the following response. Save the access_token value so that you will use it in step 2:

    .expires=Tue, 17 Jun 2014 22:11:12 GMT
    .issued=Tue, 03 Jun 2014 22:11:12 GMT
    access_token=c-D34PHKFGaPthuF2sIwmeowXYAPFiSPsMH...
    expires_in=1209599
    token_type=bearer
    userName=xxxxxxx
    
  2. Compose a appropriate GET request to a secured resource with jQuery (use show response to see the whole response):

    var getData = function(){
    var url = "http://yoursite/api/protectedResource/";
    $.ajax(url,{
    type: "GET",
    headers: "Authorization" : "Bearer " + accessToken
    }).always(showResponse);
    return false;
    };
    

I hope this will get you started.

Share:
13,595
Jenan
Author by

Jenan

Updated on July 29, 2022

Comments

  • Jenan
    Jenan over 1 year

    I use ASP.NET Web API and using a jquery ajax method.

    I would like to create secure Web services using OAuth access token.

    How can I implement OAuth2 to ASP.NET Web API2 Web Services?

    I want to prevent the use of the web services without logging in - no access token.

    There is a sample project with the implementation of oauth2 to web services?

    WebApi Controller for example:

    public class GetDataController : ApiController
    {
        public string Get(int id, string accessToken)
        {
    
            //Check access token
            //How can I implementing this logic for authorization valid access token
            if (accessToken == isInvalid)
            {
                return "Access denied";
            }
    
            //If accessToken is valid return value
            return "value";
        }
    }
    

    Javascript:

    $.get( "api/getdata", { id: 1, accessToken: "KEY" } )
    .done(function( data ) {
    alert( "Data Loaded: " + data );
    });