Returning a custom HTTP response code when the authentication fails for a custom credentials auth provider

Viewed 62

I know that I can return a custom reponse when using a custom authentication provider like the code below:

Return a custom auth response object from ServiceStack authentication

I'm just wondering if there is a way to return a custom HTTP response code.

For example, when the authentication fails, instead of a 401 unauthorized error, I want to send another HTTP response code to give more details on what failed. For example, when the account got locked, I will send the error code XYZ!

public class MyCredentialsAuthProvider : CredentialsAuthProvider
{
    public override object Authenticate(ServiceStack.ServiceInterface.IServiceBase authService, IAuthSession session, Auth request)
    {
        //let normal authentication happen
        var authResponse = (AuthResponse)base.Authenticate(authService, session, request);

        //return your own class, but take neccessary data from AuthResponse
        return new
            {
                UserName = authResponse.UserName,
                SessionId = authResponse.SessionId,
                ReferrerUrl = authResponse.ReferrerUrl,
                SessionExpires = DateTime.Now
            };

    }
}

In a try catch, I found a way of return a custom HTTP code in that function. I return for example:

return new ServiceStack.HttpError(423, "Locked");

I'm not sure if this is the right way

1 Answers

You can return an Error Response (like HttpError) to return a custom Error, but for successful responses you should return the AuthenticateResponse type as that's what all clients/service consumers are expecting (and other AuthResponse Filters and Decorators). If you want to return additional info in your AuthenticateResponse you should return them in its Meta Dictionary property.

Related