问题描述
尝试使用功能键(AuthorizationLevel.Function)保护我的Azure功能
我的天蓝色函数使用signalR。 如果我在协商和其他SignalR入口点上使用AuthorizationLevel.Function,那么当javascript代码连接到signalR时如何传递功能键: 功能:
public static SignalRConnectionInfo Negotiate(
[HttpTrigger( AuthorizationLevel.Function,"post" )] HttpRequest req,[SignalRConnectionInfo( HubName = "myHub")] SignalRConnectionInfo connectionInfo,ILogger log )
{
return connectionInfo;
}
网站:
const connection = new signalR.HubConnectionBuilder()
.withUrl('https://<myfunction>.azurewebsites.net')
.configureLogging(signalR.LogLevel.information)
.build();
connection.start()
.catch(console.error);
似乎HubConnectionBuilder可以在c#中访问标头,但不能在javascript中访问。
我已阅读Add headers to @aspnet/signalr Javascript client 但是第一个建议将密钥附加到url,并且在连接时会将/ negotiate附加到该URL,从而导致https:// host /&code = / negotiate无效的url。
如果不可能,建议使用其他方法来保护我的signalR功能吗? (也许是https://docs.microsoft.com/en-us/aspnet/core/signalr/authn-and-authz?view=aspnetcore-3.1中的不记名令牌)
谢谢
解决方法
如果您查看the documentation of the withUrl method,它将允许options对象作为第二个参数:
function withUrl(url: string,options: IHttpConnectionOptions)
选项的类型为IHttpConnectionOptions,它提供了一些可能性:
a)您可以提供IHttpConnectionOptions.accessTokenFactory的实现,该实现应返回Bearer令牌(要正常工作,您需要在Azure函数中手动验证Bearer令牌)
b)您可以提供自己的HttpClient实现,在该实现中,您可以通过添加Azure功能键来修改Post请求,如下所示:
const connection = new signalR.HubConnectionBuilder()
.withUrl('https://<myfunction>.azurewebsites.net',{
httpClient: {
post: (url,httpOptions) => {
const headers = {
...httpOptions.headers,'x-functions-key': YOUR_AZURE_FUNCTION_KEY,}
return axios.post(url,{},{ headers }).then((response) => {
return (newResponse = {
statusCode: response.status,statusText: response.statusText,content: JSON.stringify(response.data),})
})
},},})
.configureLogging(signalR.LogLevel.Information)
.build()
来源:
https://docs.microsoft.com/en-us/aspnet/core/signalr/javascript-client?view=aspnetcore-3.1
How to pass Custom Header from React JS client to SignalR hub?
,正如 my answer 中对此问题链接的问题所述,您现在可以执行以下操作:
const connection = new signalR.HubConnectionBuilder()
.withUrl('https://<myfunction>.azurewebsites.net',{
headers: {'x-functions-key': YOUR_AZURE_FUNCTION_KEY}
})
.build();