2

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.

  1. For Web API, How can I return status codes 401 or 403 along with some additional message as JSON payload?
  2. For MVC Actions that return HTML, How can I return status codes 401 or 403 and redirect to different URL?
  3. How can I check if the request is WebAPI or MVC action?
abatishchev
  • 98,240
  • 88
  • 296
  • 433
iraSenthil
  • 11,307
  • 6
  • 39
  • 49

2 Answers2

1

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

Ivan Leonenko
  • 2,363
  • 2
  • 27
  • 37
  • I found the suggestion https://stackoverflow.com/questions/31205599/asp-net-web-api-correct-way-to-return-a-401-unauthorised-response easier. – B--rian Dec 10 '19 at 12:32
1

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);
}
  • This will set the content, not the ReasonPhrase, which is more applicable to extra exception info messages – Red May 05 '20 at 14:57