[英]Blazor WASM Authentication Static Web App
I've got a problem which I quite don't understand yet (used doc: https://docs.microsoft.com/en-us/aspnet/core/blazor/security/?view=aspnetcore-6.0 ) , if I try to login , it works on the Static Web App ( SWA ) and locally .我有一个我还不太明白的问题(使用文档: https : //docs.microsoft.com/en-us/aspnet/core/blazor/security/? view = aspnetcore- 6.0 ),如果我尝试登录,它适用于静态 Web 应用程序 ( SWA ) 和本地。
but when I try to logout , locally it works and on the SWA it doesn't .但是当我尝试注销时,它在本地工作,而在SWA上却没有。
Anyone has an idea what the problem is?任何人都知道问题是什么? Screenshots for reference:
截图供参考:
Portal app registration:门户应用注册:
appsettings.json appsettings.json
{
"AzureAd": {
"Authority": "https://login.microsoftonline.com/TENANT-ID",
"ClientId": "CLIENT-ID",
"ValidateAuthority": true
}
}
staticwebapp.config.json静态webapp.config.json
{
"networking": {
"allowedIpRanges": [
"IP/MASK"
]
}
}
Program.cs程序.cs
public class Program
{
public static async Task Main(string[] args)
{
var builder = WebAssemblyHostBuilder.CreateDefault(args);
builder.RootComponents.Add<App>("#app");
builder.Services.AddSingleton<IProductService<ProductA,InsuredPerson>, ProductAService>();
builder.Services.AddSingleton<IProductService<ProductB,InsuredPerson>, ProductBService>();
builder.Services.AddSingleton<IDownloadService,DownloadService>();
builder.Services.AddSingleton<IUploadService, UploadService>();
builder.Services.AddAutoMapper(new[] { typeof(ServiceMappingProfile)});
builder.Services.AddHttpClient();
builder.Services.AddScoped(sp => new HttpClient { BaseAddress = new Uri(builder.HostEnvironment.BaseAddress) });
builder.Services.AddLocalization();
builder.Services.AddMsalAuthentication(options =>
{
builder.Configuration.Bind("AzureAd", options.ProviderOptions.Authentication);
options.ProviderOptions.DefaultAccessTokenScopes
.Add("https://graph.microsoft.com/User.Read");
options.ProviderOptions.LoginMode = "redirect";
});
var host = builder.Build();
CultureInfo culture;
var js = host.Services.GetRequiredService<IJSRuntime>();
var result = await js.InvokeAsync<string>("blazorCulture.get");
if (result != null)
{
culture = new CultureInfo(result);
}
else
{
culture = new CultureInfo("en-US");
await js.InvokeVoidAsync("blazorCulture.set", "en-US");
}
CultureInfo.DefaultThreadCurrentCulture = culture;
CultureInfo.DefaultThreadCurrentUICulture = culture;
await host.RunAsync();
}
}
App.razor应用程序.razor
<CascadingAuthenticationState>
<Router AppAssembly="@typeof(App).Assembly">
<Found Context="routeData">
<AuthorizeRouteView RouteData="@routeData" DefaultLayout="@typeof(MainLayout)">
<NotAuthorized>
@if (context.User.Identity?.IsAuthenticated != true)
{
<RedirectToLogin />
}
else
{
<p role="alert">You are not authorized to access this resource.</p>
}
</NotAuthorized>
</AuthorizeRouteView>
<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>
Please check these points while configuring:配置时请检查以下几点:
• Install the NuGet package Microsoft.Authentication.WebAssembly.Msal
to authenticate your application using NuGet Manager. • 安装 NuGet 包
Microsoft.Authentication.WebAssembly.Msal
以使用 NuGet 管理器对您的应用程序进行身份验证。
• While Enabling the authentication by injecting the [Authorize] attribute to the Razor pages (Counter.razor and FetchData.razor).Also add reference Microsoft.AspNetCore.Authorization • 通过将 [Authorize] 属性注入Razor 页面(Counter.razor 和 FetchData.razor)来启用身份验证。同时添加参考 Microsoft.AspNetCore.Authorization
@attribute [Authorize]
@using Microsoft.AspNetCore.Authorization
In LoginDisplay.razor , check the below code for login and logout在LoginDisplay.razor 中,检查下面的登录和注销代码
@using Microsoft.AspNetCore.Components.Authorization
@using Microsoft.AspNetCore.Components.WebAssembly.Authentication
@inject NavigationManager Navigation
@inject SignOutSessionStateManager SignOutManager
<AuthorizeView>
<Authorized>
Hello, @context.User.Identity.Name!
<button class="nav-link btn btn-link" @onclick="BeginLogout">
Log out
</button>
</Authorized>
<NotAuthorized>
<a href="authentication/login">Log in</a>
</NotAuthorized>
</AuthorizeView>
@code {
private async Task BeginLogout(MouseEventArgs args)
{
await SignOutManager.SetSignOutState();
Navigation.NavigateTo("authentication/logout");
}
}
Pages/Authentication.razor页面/Authentication.razor
@page "/authentication/{action}"
@using Microsoft.AspNetCore.Components.WebAssembly.Authentication
<RemoteAuthenticatorView Action="@Action" />
@code {
[Parameter]
public string Action { get; set; }
}
Reference : Using Azure Active Directory to Secure a Blazor WebAssembly Standalone App (code-maze.com)参考: 使用 Azure Active Directory 保护 Blazor WebAssembly 独立应用程序 (code-maze.com)
Workarounds that you may try:您可以尝试的解决方法:
Try 1: Clear all the cache , try login and logout.尝试1:清除所有缓存,尝试登录和注销。
Try 2: If all these are set properly and still facing the issue , Try with setting Redirect type to Web instead of SPA.尝试 2:如果所有这些都设置正确但仍然面临问题,请尝试将重定向类型设置为 Web 而不是 SPA。
For example:例如:
Try 3: Include "post_logout_redirect_uri": "https://localhost:5001/authentication/logout-callback", In the json file of app where the redirect uri is mentioned And give that url in logout url in portal in the app's registration screen:尝试 3:包括“post_logout_redirect_uri”:“https://localhost:5001/authentication/logout-callback”,在提到重定向 uri 的应用程序的 json 文件中,并在应用程序注册屏幕的门户中的注销 url 中给出该 url :
- select Authentication in the menu.
在菜单中选择身份验证。
- In the Logout URL section, set it to https:// localhost:5001/authentication/logout-callback
在注销 URL 部分,将其设置为 https:// localhost:5001/authentication/logout-callback
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.