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?
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:
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();
});
}
}
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");
public class RequiresAuth : IReturn<RequiresAuth>
{
public string Name { get; set; }
}
[Authenticate]
public class RequiresAuthService : Service
{
public object Any(RequiresAuth request) => request;
}
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));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With