Reputation: 11577
I am trying to write a custom Authorize attribute to authorize some of the API endpoints and MVC actions. Following this StackOverflow answer, I wrote a custom attribute. I am using UnauthorizedResult to return 401.
Upvotes: 2
Views: 8033
Reputation: 323
A more modern response that applies to ASP.NET Core
at least would be
public async Task<IActionResult> CtrlAction()
{
...
var result = // whatever object you want
return StatusCode((int) HttpStatusCode.Unauthorized, result);
}
Upvotes: 1
Reputation: 2383
Answering your first question, this is how overridden method of authorization attribute may look like. Error message will be status message and content is in response body.
public override Task OnAuthorizationAsync(HttpActionContext actionContext, System.Threading.CancellationToken cancellationToken)
{
string errorMessage = "User has no enough permissions to perform requested operation.";
var httpContent = new StringContent("{ \"some\": \"json\"}", Encoding.UTF8, "application/json");
actionContext.Response = new HttpResponseMessage(HttpStatusCode.Forbidden)
{
ReasonPhrase = errorMessage,
Content = httpContent
};
return Task.FromResult<object>(null);
}
From MVC action you can return status code like this return StatusCode(418);
or using dedicated method like return Unauthorized();
. To redirect you can use RedirectToAction
or context.Response.Redirect
Upvotes: 1