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 .
but when I try to logout , locally it works and on the SWA it doesn't .
Anyone has an idea what the problem is? Screenshots for reference:
appsettings.json
{
"AzureAd": {
"Authority": "https://login.microsoftonline.com/TENANT-ID",
"ClientId": "CLIENT-ID",
"ValidateAuthority": true
}
}
staticwebapp.config.json
{
"networking": {
"allowedIpRanges": [
"IP/MASK"
]
}
}
Program.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
<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.
• While Enabling the authentication by injecting the [Authorize] attribute to the Razor pages (Counter.razor and FetchData.razor).Also add reference Microsoft.AspNetCore.Authorization
@attribute [Authorize]
@using Microsoft.AspNetCore.Authorization
In LoginDisplay.razor , check the below code for login and logout
@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
@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)
Workarounds that you may try:
Try 1: Clear all the cache , try login and logout.
Try 2: If all these are set properly and still facing the issue , Try with setting Redirect type to Web instead of 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:
- select Authentication in the menu.
- In the Logout URL section, set it to https:// localhost:5001/authentication/logout-callback
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.