ASP.net Examples

Download Java SE 8.

ASP.net Web API with token authentication

ASP.net REST Web API

Web API is used to implement REST API CRUD operations ( create, read, update and delete ).

Steps to create asp.net web api with token authentication

1) Create a new asp.net web application project.

asp.net web application project

2) Select Empty asp.net web application and choose MVC and Web API core references.

asp.net web api project

3) Add Microsoft.Owin packages as below using Manage NuGet Packages option in reference right click menu.

Manage Nuget Packages OAuth

3) Create a folder 'MessageAPIHandler' and add class file for custom authorization provider as 'AuthorizationProvider.cs'.

using Microsoft.Owin.Security.OAuth;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Threading.Tasks;
using System.Security.Claims;

namespace MessageAPIHandler.WebAPITokenAuth
{
    public class AuthorizationProvider: OAuthAuthorizationServerProvider
    {
        public override async Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
        {
            context.Validated();
        }
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            var identity = new ClaimsIdentity(context.Options.AuthenticationType);
            if (context.UserName == "admin" && context.Password == "admin")
            {
                identity.AddClaim(new Claim("username", "admin"));
                context.Validated(identity);
            }
            else
            {
                context.SetError("Invalid access", "Invalid user name and password");
                return;
            }
        }
    }
}

4) Define AthurizeAttribute Class.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace WebAPITokenAuth
{
    public class AuthorizeAttribute: System.Web.Http.AuthorizeAttribute
    {
        protected override void HandleUnauthorizedRequest(System.Web.Http.Controllers.HttpActionContext actionContext)
        {
            if (!HttpContext.Current.User.Identity.IsAuthenticated)
            {
                base.HandleUnauthorizedRequest(actionContext);
            }
            else
            {
                actionContext.Response = new System.Net.Http.HttpResponseMessage(System.Net.HttpStatusCode.Forbidden);
            }
        }
    }
}

5) Create Employee domain class as file name 'Employee.cs'.

    public class Employee
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string Designation { get; set; }
    }

6) Create Controller as 'EmmployeeController.cs' with below code under Controller folder.

[FromBody] attribute is used to get the value of the Employee item from the body of the HTTP request.
HTTP GET method is indicated by the [HttpGet] attribute, and HTTP POST method is indicated by the [HttpPost] attribute
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;

namespace WebAPITokenAuth.Controllers
{
    public class EmployeeController : ApiController
    {
        [Authorize]
        [HttpGet]
        [Route("api/employees")]
        public IHttpActionResult GetEmployees()
        {
            List employeeList = new List()
            {
                new Employee() {Id = 1, Name="Employee1", Designation="Manager" },
                 new Employee() {Id = 2, Name="Employee2", Designation="Supervisor" }
            };
            return Ok(employeeList);
        }

        [Authorize]
        [HttpPost]
        [Route("api/employee/add")]
        public IHttpActionResult AddEmployee([FromBody]Employee employee)
        {
            return Ok("Employee is added, Employee: " + "ID: " + employee.Id.ToString() + ", Name: "+ employee.Name);
        }
    }
}

7) Add Startup class "Startup.cs'

using System;
using System.Threading.Tasks;
using Microsoft.Owin;
using Owin;
using Microsoft.Owin.Security.OAuth;
using System.Web.Http;

[assembly: OwinStartup(typeof(WebAPITokenAuth.Startup))]

namespace WebAPITokenAuth
{
    public class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=316888
            // Enable cors origin requests
            app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);

            var authProvider = new AuthorizationProvider();
            OAuthAuthorizationServerOptions options = new OAuthAuthorizationServerOptions()
            {
                AllowInsecureHttp = true,
                TokenEndpointPath = new PathString("/token"),
                AccessTokenExpireTimeSpan = TimeSpan.FromDays(1),
                Provider = authProvider
            };
            app.UseOAuthAuthorizationServer(options);
            app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());

            WebApiConfig.Register(new HttpConfiguration());
        }
    }
}

Running Web API using Postman chrome web store

Running REST Web API is just like launching any asp.net web or press F5.

To test the Web API, Postman App is available in Chrome Web Store.

Get Request

  • Get request with valid user name and password as key value pairs in HTTP request body section to get token information.
  • Get request with header Authorization key with valid token ("Bearer "+) to get employees information .

Post Request

  • Get request with valid user name and password as key value pairs in HTTP request body section to get token information.
  • Post request with header Authorization key with valid token ("Bearer "+) and body section for input fields to add employee information .



Privacy Policy  |  Copyrightcopyright symbol2020 - All Rights Reserved.  |  Contact us   |  Report website issues in Github   |  Facebook page   |  Google+ page

Email Facebook Google LinkedIn Twitter
^