在我的ServiceStack应用程序中,我想拒绝为未经授权的用户访问频道 - 因此即使是加入事件也不会触发未经授权的客户端。我正在使用不与DB交互的自定义身份验证提供程序,现在非常简约(主要用于测试目的)
public class RoomsAuthProvider : CredentialsAuthProvider
{
private int userId = 0;
public RoomsAuthProvider(AppSettings appSettings) : base(appSettings)
{
}
public RoomsAuthProvider()
{
}
public override bool TryAuthenticate(IServiceBase authService,
string userName, string password)
{
if (password == "ValidPassword")
{
return true;
}
else
{
return false;
}
}
public override IHttpResult OnAuthenticated(IServiceBase authService,
IAuthSession session, IAuthTokens tokens,
Dictionary<string, string> authInfo)
{
//Fill IAuthSession with data you want to retrieve in the app eg:
session.FirstName = "some_firstname_from_db";
//...
//Call base method to Save Session and fire Auth/Session callbacks:
return base.OnAuthenticated(authService, session, tokens, authInfo);
//session.CreatedAt = DateTime.Now;
//session.DisplayName = "CustomDisplayName" + userId;
//session.IsAuthenticated = true;
//session.UserAuthName = session.UserName;
//session.UserAuthId = userId.ToString();
//Interlocked.Increment(ref userId);
//authService.SaveSession(session, SessionExpiry);
//return null;
}
}
主要服务:
[Authenticate]
public class ServerEventsService : Service
{
...
}
旁注 - 我试过覆盖默认的DisplayUsername,不是username1 ... usernameN但没有运气。我的客户端代码是
var client = new ServerEventsClient("http://localhost:1337/", "home")
{
OnConnect = OnConnect,
OnCommand = HandleIncomingCommand,
OnMessage = HandleIncomingMessage,
OnException = OnException,
OnHeartbeat = OnHeartbeat
}.Start();
client.Connect().Wait();
var authResponse = client.Authenticate(new Authenticate
{
provider = "credentials",
UserName = "test@gmail.com",
Password = "p@55w0rd",
RememberMe = true,
});
client.ServiceClient.Post(new PostChatToChannel
{
Channel = "home", // The channel we're listening on
From = client.SubscriptionId, // Populated after Connect()
Message = "Hello, World!",
});
即使我跳过身份验证调用,其他客户端仍然会在尝试执行未经授权的帖子(并收到错误)时获取有关未经过身份验证的客户端的onJoin命令。此外,当我故意做多个未经授权的用户计数器增长 - 分配的用户名变为username2,username3等等 - 如何完全禁用未经授权的用户?用Authenticate标记我的DTO也没有改变任何东西。欢迎提出任何想法以及我对ServiceStack不熟悉的想法,并希望实施最佳实践。
答案 0 :(得分:2)
已经有一个选项可以限制对经过身份验证的用户的访问:
Plugins.Add(new ServerEventsFeature {
LimitToAuthenticatedUsers = true
});