实现你自己的 Basic AuthProvider
您只需要继承BasicAuthProvider 并用您自己的实现覆盖TryAuthenticate 方法,例如:
public class MyBasicAuthProvider : BasicAuthProvider
{
public override bool TryAuthenticate(IServiceBase authService,
string userName, string password)
{
return MyIsValidLogin(userName, password);
}
}
然后在注册 AuthFeature 时将其提供给 ServiceStack,例如:
Plugins.Add(new AuthFeature(
() => new CustomUserSession(), //Use your own typed Custom UserSession type
new IAuthProvider[] {
new MyBasicAuthProvider()
});
这插入到 ServiceStack 的内置身份验证中,让您使用 HTTP BasicAuth 进行身份验证并使用内置的[Authenticate] 属性保护您的服务。
使用内置的 ServiceClient 发送基本身份验证
ServiceStack .NET Service Clients 通过设置用户名/密码字段内置了对基本身份验证请求的支持,即:
var client = new JsonServiceClient {
UserName = username,
Password = password
};
现在,当遇到未经身份验证的请求时,将使用 BasicAuth 凭据自动重新发送请求。要始终在您可以设置的每个请求上发送 BasicAuth:
client.AlwaysSendBasicAuthHeader = true;
使用全局请求过滤器手动验证 BasicAuth
使用 ServiceStack 内置身份验证的替代方法是使用全局请求过滤器,该过滤器手动提取 BasicAuth 用户名和密码,并在请求上设置一个标志以指示请求已通过身份验证,例如:
this.GlobalRequestFilters.Add((req, res, dto) => {
var userAndPass = req.GetBasicAuthUserAndPassword();
if (userAndPass == null)
return;
var username = userAndPass.Value.Key;
var password = userAndPass.Value.Value;
if (MyIsValidLogin(username, password)) {
//Set a flag that will be available for the entire request:
req.Items["UserAuthenticatedWithBasicAuth"] = username;
}
});
现在ServiceStack's Request pipeline 中的所有服务、属性过滤器和任何其他自定义逻辑都可以检查此标志以查看它是否已设置,例如:
public class MyServices : Service
{
public object Any(Request request)
{
var authenticatedUser = Request.Items["UserAuthenticatedWithBasicAuth"];
if (authenticatedUser != null) {
//this user was authenticated with BasicAuth
}
}
}