这是我的Auth配置:
container.Register<IAuthRepository>(c => new OrmLiteAuthRepository(c.Resolve<IDbConnectionFactory>()));
container.Resolve<IAuthRepository>().InitSchema();
Plugins.Add(new AuthFeature(() => new AuthUserSession(),
new IAuthProvider[]
{
new ApiKeyAuthProvider(AppSettings)
}));
然后我添加一个GlobalRequestFilter,这样我就可以检查实时与测试:
GlobalRequestFilters.Add((req, res, requestDto) =>
{
var user = req.GetUser();
var apikey = req.GetApiKey();
}
user和apikey都为null。
我使用嵌入apikey的方法作为基本身份验证的用户名。我在请求中看到了标题。这不会起作用吗?
答案 0 :(得分:4)
IRequest.GetUser()
是一种返回Windows Auth ASP.NET IPrincipal
的扩展方法(即,如果使用AspNetWindowsAuthProvider
),它与ServiceStack Auth无关,它基于User Sessions
但是应该返回API Key Auth Requests的ApiKey,如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));