Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is my api key null with ServiceStack ApiKeyAuthProvider?

Tags:

servicestack

Here is my Auth config:

container.Register<IAuthRepository>(c => new OrmLiteAuthRepository(c.Resolve<IDbConnectionFactory>()));
container.Resolve<IAuthRepository>().InitSchema();
Plugins.Add(new AuthFeature(() => new AuthUserSession(),
new IAuthProvider[]
{
    new ApiKeyAuthProvider(AppSettings) 
}));

I then add a GlobalRequestFilter so I can check live vs test:

GlobalRequestFilters.Add((req, res, requestDto) =>
{
    var user = req.GetUser();
    var apikey = req.GetApiKey();
}

Both user and apikey are null.

I'm using the method of embedding the apikey as the username for Basic Authentication. I see the header in the request. Will that not work here?

like image 608
IronicMuffin Avatar asked Dec 15 '25 18:12

IronicMuffin


1 Answers

IRequest.GetUser() is an extension method that returns the Windows Auth ASP.NET IPrincipal (i.e. if using AspNetWindowsAuthProvider), it's not related to ServiceStack Auth which is based on User Sessions.

But the ApiKey should be returned for API Key Auth Requests as seen in this stand-alone API Key Auth integration test:

Minimal AppHost using OrmLite AuthRepository

class AppHost : AppSelfHostBase
{
    public static ApiKey LastApiKey;

    public AppHost() : base(nameof(ApiKeyAuthTests), typeof(AppHost).GetAssembly()) { }

    public override void Configure(Container container)
    {
        var dbFactory = new OrmLiteConnectionFactory(":memory:", SqliteDialect.Provider);
        container.Register<IDbConnectionFactory>(dbFactory);

        container.Register<IAuthRepository>(c => new OrmLiteAuthRepository(dbFactory));
        container.Resolve<IAuthRepository>().InitSchema();

        Plugins.Add(new AuthFeature(() => new AuthUserSession(),
            new IAuthProvider[] {
                new ApiKeyAuthProvider(AppSettings) { RequireSecureConnection = false },
            })
        {
            IncludeRegistrationService = true,
        });

        GlobalRequestFilters.Add((req, res, dto) =>
        {
            LastApiKey = req.GetApiKey();
        });
    }
}

Register new User and Access their API Keys

appHost = new AppHost()
    .Init()
    .Start("http://*:2337/");

var client = new JsonServiceClient(ListeningOn);
var response = client.Post(new Register
{
    UserName = Username,
    Password = Password,
    Email = "as@if{0}.com",
    DisplayName = "DisplayName",
    FirstName = "FirstName",
    LastName = "LastName",
});

userId = response.UserId;
apiRepo = (IManageApiKeys)appHost.Resolve<IAuthRepository>();
var apiKeys = apiRepo.GetUserApiKeys(userId);
liveKey = apiKeys.First(x => x.Environment == "live");
testKey = apiKeys.First(x => x.Environment == "test");

A Minimal Authenicated Service

public class RequiresAuth : IReturn<RequiresAuth>
{
    public string Name { get; set; }
}

[Authenticate]
public class RequiresAuthService : Service
{
    public object Any(RequiresAuth request) => request;
}

Calling the Authenticated Service with an API Key

var client = new JsonServiceClient(ListeningOn)
{
    Credentials = new NetworkCredential(liveKey.Id, ""),
};

var request = new RequiresAuth { Name = "foo" };
var response = client.Send(request);
Assert.That(response.Name, Is.EqualTo(request.Name));

Assert.That(AppHost.LastApiKey.Id, Is.EqualTo(liveKey.Id));
like image 155
mythz Avatar answered Dec 18 '25 10:12

mythz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!