Click here to Skip to main content
15,879,326 members
Articles / Web Development / ASP.NET
Tip/Trick

Creating REST API with OAuth in VS 2013

Rate me:
Please Sign up or sign in to vote.
3.81/5 (11 votes)
28 Oct 2014CPOL 22.6K   23   4
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

Image 1

Step-2

Select "Individual User Accounts"

Image 2

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

C++
[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

C++
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.

C++
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 

C++
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

Image 3

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.

C++
$.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)); });

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer
India India
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralMy vote of 3 Pin
StanleyJHubert3-Dec-14 22:59
StanleyJHubert3-Dec-14 22:59 
GeneralMy Vote 5 Pin
Shemeemsha (ഷെമീംഷ)28-Oct-14 23:47
Shemeemsha (ഷെമീംഷ)28-Oct-14 23:47 
GeneralMy vote of 1 Pin
Michael Gledhill28-Oct-14 1:01
Michael Gledhill28-Oct-14 1:01 
Suggestion[My vote of 2] Poor article Pin
Member 382109327-Oct-14 12:59
Member 382109327-Oct-14 12:59 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.