Authentication
The authentication is done when the handshake is done and the protocol instance is created. The module responsible for authentication is the IXSocketAuthenticationPipeline
.
Add the template module
Under the XSockets.NET 5 templates you will find the AuthPipeline
Customize Authentication
How you implement this is totally up to you. Maybe you have cookie based authentication. If you the cookies can be extracted from the ConnectionContext
. If you have token based authentication you can find the token in the headers of the ConnectionContext
.
You can return false
to deny the connection. The protocol will then send back a error and then disconnect the client. If you return true the connection will be allowed even if there is no User
set to the ConnectionContext
using System.Security.Principal;
using XSockets.Core.Common.Protocol;
using XSockets.Core.Common.Socket;
using XSockets.Plugin.Framework.Attributes;
namespace MySample.Modules
{
[Export(typeof(IXSocketAuthenticationPipeline))]
public class MyAuthPipeline : IXSocketAuthenticationPipeline
{
public async Task<bool> GetPrincipal(IXSocketProtocol protocol)
{
if (protocol.ConnectionContext.User == null)
{
//You will find user info on the ConnectionContext
//fake, implement your own logic to set the User
var roles = new string[] { "superman", "hulk" };
var userIdentity = new GenericIdentity("David");
protocol.ConnectionContext.User = new GenericPrincipal(userIdentity, roles);
}
// Allow clients that is not authenticated
// If you return false the client will be disconnected
// with a SecurityException sent to the client
return true;
}
}
}
Example
Here we return false if the client was not authenticated in the IXSocketAuthenticationPipeline
using System.Security.Principal;
using XSockets.Core.Common.Protocol;
using XSockets.Core.Common.Socket;
using XSockets.Plugin.Framework.Attributes;
namespace MySample.Modules
{
[Export(typeof(IXSocketAuthenticationPipeline))]
public class MyAuthPipeline : IXSocketAuthenticationPipeline
{
public async Task<bool> GetPrincipal(IXSocketProtocol protocol)
{
// ...
// could not authenticate client, return false to disconnet
// ...
return false;
}
}
}
Putty as sample client
The handshake is ok, but when the AuthenticationPipeline
fails the connection is closed by the server