使用Blazor服务器和Azure AD身份验证获取身份验证令牌

时间:2020-09-01 15:00:00

标签: authentication azure-active-directory blazor-server-side

我已使用Blazor服务器应用程序设置了Azure AD身份验证。有用。我被重定向到登录名,然后返回到应用程序。

在Startup.cs中:

services.AddAuthentication(AzureADDefaults.AuthenticationScheme)
    .AddAzureAD(options => Configuration.Bind("AzureAd", options));

services.AddControllersWithViews(options =>
{
    var policy = new AuthorizationPolicyBuilder()
        .RequireAuthenticatedUser()
        .Build();
    options.Filters.Add(new AuthorizeFilter(policy));
});

我可以通过以下方式获得索赔

var authState = await AuthenticationStateProvider.GetAuthenticationStateAsync();
var user = authState.User; 

但是如何获得身份验证令牌?我想要它,以便可以使用它与Microsoft Graph进行身份验证。除了包含身份验证令牌(已选中)的复选框,我在Azure AD中找不到任何其他内容。有什么想法吗?

编辑我对可接受答案的更改:

var scopes = new[] { "user.read" };
services.AddMicrosoftIdentityWebAppAuthentication(Configuration, "AzureAd")
    .EnableTokenAcquisitionToCallDownstreamApi(scopes)
    .AddInMemoryTokenCaches();

services.AddDownstreamWebApiService(Configuration);
services.AddMicrosoftGraph(scopes, "https://graph.microsoft.com/v1.0");

services.AddControllersWithViews(options =>
{
    var policy = new AuthorizationPolicyBuilder()
        .RequireAuthenticatedUser()
        .Build();
    options.Filters.Add(new AuthorizeFilter(policy));
}).AddMicrosoftIdentityUI();

1 个答案:

答案 0 :(得分:2)

您可以将this demo project in github与Azure AD身份验证配合使用,该身份代表登录用户来调用Microsoft Graph API。

public void ConfigureServices(IServiceCollection services)
{
    // replace this line
    //services.AddAuthentication(AzureADDefaults.AuthenticationScheme)
    //.AddAzureAD(options => Configuration.Bind("AzureAd", options));

    // with this
    string[] scopes = Configuration.GetValue<string>("CalledApi:CalledApiScopes")?.Split(' ');
    services.AddMicrosoftWebAppAuthentication(Configuration, "AzureAd")
                .AddMicrosoftWebAppCallsWebApi(Configuration,
                                               scopes,
                                               "AzureAd")
            .AddInMemoryTokenCaches();
    services.AddDownstreamWebApiService(Configuration);
    services.AddMicrosoftGraph(scopes,
                               Configuration.GetValue<string>("CalledApi:CalledApiUrl"));


    // Added AddMicrosoftIdentityUI()
    services.AddControllersWithViews(options =>
    {
        var policy = new AuthorizationPolicyBuilder()
            .RequireAuthenticatedUser()
            .Build();
        options.Filters.Add(new AuthorizeFilter(policy));
    }).AddMicrosoftIdentityUI();

    services.AddRazorPages();
    // Add consent handler
    services.AddServerSideBlazor().AddMicrosoftIdentityConsentHandler();
        
    services.AddSingleton<WeatherForecastService>();
}

我们可以直接使用Graph

enter image description here