In
this blog, we will discuss how to implement basic authentication in ASP.NET WEB
API.
STEP 1 : HTML , JQuery and AngularJS code used in the demo. Copy and
paste the following code in Employees.html page in project.
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta charset="utf-8" />
<script src="Scripts/jquery-1.10.2.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function ($scope, $http) {
$scope.Title = "Basic
Authentication in ASP.NET Web API"
var ulEmployees = $('#ulEmployees');
$scope.fnGetEmployees = function (username, password)
{
$scope.Employees = undefined;
$.ajax({
type: 'GET',
url: "api/employee/",
dataType: 'json',
headers: {
'Authorization': 'Basic ' + btoa(username + ':' + password)
},
success: function (data) {
$scope.$apply(function () {
$scope.Employees =
JSON.parse(JSON.stringify(data));
})
ulEmployees.empty();
},
complete: function (erro) {
if (erro.status == '401') {
ulEmployees.empty();
ulEmployees.append('<li
style="color:red">'
+ erro.status +
' : ' + erro.statusText + '</li>')
}
}
});
}
});
</script>
</head>
<body>
<div ng-app="myApp" ng-controller="myCtrl" class="container
col-lg-6">
<h4>{{Title}}</h4>
Username : <input class="form-control" type="text" id="txtUsername" ng-model="UserName" />
<br />
<br />
Password : <input class="form-control" type="password" id="txtPassword" ng-model="Password" />
<br /><br />
<input id="btnGetEmp" class="btn
btn-success" ng-click="fnGetEmployees(UserName,Password)" type="button" value="Get Employees" />
<!--<input
id="btnClear" type="button" value="Clear"
/>-->
<hr />
<div id="ulEmployees"></div>
<table ng-show="Employees" class="table">
<thead>
<tr>
<th>ID</th>
<th>First Name</th>
<th>Last Name</th>
<th>Gender</th>
<th>Salary</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="emp in Employees">
<td>{{emp.ID}}</td>
<td>{{emp.FirstName}}</td>
<td>{{emp.LastName}}</td>
<td>{{emp.Gender}}</td>
<td>{{emp.Salary}}</td>
</tr>
</tbody>
</table>
</div>
</body>
</html>
STEP 2 :Add ADO.NET Entity Data Model EmployeeDB.edmx"
in project
STEP 3 : The basic authentication can be applied
on a specific controller, specific action, or globally on all Web API
controllers. In this example we apply the attribute on a specific
controller, to enable basic authentication for all the methods in that
controller
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Web.Http;
namespace WebApiBasicAutho.Controllers
{
public class EmployeeController : ApiController
{
[BasicAuthentication]
public HttpResponseMessage Get()
{
string username = Thread.CurrentPrincipal.Identity.Name;
using (EmployeeDBEntities entities = new EmployeeDBEntities())
{
return Request.CreateResponse(HttpStatusCode.OK,
entities.Employees.ToList());
}
}
}
}
STEP 4 : Create a class name it ‘EmployeeSecurity.cs’ that checks if the username and password are valid. Copy and paste the following code in it.
using System;
using System.Linq;
namespace WebApiBasicAutho
{
public class EmployeeSecurity
{
public static bool Login(string username,string password)
{
using (EmployeeDBEntities entities = new EmployeeDBEntities())
{
return entities.Users.Any(user =>
user.Username.Equals(username, StringComparison.OrdinalIgnoreCase)
&& user.Password == password);
}
}
}
}
STEP 4 : To create a basic authentication filter, add
a new class file with a name 'BasicAuthenticationAttribute.cs'. Copy and paste the following code in it.
using System;
using System.Net;
using System.Net.Http;
using System.Security.Principal;
using System.Text;
using System.Threading;
using System.Web.Http.Controllers;
using System.Web.Http.Filters;
namespace WebApiBasicAutho
{
public class BasicAuthenticationAttribute : AuthorizationFilterAttribute
{
public override void OnAuthorization(HttpActionContext actionContext)
{
if(actionContext.Request.Headers.Authorization
== null)
{
actionContext.Response =
actionContext.Request
.CreateResponse(HttpStatusCode.Unauthorized);
}
else
{
string authenticationToken =
actionContext.Request.Headers
.Authorization.Parameter;
string decodedAuthenticationToken = Encoding.UTF8.GetString(
Convert.FromBase64String(authenticationToken));
string[] usernamePasswordArray =
decodedAuthenticationToken.Split(':');
string username = usernamePasswordArray[0];
string password = usernamePasswordArray[1];
if (EmployeeSecurity.Login(username,
password))
{
Thread.CurrentPrincipal = new GenericPrincipal(
new GenericIdentity(username), null);
}
else
{
actionContext.Response =
actionContext.Request
.CreateResponse(HttpStatusCode.Unauthorized);
}
}
}
}
}
No comments:
Post a Comment