使用Azure AD的SignalR(Blazor Server聊天应用程序)

dwbf0jvd  于 2023-01-21  发布在  其他
关注(0)|答案(2)|浏览(140)

https://learn.microsoft.com/en-us/azure/azure-signalr/signalr-tutorial-build-blazor-server-chat-app
如何使此功能与激活的Azure AD一起工作?当我在Visual Studio中本地运行时,它工作完美,但当部署时,它将不与Azure AD一起工作,只有当我删除Azure AD时,它才能工作。
这是部署时和单击用户名文本框旁边的按钮"聊天!"后的错误消息:

  • "错误:无法启动聊天客户端:响应状态代码未指示成功:403(禁止)。"*

(我已经找到了其他像这样的线程Blazor Server SignalR Chat works on Local, not on Azure,但没有解决方案)
//Program.cs

using BlazorApp6ADChat;
using BlazorApp6ADChat.Data;
using BlazorChat;
using Microsoft.AspNetCore.Authentication.OpenIdConnect;
using Microsoft.Identity.Web;
using Microsoft.Identity.Web.UI;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
    .AddMicrosoftIdentityWebApp(builder.Configuration.GetSection("AzureAd"));
builder.Services.AddControllersWithViews()
    .AddMicrosoftIdentityUI();

builder.Services.AddAuthorization(options =>
{
    // By default, all incoming requests will be authorized according to the default policy
    options.FallbackPolicy = options.DefaultPolicy;
});

builder.Services.AddRazorPages();
builder.Services.AddServerSideBlazor()
    .AddMicrosoftIdentityConsentHandler();
builder.Services.AddSingleton<WeatherForecastService>();

var app = builder.Build();

// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Error");
    // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
    app.UseHsts();
}

app.UseHttpsRedirection();

app.UseStaticFiles();

app.UseRouting();

app.MapControllers();
app.MapBlazorHub();
app.MapFallbackToPage("/_Host");
app.MapHub<BlazorChatSampleHub>(BlazorChatSampleHub.HubUrl);

app.UseAuthentication();
app.UseAuthorization();

app.Run();

//appsettings.json

{
  "AzureAd": {
    "Instance": "https://login.microsoftonline.com/",
    "Domain": "xxx.onmicrosoft.com",
    "TenantId": "xxx",
    "ClientId": "xxx",
    "CallbackPath": "/signin-oidc"
  },
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "AllowedHosts": "*"
}

qmb5sa22

qmb5sa221#

不确定这是否有帮助。这是我如何用SignalR集线器连接WebAssembly主机(服务器)的。

services.TryAddEnumerable(
    ServiceDescriptor.Singleton<IPostConfigureOptions<JwtBearerOptions>,
    ConfigureJwtBearerOptions>());
public class ConfigureJwtBearerOptions : IPostConfigureOptions<JwtBearerOptions>
{
    public void PostConfigure(string name, JwtBearerOptions options)
    {
        var originalOnMessageReceived = options.Events.OnMessageReceived;
        options.Events.OnMessageReceived = async context =>
        {
            await originalOnMessageReceived(context);

            if (string.IsNullOrEmpty(context.Token))
            {
                var accessToken = context.Request.Query["access_token"];
                var requestPath = context.HttpContext.Request.Path;
                var endPoint = $"/chathub";

                if (!string.IsNullOrEmpty(accessToken) &&
                    requestPath.StartsWithSegments(endPoint))
                {
                    context.Token = accessToken;
                }
            }
        };
    }
}
gwbalxhn

gwbalxhn2#

我在这里发布了一个解决方案:Microsoft Learn
基本上:
1.手动获取主机.cshtml页面中的Cookie
1.将Cookie集合传递给app.razor,以便创建级联参数
1.示例化SignalR客户端时检索参数并手动填充Cookie容器(您可能在Web上看到过此代码,但如果没有步骤1和2,它将无法在Azure上工作,只能在IIS Express中工作)
Program.cs

public class Program
{
    public static void Main(string[] args)
    {
        var builder = WebApplication.CreateBuilder(args);

        builder.Services.AddAutoMapper(typeof(Program).Assembly);

         builder.Services.AddHttpClient();
        builder.Services.AddHttpContextAccessor();
        builder.Services.AddScoped<HttpContextAccessor>();          

        builder.Services.AddResponseCompression(opts =>
        {
            opts.MimeTypes = ResponseCompressionDefaults.MimeTypes.Concat(
                new[] { "application/octet-stream" });
        });

        var app = builder.Build();

        app.UseResponseCompression();

        app.UseRouting();

        app.UseAuthentication();
        app.UseAuthorization();

        app.MapControllers();
        app.MapBlazorHub();
  
        app.MapHub<ChatHub>("/chathub");
        app.MapFallbackToPage("/_Host");

        app.Run();
    }
}

_主机.cshtml:

<body>
    @{
        var CookieCollection = HttpContext.Request.Cookies;
        Dictionary<string, string> Cookies = new Dictionary<string, string>();
        foreach (var cookie in CookieCollection)
        {
            Cookies.Add(cookie.Key, cookie.Value);
        }        
    }
    <component type="typeof(App)" render-mode="ServerPrerendered" param-Cookies="Cookies" />

app.razor:

<CascadingValue Name="Cookies" Value="Cookies">
<CascadingAuthenticationState>
    <Router AppAssembly="@typeof(App).Assembly">
        <Found Context="routeData">
            <AuthorizeRouteView RouteData="@routeData" DefaultLayout="@typeof(MainLayout)" />
            <FocusOnNavigate RouteData="@routeData" Selector="h1" />
        </Found>
        <NotFound>
            <PageTitle>Not found</PageTitle>
            <LayoutView Layout="@typeof(MainLayout)">
                <p role="alert">Sorry, there's nothing at this address.</p>
            </LayoutView>
        </NotFound>
    </Router>
</CascadingAuthenticationState>
</CascadingValue>
@code {
    [Parameter] public Dictionary<string, string> Cookies { get; set; }
}

Index.razor:

@code {
    #nullable disable
    [CascadingParameter(Name = "Cookies")] public Dictionary<string, string> Cookies { get; set; }    

    System.Security.Claims.ClaimsPrincipal CurrentUser;
    private HubConnection hubConnection;
    private List<string> messages = new List<string>();
    private string userInput;
    private string messageInput;
    private string strError = "";

    protected override async Task OnInitializedAsync()
    {
        try
        {
            var authState = await AuthenticationStateProvider.GetAuthenticationStateAsync();

            CurrentUser = authState.User;

            // ** SignalR Chat

            try
            {
                hubConnection = new HubConnectionBuilder()
                 .WithUrl(Navigation.ToAbsoluteUri("/chathub"), options =>
                 {
                     options.UseDefaultCredentials = true;
                     var cookieCount = Cookies.Count();
                     var cookieContainer = new CookieContainer(cookieCount);
                     foreach (var cookie in Cookies)
                         cookieContainer.Add(new Cookie(
                             cookie.Key,
                             WebUtility.UrlEncode(cookie.Value),
                             path: "/",
                             domain: Navigation.ToAbsoluteUri("/").Host));
                     options.Cookies = cookieContainer;

                     foreach (var header in Cookies)
                         options.Headers.Add(header.Key, header.Value);

                     options.HttpMessageHandlerFactory = (input) =>
                     {
                         var clientHandler = new HttpClientHandler
                             {
                                 PreAuthenticate = true,
                                 CookieContainer = cookieContainer,
                                 UseCookies = true,
                                 UseDefaultCredentials = true,
                             };
                         return clientHandler;
                     };
                 })
                 .WithAutomaticReconnect()
                 .Build();

                hubConnection.On<string, string>("ReceiveMessage", (user, message) =>
                {
                    var encodedMsg = $"{user}: {message}";
                    messages.Add(encodedMsg);
                    InvokeAsync(StateHasChanged);
                });

                await hubConnection.StartAsync();
            }
            catch(Exception ex)
            {
                strError = ex.Message;
            }

        }
        catch
        {
            // do nothing if this fails
        }
    }

    // ** SignalR Chat
    private async Task Send()
    {
        if (hubConnection is not null)
        {
            await hubConnection.SendAsync("SendMessage", messageInput);
        }
    }

    public bool IsConnected =>
        hubConnection?.State == HubConnectionState.Connected;

    public async ValueTask DisposeAsync()
    {
        if (hubConnection is not null)
        {
            await hubConnection.DisposeAsync();
        }
    }
}

ChatHub.cs:

[Authorize]
public class ChatHub : Hub
{
    public async override Task OnConnectedAsync()
    {
        if (this.Context.User?.Identity?.Name != null)
        {
            await Clients.All.SendAsync(
                "broadcastMessage", 
                "_SYSTEM_", 
                $"{Context.User.Identity.Name} JOINED");
        }
    }
    public async Task SendMessage(string message)
    {
        if (this.Context.User?.Identity?.Name != null)
        {
            await Clients.All.SendAsync(
                "ReceiveMessage", 
                this.Context.User.Identity.Name, 
                message);
        }
    }
}

相关问题