如何解决使用 ASP.NET Core Blazor WebAssembly 的图形 API
我想从 Microsoft 图形 Web API 获取信息。我按照以下说明操作:
问题是 AuthenticateRequestAsync 方法中的变量“token”始终为空。这意味着 Blazor 应用没有获得令牌。
public async Task AuthenticateRequestAsync(HttpRequestMessage request)
{
var result = await TokenProvider.RequestAccessToken(
new AccessTokenRequestOptions()
{
Scopes = new[] { "https://graph.microsoft.com/User.Read" }
});
if (result.TryGetToken(out var token))
{
request.Headers.Authorization ??= new AuthenticationHeaderValue(
"Bearer",token.Value);
}
}
Program.cs 有以下代码:
builder.Services.AddScoped(sp => new HttpClient { BaseAddress = new Uri(builder.HostEnvironment.BaseAddress) });
builder.Services.AddMsalAuthentication<RemoteAuthenticationState,RemoteUserAccount>(options =>
{
options.ProviderOptions.DefaultAccessTokenScopes.Add("https://graph.microsoft.com/User.Read");
builder.Configuration.Bind("AzureAd",options.ProviderOptions.Authentication);
});
builder.Services.AddGraphClient("https://graph.microsoft.com/User.Read");
在 Index.razor 中,我只添加了两行代码 I OnInitializedAsync 方法
var request = GraphClient.Me.Request();
user = await request.GetAsync();
我花了很多时间来弄清楚主要问题是什么,但没有成功。我将不胜感激。
解决方法
我已经从您在评论中发布的 GitHub URL 克隆了您的存储库。 从Microsoft Graph API中获取数据的代码没有问题,问题是您在用户登录之前编写了当应用程序显示索引组件时调用API的代码,您必须检查是否用户首先登录并在 UI 中添加登录按钮,或者您可以将 [Authorize] 添加到索引页面,以便在显示组件之前将用户重定向到登录并制作 API 并实现该功能,请确保添加CascadingAuthenticationState 和 AuthorizeView 到你的 App.razor 如下
<CascadingAuthenticationState>
<Router AppAssembly="@typeof(Program).Assembly">
<Found Context="routeData">
<AuthorizeRouteView RouteData="@routeData" DefaultLayout="@typeof(MainLayout)">
<NotAuthorized>
@if (!context.User.Identity.IsAuthenticated)
{
<a class="btn btn-success" href="/authentication/login">Login with Microsoft</a>
}
else
{
<p>You are not authorized to access this resource.</p>
}
</NotAuthorized>
</AuthorizeRouteView>
</Found>
<NotFound>
<LayoutView Layout="@typeof(MainLayout)">
<p>Sorry,there's nothing at this address.</p>
</LayoutView>
</NotFound>
</Router>
</CascadingAuthenticationState>
然后在您的 Index.razor 中在顶部添加以下行
@attribute [Authorize]
然后,如果用户未登录,则启动应用程序,他/她将被要求这样做,然后转到 Index 组件并进行 API 调用,然后将成功
,请想象一下单页网站。通常,这种页面有一个“联系我们”标签,其中有联系表格。如果用户填写了联系表格,那么数据必须以某种方式发送给我们。为此,我尝试使用 MS 图形 API。当用户单击提交按钮时,将在后台创建我的帐户的注册并向我发送一封电子邮件。这意味着用户不知道任何注册程序。 ——萨莫·西蒙西奇
为了让您的应用能够在租户中创建用户,它需要使用需要机密的仅限应用的流程。我们不建议仅公开此类性质的应用流,因为这些流很容易被利用来创建虚假用户或压倒您的租户,并向公众开放。
最好的方法是在本地数据库中进行这些注册,然后让守护程序应用程序在后台处理它们。这是示例,其中 daemon console application is calling Microsoft Graph.
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。