Authentication handler C# with Example



Authentication handler C# with Example

public class AuthenticationHandler : DelegatingHandler 
{ 
///  
/// Holds request's header name which will contains token. 
///  
private const string securityToken = " RequestAuthToken"; 
///  
/// Default overridden method which performs authentication. 
///  
/// Http request message. 
///  Cancellation  token. 
/// Returns http response message of type  class 
asynchronously. 
protected override Task SendAsync(HttpRequestMessage request, 
CancellationToken cancellationToken) 
{ 
if (request.Headers.Contains(securityToken)) 
{ 
bool authorized = Authorize(request); 
if (!authorized) 
{ 
return ApiHttpUtility.FromResult(request, false, HttpStatusCode.Unauthorized, 
MessageTypes.Error, Resource.UnAuthenticatedUser); 
} 
} 
else 
{ 
return ApiHttpUtility.FromResult(request, false, HttpStatusCode.BadRequest, 
MessageTypes.Error, Resource.UnAuthenticatedUser); 
} 
return base.SendAsync(request, cancellationToken); 
} 
///  
/// Authorize user by validating token. 
///  
/// Authorization context. 
/// Returns a value indicating whether current request is authenticated or 
not. 
private bool Authorize(HttpRequestMessage requestMessage) 
{ 
try 
{ 
HttpRequest request = HttpContext.Current.Request; 
string token = request.Headers[securityToken]; 
return SecurityUtility.IsTokenValid(token, request.UserAgent, 
HttpContext.Current.Server.MapPath("~/Content/"), requestMessage); 
} 
catch (Exception) 
{ 
return false; 
} 
} 
 

} 
 

0 Comment's

Comment Form

Submit Comment