图 API 与 ASP.NET Core Blazor WebAssembly
Graph API with ASP.NET Core Blazor WebAssembly
我想从 Microsoft graph web API 获取信息。我遵循了这些说明:
问题是 AuthenticateRequestAsync 方法中的变量“token”始终为 null。这意味着 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我只是添加了两行代码我OnInitializedAsync方法
var request = GraphClient.Me.Request();
user = await request.GetAsync();
我花了很多时间找出主要问题是什么但没有成功。我将不胜感激任何帮助。
不确定问题的原因。
但我可以使用以下代码和配置使其工作:
Program.cs
public static async Task Main(string[] args)
{
var builder = WebAssemblyHostBuilder.CreateDefault(args);
builder.RootComponents.Add<App>("app");
// Adds the Microsoft graph client (Graph SDK) support for this app.
builder.Services.AddMicrosoftGraphClient("https://graph.microsoft.com/User.Read");
// Integrates authentication with the MSAL library
builder.Services.AddMsalAuthentication(options =>
{
builder.Configuration.Bind("AzureAd", options.ProviderOptions.Authentication);
options.ProviderOptions.DefaultAccessTokenScopes.Add("https://graph.microsoft.com/User.Read");
});
await builder.Build().RunAsync();
}
appsettings.json
{
"AzureAd": {
"Authority": "https://login.microsoftonline.com/exxxxx4e-bd27-40d5-8459-230ba2xxxxxb",
"ClientId": "7xxxxxx8-88b3-4c02-a2f8-0a890xxxxxx5",
"CallbackPath": "/signin-oidc",
"ValidateAuthority": "true",
"DefaultScopes": [
"openid",
"profile"
]
}
}
您可以参考配置和示例代码here。
我已经从您在评论中发布的 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]
如果用户未登录,则启动应用程序,he/she 将被要求这样做,然后转到索引组件并进行 API 调用,然后调用成功
Please imagine the single-page website. Usually, this kind of page has a "contact us" tab where is the contact form. If the user fills up the contact form then data have to be somehow sent to us. For this purpose, I tried to use MS graph API. When the user clicks the submit button, in the background the registration to my account will be created and an email will be sent to me. It means that the user is not aware of any registration procedure. – Samo Simoncic
为了让您的应用能够在租户中创建用户,它需要使用需要密钥的应用专用流。我们不建议公开这种性质的仅应用程序流,它很容易被利用来创建虚假用户或淹没您的租户,对一般人开放 public.
最好的方法是在本地数据库中进行此注册,然后让守护程序应用程序在后台处理它们。这是示例,其中 daemon console application is calling Microsoft Graph.
我想从 Microsoft graph web API 获取信息。我遵循了这些说明:
问题是 AuthenticateRequestAsync 方法中的变量“token”始终为 null。这意味着 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我只是添加了两行代码我OnInitializedAsync方法
var request = GraphClient.Me.Request();
user = await request.GetAsync();
我花了很多时间找出主要问题是什么但没有成功。我将不胜感激任何帮助。
不确定问题的原因。
但我可以使用以下代码和配置使其工作:
Program.cs
public static async Task Main(string[] args)
{
var builder = WebAssemblyHostBuilder.CreateDefault(args);
builder.RootComponents.Add<App>("app");
// Adds the Microsoft graph client (Graph SDK) support for this app.
builder.Services.AddMicrosoftGraphClient("https://graph.microsoft.com/User.Read");
// Integrates authentication with the MSAL library
builder.Services.AddMsalAuthentication(options =>
{
builder.Configuration.Bind("AzureAd", options.ProviderOptions.Authentication);
options.ProviderOptions.DefaultAccessTokenScopes.Add("https://graph.microsoft.com/User.Read");
});
await builder.Build().RunAsync();
}
appsettings.json
{
"AzureAd": {
"Authority": "https://login.microsoftonline.com/exxxxx4e-bd27-40d5-8459-230ba2xxxxxb",
"ClientId": "7xxxxxx8-88b3-4c02-a2f8-0a890xxxxxx5",
"CallbackPath": "/signin-oidc",
"ValidateAuthority": "true",
"DefaultScopes": [
"openid",
"profile"
]
}
}
您可以参考配置和示例代码here。
我已经从您在评论中发布的 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]
如果用户未登录,则启动应用程序,he/she 将被要求这样做,然后转到索引组件并进行 API 调用,然后调用成功
Please imagine the single-page website. Usually, this kind of page has a "contact us" tab where is the contact form. If the user fills up the contact form then data have to be somehow sent to us. For this purpose, I tried to use MS graph API. When the user clicks the submit button, in the background the registration to my account will be created and an email will be sent to me. It means that the user is not aware of any registration procedure. – Samo Simoncic
为了让您的应用能够在租户中创建用户,它需要使用需要密钥的应用专用流。我们不建议公开这种性质的仅应用程序流,它很容易被利用来创建虚假用户或淹没您的租户,对一般人开放 public.
最好的方法是在本地数据库中进行此注册,然后让守护程序应用程序在后台处理它们。这是示例,其中 daemon console application is calling Microsoft Graph.