65.9K
CodeProject is changing. Read more.
Home

Creating REST API with OAuth in VS 2013

starIconstarIconstarIcon
emptyStarIcon
starIcon
emptyStarIcon

3.81/5 (9 votes)

Oct 26, 2014

CPOL
viewsIcon

23241

This article describes steps to create rest api with OAuth and how to use those api using OAuth

Introduction

Web API uses OAuth framework to secure rest method. Api methods are secured by OAuth access token. To access those api, we must show accesstoken to api methods.

Steps to create API with OAuth

Step-1

Step-2

Select "Individual User Accounts"

Now application is created with OAuth authenication and API controller class surrounded by [Authorize] attribute. API are listed in http://localhost:50117/Help

[Authorize]
public class ValuesController : ApiController
{
}

Following code blocks are used to get the access token.

Registration:

User can register using API http://localhost:50117/api/Account/Register as

var registrationData =  {
    "UserName": "testapi@test.com",
    "Password": "Test$123",
    "ConfirmPassword": "Test$123"
};

$.ajax({
	type: "POST",
	url: 'http://localhost:50117/api/Account/Register/',
	data: JSON.stringify(registrationData),
	contentType: "application/json; charset=utf-8",
	success: function (response) { alert(JSON.stringify(response)); }
}).fail(function (response) { alert(JSON.stringify(response)); });

Access Token:

After registration we need to get Access token. We can use /Token api to get access token. We have enpoint code for access token  in Startup.cs.

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

We can post user credential and get access token as 

var accsessToken = '';
$.ajax({
	type: "POST",
	url: 'http://localhost:50117/Token',
	data: 'grant_type=password&username=testapi@test.com&password=Test$123',
	contentType: "Content-Type: application/x-www-form-urlencoded",
	success: function (response) { accsessToken = response.access_token; }
}).fail(function (response) { alert(JSON.stringify(response)); });

Access token response looks like

API Access:

After getting access token we can use api methods. AccessToken can be used as bearer token in requet header. To access api methods, we need to show access token.

$.ajax({
    type: "GET",
    url: 'http://localhost:50117/api/values',
    beforeSend: function (xhr) {
      xhr.setRequestHeader("Authorization", 'Bearer ' + accesstoken);
    },
    success: function (response) { alert(JSON.stringify(response)); }
    }).fail(function (response) { alert(JSON.stringify(response)); });