2016-02-16 29 views
1

在我的ServiceStack应用程序中,我想拒绝未经授权的用户访问频道,因此即使连接事件也不会针对未经授权的客户端触发。我使用的是不与数据库进行交互,是现在很简约(主要用于测试目的)的定制身份验证提供商ServiceStack ServerSentEvents限制访问渠道

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不是用户名1 ...用户名N,但没有运气。我的客户端代码

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 = "[email protected]", 
    Password = "[email protected]", 
    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也没有改变任何东西。欢迎任何想法以及Cryology,因为我是ServiceStack的新手,并希望实施最佳实践。

回答

2

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

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

这个工作,虽然我不得不删除开始()从客户呼叫和呼叫连接()。这确实是正确的答案。还想了解如何覆盖用户名,但这是我相信一个单独问题的主题 – HardLuck