Search code examples
c#restservicestackrestful-authentication

ServiceStack custom response on failed authentication


I've created a custom authentication for servicestack, which works well. The only problem is, that I get empty responses for every route, that requires authentication, when I am not logged in. How can I change this to return something like

{
    "statuscode":"401",
    "message":"Unauthorized"
}

Thanks!


Solution

  • The Status Code and the Status Description is already in the returned HTTP Response Headers which is the expected response from a HTTP API. If you're calling from a web browser (i.e. client that accepts HTML) you can implement a /login page (configurable with AuthFeature.HtmlRedirect) to show the user a login page.

    Otherwise you can override OnFailedAuthentication() in your Custom AuthProvider to override what gets returned in a failed Auth response, be mindful of what you write in the response body as a JSON response only makes sense for clients requesting JSON responses.