【发布时间】:2018-10-26 21:44:54
【问题描述】:
我正在尝试在我的后端应用(Azure 移动应用)中构建通知机制。 我设法覆盖了 Authorize 属性,以使通知中心仅可供授权用户访问。
public class QueryStringBearerAuthorizeAttribute : Microsoft.AspNet.SignalR.AuthorizeAttribute
{
public override bool AuthorizeHubConnection(HubDescriptor hubDescriptor, IRequest request)
{
try
{
var user = (request.Environment["server.User"] as ClaimsPrincipal).FindFirst(ClaimTypes.NameIdentifier).Value;
if (user == null)
return false;
return true;
}
catch(Exception ex)
{
return false;
}
}
public override bool AuthorizeHubMethodInvocation(IHubIncomingInvokerContext hubIncomingInvokerContext, bool appliesToMethod)
{
var connectionId = hubIncomingInvokerContext.Hub.Context.ConnectionId;
// check the authenticated user principal from environment
var environment = hubIncomingInvokerContext.Hub.Context.Request.Environment;
var principal = environment["server.User"] as ClaimsPrincipal;
if (principal != null && principal.Identity != null && principal.Identity.IsAuthenticated)
{
// create a new HubCallerContext instance with the principal generated from token
// and replace the current context so that in hubs we can retrieve current user identity
hubIncomingInvokerContext.Hub.Context = new HubCallerContext(new ServerRequest(environment), connectionId);
return true;
}
else
{
return false;
}
}
}
在 startup.cs 文件中:
var authorizer = new Hubs.QueryStringBearerAuthorizeAttribute();
var module = new AuthorizeModule(authorizer, authorizer);
GlobalHost.HubPipeline.AddModule(module);
app.MapSignalR();
通过控制台应用程序 (c#),我可以通过提供 X-ZUMO-AUTH 标头连接到通知中心。但是,在 Web 应用程序中,无法设置标头。
有没有办法使用查询字符串而不是标头来检查身份验证令牌?
【问题讨论】:
-
网络应用程序是什么意思?浏览器网站?
-
是的,我的意思是一个网站
-
你使用XHR还是fetch
-
xhr,这是我连接到 signalR 集线器的方式: $.ajaxSetup( { beforeSend: function (xhr) { xhr.setRequestHeader('token', 'value'); } }); $.connection.hub.url = 'myUrl/signalr'; $.connection.hub.start().done(function () { //stuff } 但是标头没有正确设置,在服务器端它没有被接收
-
你试过答案了吗?我环顾四周,对于 ZUMO Auth,您需要 Header: 'X-ZUMO-APPLICATION' 并将您的应用程序密钥添加为值。
标签: c# azure authentication signalr