过了一段时间我找到了解决方案!
基本上,您会收到来自 AAD 的 ClaimsPrincipal,但您必须使用 AAD ClaimsPrincipal 中的声明在应用程序内创建自己的 ClaimsPrincipal。
在ExternalAuthStateProvider.cs的LoginWithExternalProviderAsync()方法中,我执行了以下操作:
private async Task<ClaimsPrincipal> LoginWithExternalProviderAsync()
{
var authenticationResult = await _platformService.GetAuthenticationResult();
var authenticatedUser = new ClaimsPrincipal(new ClaimsIdentity(authenticationResult.ClaimsPrincipal.Claims, "Basic"));
return await Task.FromResult(authenticatedUser);
}
你只需要这样做,然后它就起作用了!
额外的 - - - - - -
为了改善登录注销流程,我创建了一个LoginPage.razor:
@page "/login"
@using Microsoft.AspNetCore.Authorization
@using Microsoft.AspNetCore.Components.Authorization
@using OfficeManagerApp.Areas.Services.Implementations
@attribute [AllowAnonymous]
@inject AuthenticationStateProvider AuthenticationStateProvider
@inject NavigationManager NavigationManager
<button @onclick="Login">Log in</button>
@code
{
public async Task Login()
{
await ((ExternalAuthStateProvider)AuthenticationStateProvider)
.LogInAsync();
NavigationManager.NavigateTo("/");
}
}
更改了 RedirectToLogin,razor:
@inject NavigationManager NavigationManager
<div class="loader loader-bouncing"><span>Redirecting...</span></div>
@code {
protected override void OnInitialized()
{
NavigationManager.NavigateTo("/login");
}
}
并添加了注销方法:
private void Logout(){
((ExternalAuthStateProvider)AuthenticationStateProvider)
.Logout();
}
还对我的 Main.razor 做了一些更改:
<CascadingAuthenticationState>
<Router AppAssembly="@typeof(Main).Assembly">
<Found Context="routeData">
<AuthorizeRouteView RouteData="@routeData" DefaultLayout="@typeof(MainLayout)">
<Authorizing>
Authorizing...
</Authorizing>
<NotAuthorized>
@if (!context.User.Identity.IsAuthenticated)
{
<RedirectToLogin />
}
else
{
<p>You are not authorized to access this resource.</p>
}
</NotAuthorized>
</AuthorizeRouteView>
</Found>
<NotFound>
<LayoutView Layout="@typeof(MainLayout)">
<p role="alert">Sorry, there's nothing at this address.</p>
</LayoutView>
</NotFound>
</Router>
</CascadingAuthenticationState>
请注意,不要忘记添加到您的 _Imports.razor:
@using Microsoft.AspNetCore.Components.Authorization