基本認証と SSL の両方を使用する自己ホスト型 (コンソール アプリ内) の SignalR ハブがあります。
ハブ クラスは次のとおりです。
[HubName("TestingHub")]
[Authorize(Mode=AuthorizeMode.Both)]
public class TestingHub : Hub
{
public void TestMethod(int arg)
{
Console.WriteLine("Arg: {0}", arg);
}
public string TestWebClientCall(string message)
{
Clients.Caller.clientFunction(string.Format("From the server : {0}", message));
return "Call Worked";
}
}
セルフホスティングは次のように行われます。
var url = "https://localhost:3232/";
var server = new Server(url);
server.Configuration.DisconnectTimeout = TimeSpan.Zero;
var authoriser = new Authoriser();
server.HubPipeline.AddModule(new AuthorizeModule(authoriser, authoriser));
server.AuthenticationSchemes = AuthenticationSchemes.Basic;
server.MapHubs();
server.Start();
Authoriser クラスは次のとおりです。
public class Authoriser : IAuthorizeHubConnection, IAuthorizeHubMethodInvocation
{
bool isAuthorised(HttpListenerBasicIdentity identity)
{
var authorised = Membership.Provider.ValidateUser(identity.Name, identity.Password);
return authorised;
}
public bool AuthorizeHubConnection(HubDescriptor hubDescriptor, IRequest request)
{
var identity = (HttpListenerBasicIdentity)request.User.Identity;
return isAuthorised(identity);
}
public bool AuthorizeHubMethodInvocation(IHubIncomingInvokerContext hubIncomingInvokerContext)
{
var identity = (HttpListenerBasicIdentity)hubIncomingInvokerContext.Hub.Context.User.Identity;
return isAuthorised(identity);
}
}
次に、MVC Razor ページの JavaScript は次のとおりです。
$(document).ready(function () {
var hubUrl = "https://localhost:3232/";
$.connection.hub.url = hubUrl;
var hub = $.connection.TestingHub;
if (hub == undefined) {
alert("hub not found at " + hubUrl);
}
else {
$.extend(hub, {
clientFunction: function (textMessage) {
alert("clientFunction called : " + textMessage);
}
});
$.connection.hub.start()
.done(function() {
hub.server.testWebClientCall('Hello from the client')
.done(function (message) {
alert(message);
});
})
.fail(function() {
alert("could not connect!");
});
}
});
何が起こるかは次のとおりです。
- ページが読み込まれ、Basic Auth ログイン ボックスがポップアップ表示されます。ユーザー名とパスワードが入力されます。
- Basic Authログインボックスが再びポップアップします-SignalR /ハブ用のスクリプトインクルードを推測しています
- 「ハブ」オブジェクトは有効です。つまり、「TestingHub」が表示されます
- $.connection.hub.start() 呼び出しは常に .fail になり、hub.server.testWebClientCall は試行されません。
.NET コンソール アプリ クライアントからアクセスできるため、SSL 証明書はすべてセルフ ホスティング用に適切にセットアップされています。
問題は、基本認証と SSL の両方が関与するこの自己ホスト型ハブに対して、これをどのように行うべきかということです。認証を通過するために、ユーザー名とパスワードの組み合わせを SignalR ハブ/呼び出しに渡すにはどうすればよいですか?
参考までに、この種のアプローチをテストしているのは、現在、HTTPS/SSL を介したフォーム認証を介して保護されている MVC3 サイトがあり、私の質問の別の 1 つに従って、安全でない自己ホスト型 SignalR ハブ (つまり、HTTPS 以外) にアクセスするためです。 /SSL) を MVC サイトから HTTP/SSL で使用しても機能しないようです。
SignalR サンプルでは、「ホスティング」(つまり AuthHub クラス) に関する承認の詳細を見つけましたが、Web クライアントから接続する方法については何も見つかりません - 「現実世界」が不足しているようです。サンプル - つまり、完全な認証と SSL 暗号化を使用します。