1) Create a new asp.net web application project.
2) Select Empty asp.net web application and choose MVC and Web API core references.
3) Add Microsoft.Owin packages as below using Manage NuGet Packages option in reference right click menu.
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.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() { ListemployeeList = 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 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.
Privacy Policy | Copyright2020 - All Rights Reserved. | Contact us
| Report website issues in Github
| Facebook page
| Google+ page