Remove bearer token from custom authentication

Currently we are using JWT and two custom authentication providers. In one of these providers we’d like to remove the creation of the JWT token but it seems to be created after we set the authenticate dto values.

I don’t understand what that means, but if you just register a JwtAuthProviderReader it will only be able to read/process JWT tokens, not create them.

Sure, but what I need is both. With custom auth provider 1 we want to include the JWT, but with provider 2 we don’t want to create.

I still don’t follow. If they’re Custom Auth Providers you should be able to control what it does or doesn’t do.

I guess that was my thought as well and why i’m asking… here’s the code for the provider I don’t want to include the token in the response.

 public class ApiKeyExchangeAuthProvider: AuthProvider
{
    private static readonly ILog Logger = LogManager.GetLogger(typeof(ApiKeyExchangeAuthProvider));
    private readonly IUserManager userManager;
    private readonly IApiKeyManager apiKeyManager;
    public static string Name = "ApiKeyExchange";
    public static string Realm = "/auth/apikey";

    private User authUser;

    private class ApiKeyExchangeAuthValidator : AbstractValidator<Authenticate>
    {
        public ApiKeyExchangeAuthValidator()
        {
            RuleFor(x => x.UserName).NotEmpty().Unless(p => p.provider == AuthenticateService.LogoutAction);
            RuleFor(x => x.Password).NotEmpty().Unless(p => p.provider == AuthenticateService.LogoutAction);
        }
    }


    public ApiKeyExchangeAuthProvider(IUserManager userManager, IApiKeyManager apiKeyManager)
    {
        this.userManager = userManager;
        this.apiKeyManager = apiKeyManager;
        Provider = Name;
        AuthRealm = Realm;
    }

    private bool TryAuthenticate(IServiceBase authService, string userName, string password, bool isPasswordEncrypted, string ipAddress, string referrerUrl)
    {
        bool result = false;
        try
        {
            Logger.DebugFormat("Trying to authenticate user {0}", userName);
            authUser = userManager.LogOn(userName, password, ipAddress ?? authService.Request.RemoteIp, isPasswordEncrypted, referrerUrl);
            result = authUser != null;
        }
        catch (Exception ex)
        {
            Logger.Error("Authentication Error", ex);
            Logger.WarnFormat("User {0} failed authentication", userName);
        }

        return result;
    }

    public override bool IsAuthorized(IAuthSession session, IAuthTokens tokens, Authenticate request = null)
    {
        return false;
    }

    public override object Authenticate(IServiceBase authService, IAuthSession session, Authenticate request)
    {
        new ApiKeyExchangeAuthValidator().ValidateAndThrow(request);
        string userName = request.UserName;
        string password = request.Password;
        string referrerUrl = request.Continue;
        string ipAddress = authService.Request.UserHostAddress;
        
        Logger.InfoFormat("Login request from app [{0}]", ApiSignature.GetAppId(authService.Request));

        var auth = new AuthSignatureRequired();
        auth.Execute(authService.Request, authService.Request.Response, request);

        if (!TryAuthenticate(authService, userName, password, request.State == "encrypted", ipAddress, referrerUrl))
            throw new HttpError(HttpStatusCode.Unauthorized, AuthorizationErrorCode.InvalidAppAuthRequest,
                ErrorMessages.InvalidOrUnknownHmacRequest);

        var userApiKey = apiKeyManager.GetUserApiKey(auth.AppIdGuid, authUser.Id) ??
                         apiKeyManager.CreateNewUserKey(authUser.Id, auth.AppIdGuid);

        return new AuthenticateResponse
        {
            UserId = authUser.Id.ToString(),
            UserName = userName,
            ReferrerUrl = referrerUrl,
            BearerToken = null,
            Meta = new Dictionary<string, string>() { { "apiKeyHash", ApiSignature.CreateToken(userApiKey.ApiKey, auth.AppSecret) } }
        };
    }
 
}

But the bearerToken is set on the response object when i test is.

It’s not this AuthProvider but the JwtAuthProvider that adds the JWT Token to AuthenticateResponse.

If you don’t want it, you should be able use a Response Filter to clear it, e.g:

RegisterTypedResponseFilter<AuthenticateResponse>((req, res, dto) => {
    dto.BearerToken = null;
});

I’ve also added JwtAuthProvider.SetBearerTokenOnAuthenticateResponse option in this commit which lets you disable populating the AuthenticateResponse DTO from v4.0.61 that’s now available on MyGet.