Basic Authentication in ASP.NET Core - asp.net-core

Question
How can I implement Basic Authentication with Custom Membership in an ASP.NET Core web application?
Notes
In MVC 5 I was using the instructions in this article which requires adding a module in the WebConfig.
I am still deploying my new MVC Coreapplication on IIS but this approach seems not working.
I also do not want to use the IIS built in support for Basic authentication, since it uses Windows credentials.

ASP.NET Security will not include Basic Authentication middleware due to its potential insecurity and performance problems.
If you require Basic Authentication middleware for testing purposes, then please look at https://github.com/blowdart/idunno.Authentication

ASP.NET Core 2.0 introduced breaking changes to Authentication and Identity.
On 1.x auth providers were configured via Middleware (as the accepted answer's implementation).
On 2.0 it's based on services.
Details on MS doc:
https://learn.microsoft.com/en-us/aspnet/core/migration/1x-to-2x/identity-2x
I've written a Basic Authentication implementation for ASP.NET Core 2.0 and publish to NuGet:
https://github.com/bruno-garcia/Bazinga.AspNetCore.Authentication.Basic

I'm disappointed by the ASP.NET Core authentication middleware design. As a framework it should simplify and led to greater productivity which isn't the case here.
Anyway, a simple yet secure approach is based on the Authorization filters e.g. IAsyncAuthorizationFilter. Note that an authorization filter will be executed after the other middlewares, when MVC picks a certain controller action and moves to filter processing. But within filters, authorization filters are executed first (details).
I was just going to comment on Clays comment to Hector's answer but didn't like Hectors example throwing exceptions and not having any challenge mechanism, so here is a working example.
Keep in mind:
Basic authentication without HTTPS in production is extremely bad. Make sure your HTTPS settings are hardened (e.g. disable all SSL and TLS < 1.2 etc.)
Today, most usage of basic authentication is when exposing an API that's protected by an API key (see Stripe.NET, Mailchimp etc). Makes for curl friendly APIs that are as secure as the HTTPS settings on the server.
With that in mind, don't buy into any of the FUD around basic authentication. Skipping something as basic as basic authentication is high on opinion and low on substance. You can see the frustration around this design in the comments here.
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.EntityFrameworkCore;
using System;
using System.Linq;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;
namespace BasicAuthFilterDemo
{
public class BasicAuthenticationFilterAttribute : Attribute, IAsyncAuthorizationFilter
{
public string Realm { get; set; }
public const string AuthTypeName = "Basic ";
private const string _authHeaderName = "Authorization";
public BasicAuthenticationFilterAttribute(string realm = null)
{
Realm = realm;
}
public async Task OnAuthorizationAsync(AuthorizationFilterContext context)
{
try
{
var request = context?.HttpContext?.Request;
var authHeader = request.Headers.Keys.Contains(_authHeaderName) ? request.Headers[_authHeaderName].First() : null;
string encodedAuth = (authHeader != null && authHeader.StartsWith(AuthTypeName)) ? authHeader.Substring(AuthTypeName.Length).Trim() : null;
if (string.IsNullOrEmpty(encodedAuth))
{
context.Result = new BasicAuthChallengeResult(Realm);
return;
}
var (username, password) = DecodeUserIdAndPassword(encodedAuth);
// Authenticate credentials against database
var db = (ApplicationDbContext)context.HttpContext.RequestServices.GetService(typeof(ApplicationDbContext));
var userManager = (UserManager<User>)context.HttpContext.RequestServices.GetService(typeof(UserManager<User>));
var founduser = await db.Users.Where(u => u.Email == username).FirstOrDefaultAsync();
if (!await userManager.CheckPasswordAsync(founduser, password))
{
// writing to the Result property aborts rest of the pipeline
// see https://learn.microsoft.com/en-us/aspnet/core/mvc/controllers/filters?view=aspnetcore-3.0#cancellation-and-short-circuiting
context.Result = new StatusCodeOnlyResult(StatusCodes.Status401Unauthorized);
}
// Populate user: adjust claims as needed
var claims = new[] { new Claim(ClaimTypes.Name, username, ClaimValueTypes.String, AuthTypeName) };
var principal = new ClaimsPrincipal(new ClaimsIdentity(claims, AuthTypeName));
context.HttpContext.User = principal;
}
catch
{
// log and reject
context.Result = new StatusCodeOnlyResult(StatusCodes.Status401Unauthorized);
}
}
private static (string userid, string password) DecodeUserIdAndPassword(string encodedAuth)
{
var userpass = Encoding.UTF8.GetString(Convert.FromBase64String(encodedAuth));
var separator = userpass.IndexOf(':');
if (separator == -1)
return (null, null);
return (userpass.Substring(0, separator), userpass.Substring(separator + 1));
}
}
}
And these are the supporting classes
public class StatusCodeOnlyResult : ActionResult
{
protected int StatusCode;
public StatusCodeOnlyResult(int statusCode)
{
StatusCode = statusCode;
}
public override Task ExecuteResultAsync(ActionContext context)
{
context.HttpContext.Response.StatusCode = StatusCode;
return base.ExecuteResultAsync(context);
}
}
public class BasicAuthChallengeResult : StatusCodeOnlyResult
{
private string _realm;
public BasicAuthChallengeResult(string realm = "") : base(StatusCodes.Status401Unauthorized)
{
_realm = realm;
}
public override Task ExecuteResultAsync(ActionContext context)
{
context.HttpContext.Response.StatusCode = StatusCode;
context.HttpContext.Response.Headers.Add("WWW-Authenticate", $"{BasicAuthenticationFilterAttribute.AuthTypeName} Realm=\"{_realm}\"");
return base.ExecuteResultAsync(context);
}
}

We implemented Digest security for an internal service by using an ActionFilter:
public class DigestAuthenticationFilterAttribute : ActionFilterAttribute
{
private const string AUTH_HEADER_NAME = "Authorization";
private const string AUTH_METHOD_NAME = "Digest ";
private AuthenticationSettings _settings;
public DigestAuthenticationFilterAttribute(IOptions<AuthenticationSettings> settings)
{
_settings = settings.Value;
}
public override void OnActionExecuting(ActionExecutingContext context)
{
ValidateSecureChannel(context?.HttpContext?.Request);
ValidateAuthenticationHeaders(context?.HttpContext?.Request);
base.OnActionExecuting(context);
}
private void ValidateSecureChannel(HttpRequest request)
{
if (_settings.RequireSSL && !request.IsHttps)
{
throw new AuthenticationException("This service must be called using HTTPS");
}
}
private void ValidateAuthenticationHeaders(HttpRequest request)
{
string authHeader = GetRequestAuthorizationHeaderValue(request);
string digest = (authHeader != null && authHeader.StartsWith(AUTH_METHOD_NAME)) ? authHeader.Substring(AUTH_METHOD_NAME.Length) : null;
if (string.IsNullOrEmpty(digest))
{
throw new AuthenticationException("You must send your credentials using Authorization header");
}
if (digest != CalculateSHA1($"{_settings.UserName}:{_settings.Password}"))
{
throw new AuthenticationException("Invalid credentials");
}
}
private string GetRequestAuthorizationHeaderValue(HttpRequest request)
{
return request.Headers.Keys.Contains(AUTH_HEADER_NAME) ? request.Headers[AUTH_HEADER_NAME].First() : null;
}
public static string CalculateSHA1(string text)
{
var sha1 = System.Security.Cryptography.SHA1.Create();
var hash = sha1.ComputeHash(Encoding.UTF8.GetBytes(text));
return Convert.ToBase64String(hash);
}
}
Afterwards you can annotate the controllers or methods you want to be accessed with Digest security:
[Route("api/xxxx")]
[ServiceFilter(typeof(DigestAuthenticationFilterAttribute))]
public class MyController : Controller
{
[HttpGet]
public string Get()
{
return "HELLO";
}
}
To implement Basic security, simply change the DigestAuthenticationFilterAttribute to not use SHA1 but direct Base64 decoding of the Authorization header.

Super-Simple Basic Authentication in .NET Core:
1. Add this utility method:
static System.Text.Encoding ISO_8859_1_ENCODING = System.Text.Encoding.GetEncoding("ISO-8859-1");
public static (string, string) GetUsernameAndPasswordFromAuthorizeHeader(string authorizeHeader)
{
if (authorizeHeader == null || !authorizeHeader.Contains("Basic "))
return (null, null);
string encodedUsernamePassword = authorizeHeader.Substring("Basic ".Length).Trim();
string usernamePassword = ISO_8859_1_ENCODING.GetString(Convert.FromBase64String(encodedUsernamePassword));
string username = usernamePassword.Split(':')[0];
string password = usernamePassword.Split(':')[1];
return (username, password);
}
2. Update controller action to get username and password from Authorization header:
public async Task<IActionResult> Index([FromHeader]string Authorization)
{
(string username, string password) = GetUsernameAndPasswordFromAuthorizeHeader(Authorization);
// Now use username and password with whatever authentication process you want
return View();
}
Example
This example demonstrates using this with ASP.NET Core Identity.
public class HomeController : Controller
{
private readonly UserManager<IdentityUser> _userManager;
public HomeController(UserManager<IdentityUser> userManager)
{
_userManager = userManager;
}
[AllowAnonymous]
public async Task<IActionResult> MyApiEndpoint([FromHeader]string Authorization)
{
(string username, string password) = GetUsernameAndPasswordFromAuthorizeHeader(Authorization);
IdentityUser user = await _userManager.FindByNameAsync(username);
bool successfulAuthentication = await _userManager.CheckPasswordAsync(user, password);
if (successfulAuthentication)
return Ok();
else
return Unauthorized();
}
}

Related

Is there a better way of JWT Web Token combined with Windows Auth. for building auth service in an ASP.NET Core project?

The reason behind my question is that, there is a beginner developer team at a company, starting to create a new business project after finishing some vital courses for web applications.
The aim is to have a Web Application within the company's intranet in the following form:
On Angular SPA frontend with ASP.NET Core WebAPI, using Entity Framework Core with a Microsoft SQL Server database running on Windows Server.
The current authentication method of course is Windows Authentication.
In order to create proper auth services, it was suggested to use JWT Web Token, however it is hard to tell whether there is a better approach for using authentication by combining them on the above mentioned Web Application.
As we are lacking of experience, a review of any familiars' would be highly appreciated in this matter!
The current authentication method of course is Windows Authentication.
In order to create proper auth services, it was suggested to use JWT
Web Token.
As you may know JSON Web Token (JWT) is an open standard (RFC 7519) that defines a compact and self-contained way for securely transmitting information between parties as a JSON object.Therefore, JWT creates a JSON web token and encodes, sterilizes, and adds a signature with a secret key that cannot be tampered with; Thus, it would ensure your application security well.
It is hard to tell whether there is a better approach for using
authentication by combining them on the above mentioned Web
Application.
Depending on your current application eco-system you could use Jwt without any concern as you have SPAs and other application running on intranet. While, implementing jwt it would allow you to ensure your authentication regardless of any platform. For instance, It could be windows app, SPA or any cross platform app. You can authenticate all the platfroms using this infrastructure.
As we are lacking of experience, a review of any familiars' would be
highly appreciated in this matter!
Considering your scenario, here is the implementaion steps, you could follow. You always can customize it based on your requirement. Altough, I am share you the basic steps which might assist you.
Note:
Following implementation, can be used either in any internal(intranet) or public web application(internet app) in any platforms.
Implementaion Guideline:
appsettings.json:
"Jwt": {
"Key": "Set_Your_SecretKey",
"Issuer": "YourApplication_URL"
}
Jwt Token View Model:
public class LoginViewModel
{
[Required]
[EmailAddress]
public string Email { get; set; } = string.Empty;
[Required]
[DataType(DataType.Password)]
public string Password { get; set; } = string.Empty;
}
Jwt Token Interface:
public interface IAuthenticationRepository
{
Task<TokenViewModel> AuthenticateLogin(LoginViewModel loginInfo);
}
Repository Implementation:
public class AuthenticationRepository : IAuthenticationRepository
{
private readonly ApplicationDbContext _dbContext;
private readonly IMapper _mapper;
private readonly IConfiguration _config;
public AuthenticationRepository(ApplicationDbContext dbContext, IMapper mapper, IConfiguration config)
{
_dbContext = dbContext;
_mapper = mapper;
_config = config;
}
public async Task<TokenViewModel> AuthenticateLogin(LoginViewModel loginInfo)
{
try
{
var isAuthenticate = await _dbContext.Users.FirstOrDefaultAsync(u => u.UserEmail == loginInfo.Email && u.Password == loginInfo.Password);
var tokenViewModel = new TokenViewModel();
if (isAuthenticate != null)
{
var getToken = GenerateJSONWebToken(loginInfo);
tokenViewModel = _mapper.Map<TokenViewModel>(isAuthenticate);
tokenViewModel.Token = getToken;
}
return tokenViewModel;
}
catch (Exception ex)
{
throw;
}
}
private string GenerateJSONWebToken(LoginViewModel userInfo)
{
var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config["Jwt:Key"]));
var credentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256);
var claims = new[] {
new Claim(JwtRegisteredClaimNames.Sub, userInfo.Email),
new Claim(JwtRegisteredClaimNames.Email, userInfo.Password),
new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString())
};
var token = new JwtSecurityToken(_config["Jwt:Issuer"],
_config["Jwt:Issuer"],
claims,
expires: DateTime.Now.AddMinutes(120),
signingCredentials: credentials);
return new JwtSecurityTokenHandler().WriteToken(token);
}
Response Model I Have Used:
public class ResponseViewModel
{
public string output { get; set; }
public string msg { get; set; }
public object apiResponse { get; set; }
}
Auth Controller:
[Route("api/Authentication")]
[ApiController]
public class AuthenticationController : ControllerBase
{
private readonly IAuthenticationRepository _authenticationService;
public AuthenticationController(IAuthenticationRepository authenticationService)
{
this._authenticationService = authenticationService;
}
[AllowAnonymous]
[Route("login")]
[HttpPost]
public async Task<IActionResult> LoginAsync([FromBody] LoginViewModel loginInfo)
{
IActionResult response = Unauthorized();
var user = await _authenticationService.AuthenticateLogin(loginInfo);
if (user.Token != null)
{
response = Ok(new ResponseViewModel { output = "success", msg = "Login Successfully", apiResponse = user });
}
return response;
}
Authenticate Your Access:
Once you have successfully generate jwt auth token, now you can pass that as Bearer token for any authorization and to restrict access you can use [Authorize] before any resource where you wants to restrict access.
Output:
Note: If you would like to know more details on jwt token you could check our official document here

.Net core web api - Role based authorization (Allow specific domains without asking JWT)

I have an API that uses standard role based authorization and JWT. I need to allow specific domains to use the API without providing JWT while still continue to using role based auth for other users. Is there a way to do this? Can I assign roles to these domains if such a way exists?
You can use an authorization filter. When authorization is required, the filter is executed. In the filter you can validate the domain an set the current user, including the roles(s):
//using System;
//using System.Collections.Generic;
//using System.Security.Claims;
//using System.Security.Principal;
//using System.Web;
//using System.Web.Http.Controllers;
//using System.Web.Http.Filters;
public class AddIdentityFilter : AuthorizationFilterAttribute
{
public override void OnAuthorization(HttpActionContext actionContext)
{
var allowedIpAdresses = new List<string> { "127.0.0.1", "" };
// Replace with your code to test the domain
var isInDomain = allowedIpAdresses.Contains(GetIp());
var identity = HttpContext.Current.User.Identity;
if (!identity.IsAuthenticated && isInDomain)
{
// Add the roles to the new Identity
HttpContext.Current.User = new GenericPrincipal(new GenericIdentity("DomainUser"), new[] { "Admin" });
}
base.OnAuthorization(actionContext);
}
// Helper to determine the ipaddress
private string GetIp()
{
var context = (HttpContextBase)HttpContext.Current.Items["MS_HttpContext"];
if (context != null)
return context.Request.UserHostAddress;
if (HttpContext.Current != null)
return HttpContext.Current.Request.UserHostAddress;
return null;
}
}
In WebApiConfig.cs add the filter:
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Only needed for Owin
config.SuppressDefaultHostAuthentication();
config.Filters.Add(new AddIdentityFilter());
// ...
}
}

ServiceStack and .NET Core Middleware

I wonder if it is possible to use ServiceStack on .NET core along with middleware.
My use case is that I'd like to have API implemented with ServiceStack, and use authorisation policies and openid connect middleware such as IdentityServer4.AccessTokenValidation.
If no, is there any alternative way to setup ServiceStack to work with openid connect server?
I glued ServiceStack and .NET Core with the following code. I am not sure if it is the best way to archive the goal, but so far it works.
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
public class AuthorizeAttribute : RequestFilterAsyncAttribute, IAuthorizeData
{
public AuthorizeAttribute(ApplyTo applyTo)
: base(applyTo)
{
Priority = -100;
}
public AuthorizeAttribute()
: this(ApplyTo.All)
{
}
public string Policy { get; set; }
public string Roles { get; set; }
public string AuthenticationSchemes { get; set; }
public override async Task ExecuteAsync(IRequest req, IResponse res, object requestDto)
{
var policyProvider = req.TryResolve<IAuthorizationPolicyProvider>();
var filter = new AuthorizeFilter(policyProvider, new[] {this});
var webRequest = req.OriginalRequest as HttpRequest;
var actionContext = new ActionContext(webRequest.HttpContext, new RouteData(), new ActionDescriptor());
var context = new AuthorizationFilterContext(actionContext, new List<IFilterMetadata>());
await filter.OnAuthorizationAsync(context);
if (context.Result is ChallengeResult)
{
res.StatusCode = 401;
res.EndRequest();
}
else if (context.Result is ForbidResult)
{
res.StatusCode = 403;
res.EndRequest();
}
}
}
You can register .NET Core Middleware in the same AppHost as ServiceStack in .NET Core Apps since ServiceStack is just another middleware in the pipeline itself but ServiceStack built-in Authentication attributes and features wont be aware about any external Authentication implementations.
For a more integrated solution check out the community contributed ServiceStack.Authentication.IdentityServer which includes a ServiceStack AuthProvider for IdentityServer.

Is it possible to secure a web api with Authentication Filters using the local AD system acounts?

I've looked at implementing a way to maybe impersonate your AD user to secure my Web API, using my local domain AD.
All the samples I've found they use basic or token authentication. or secure it using Azure AD.
I want to implement my custom authorization business logic using my local domain AD/Impersonation. All I can achieve is using BASIC authentication and the challenge always POPS UP a form to input username/password. I would like to bypass that and use my local domain + custom logic to authenticate/authorize users.
Is there a way where I can impersonate the windows user to authenticate and authorize resources in my web api?
this is what my challenge function looks like:
void Challenge(HttpRequestMessage request, HttpResponseMessage response)
{
var host = request.RequestUri.DnsSafeHost;
response.Headers.Add(WWWAuthenticateHeader, string.Format("Basic realm=\"{0}\"", host));
}
Thanks very much!
First, you should read this:
How to get HttpClient to pass credentials along with the request?
Second (if you're doing a "one hop").
If you enable "Windows Authentication" and disable "Anonymous Authentication" (in IIS under "Authentication").......you can get at the Windows Identity.
You'll want to write a custom AuthorizeAttribute.
Here is a basic one to try out:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Security.Principal;
using System.Web;
using System.Web.Http;
using System.Web.Http.Controllers;
namespace MyLibrary.CustomAttributes.WebApi
{
public class IdentityWhiteListAuthorizationAttribute : System.Web.Http.AuthorizeAttribute
{
public const string ErrorMessageBadIdentityContent = "IIdentity.Name was empty or IIdentity was not a WindowsIdentity. CurrentAction='{0}'";
public const string ErrorMessageBadIdentityReasonPhrase = "IIdentity.Name was empty or IIdentity was not a WindowsIdentity. The most likely reason is that the web service is not setup for WindowsAuthentication and/or Anonymous Authentication is enabled.";
public const string ErrorMessageNotAuthenticated = "IIdentity.IsAuthenticated was false. '{0}'";
public IdentityWhiteListAuthorizationAttribute()
{
}
private string CurrentActionName { get; set; }
public override void OnAuthorization(HttpActionContext actionContext)
{
this.CurrentActionName = actionContext.ActionDescriptor.ActionName;
base.OnAuthorization(actionContext);
}
protected override bool IsAuthorized(HttpActionContext actionContext)
{
/* this will authenticate if the authorization-header contained a "Negotiate" windows Identity. Note, WebApi must be running in Windows-Authentication mode (and the WebApi-web.config must be set for "<authentication mode="Windows" />") for this to work. (the client will send the windows identity via the DefaultRequestHeaders.Authorization header */
string currentActionName = this.CurrentActionName;
IPrincipal httpContextCurrentUserPrinc = HttpContext.Current.User; /* */
IIdentity ident = httpContextCurrentUserPrinc.Identity;
bool badIdentity = false;
string errorMessageContent = string.Empty;
string errorMessageReasonPhrase = string.Empty;
if (null == ident)
{
badIdentity = true;
errorMessageContent = string.Format(ErrorMessageBadIdentityContent, currentActionName);
errorMessageReasonPhrase = ErrorMessageBadIdentityReasonPhrase;
}
if (!badIdentity)
{
/* Ensure that we have an actual userName which means windows-authentication was setup properly */
if (string.IsNullOrEmpty(ident.Name))
{
badIdentity = true;
errorMessageContent = string.Format(ErrorMessageBadIdentityContent, currentActionName);
errorMessageReasonPhrase = ErrorMessageBadIdentityReasonPhrase;
}
}
if (!badIdentity)
{
if (!ident.IsAuthenticated)
{
badIdentity = true;
errorMessageContent = string.Format(ErrorMessageNotAuthenticated, ident.Name);
errorMessageReasonPhrase = string.Format(ErrorMessageNotAuthenticated, ident.Name);
}
}
if (!badIdentity)
{
if (ident.GetType() != typeof(WindowsIdentity))
{
badIdentity = true;
errorMessageContent = string.Format(ErrorMessageBadIdentityContent, currentActionName);
errorMessageReasonPhrase = ErrorMessageBadIdentityReasonPhrase;
}
}
if (badIdentity)
{
HttpResponseMessage resp = new HttpResponseMessage(HttpStatusCode.BadRequest)
{
Content = new StringContent(errorMessageContent),
ReasonPhrase = errorMessageReasonPhrase
};
throw new HttpResponseException(resp);
}
return true;
}
}
}
Apply that attribute to a webapi controller and/or method(s).
You could also write a DelegatingHandler...and use the same code above......

How do Implement authorization in MVC4 Web API?

I Had create a MVC4 Web API. But People without authorization also can use it.
Example: people type in address bar "/api/product/1" also can get the result.
So, How to implement Security and allow authorize person to use the WEB API only ?
How to give authorize to the person that allow login to web api ?
More info about Authentication and Authorization
Simply adding the annotation to your controller will do:
// Require authorization for all actions on the controller.
[Authorize]
public class ValuesController : ApiController
{
public HttpResponseMessage Get(int id) { ... }
public HttpResponseMessage Post() { ... }
}
// Restrict by user:
[Authorize(Users="Alice,Bob")]
public class ValuesController : ApiController
{
}
// Restrict by role:
[Authorize(Roles="Administrators")]
public class ValuesController : ApiController
{
}
you can use MVC4 AspNet.identiy.Usermanager and Microsoft.Owin.Security to authenticate user..
private IAuthenticationManager AuthenticationManager
{
get
{
return HttpContext.Current.GetOwinContext().Authentication;
}
}
public HttpResponseMessage Login(string username, string password)
{
UserManager<TenantUser> userManager=new new UserManager<TenantUser>(new UserStore<TenantUser>(YOUR DBCONTEXT));
var user = UserManager.Find(username, password);
if (user != null)
{
AuthenticationManager.SignOut(DefaultAuthenticationTypes.ApplicatioCookie);
ClaimsIdentity identity = await UserManager.CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie);
AuthenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = true }, identity);
}
else
new HttpResponseMessage(HttpStatusCode.Forbidden) { Content = new ObjectContent<object>(new { Error = "You are not authorized to perform this action" }, Configuration.Formatters.JsonFormatter) };
}
it is working for me....