ServiceStack ServerSentEvents 限制对通道的访问

ServiceStack ServerSentEvents restrict access to channel

在我的 ServiceStack 应用程序中,我想拒绝未经授权的用户访问频道 - 因此即使是加入事件也不会为未经授权的客户端触发。我正在使用不与数据库交互且目前非常简约的自定义身份验证提供程序(主要用于测试目的)

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!",
});

即使我跳过身份验证调用,其他客户端在尝试执行未经授权的 post(并收到错误)时仍会收到关于未经过身份验证的客户端的 onJoin 命令。此外,当我故意做多个未经授权的用户时,计数器增长 - 分配的用户名变为 username2,username3 等等 - 我怎样才能完全禁用未经授权的用户?用 Authenticate 标记我的 DTO 也没有改变任何东西。欢迎任何想法,也欢迎批评,因为我是 ServiceStack 的新手,想实施最佳实践。

已经有一个选项可以限制只有经过身份验证的用户才能访问:

Plugins.Add(new ServerEventsFeature {
    LimitToAuthenticatedUsers = true
});