gpt4 book ai didi

azure - 使用 Microsoft Identity 通过 Core 3.1 Web API 进行客户端 SPA 身份验证

转载 作者:行者123 更新时间:2023-12-03 02:39:48 25 4
gpt4 key购买 nike

我认为我的主要问题是我应该使用哪种身份验证流程 - 代表流程还是隐式授权流程?但是,我在 Startup.cs 中设置的身份验证和授权可能是错误的,而且我还很遥远,所以如果是这样,我深表歉意。

我在 Azure 中有一个现有的 Angular SPA,并且一个也在 Azure 中运行的 Net Framework API。

Web API 已移植到 Net Core 3.1。

在我们的 Azure 目录中,我有两个注册的应用程序。一个用于 API,另一个用于 SPA。我已在 WEB API 中的授权客户端下添加了 SPA 客户端 ID。

值得注意的是,应用程序服务实际上运行在不同的目录中(我认为这很好,但只是提一下)

以下是 Azure AD 中的相关身份验证/授权设置。

    private void ConfigureAzureAD(IServiceCollection services, IMvcBuilder mvcBuilder)
{
services.AddAuthentication(AzureADDefaults.AuthenticationScheme)
.AddAzureAD(options => Configuration.Bind("AzureAd", options));

services.Configure<OpenIdConnectOptions>(AzureADDefaults.OpenIdScheme, options =>
{
options.Authority = options.Authority + "/v2.0/";
options.TokenValidationParameters.ValidateIssuer = true;
});

mvcBuilder.AddMvcOptions(options =>
{
var policy = new AuthorizationPolicyBuilder().
RequireAuthenticatedUser().
Build();
options.Filters.Add(new AuthorizeFilter(policy));
}).
SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseResponseCaching();
}

app.UseStaticFiles();
app.UseCors(CORS_POLICY);


if (UseAzureAD)
{
app.UseHttpsRedirection();
}

app.UseRouting();
app.UseCookiePolicy();
app.UseAuthorization();
app.UseAuthentication();

app.UseMvc();
}

我可以直接成功使用该 API 并且它进行了身份验证。

SPA 正在使用 Angular ADAL。如果我没读错的话,它将不适用于 Microsoft Identity V2 端点。 - 我们仍然需要升级到 MSAL,尽管我仍然无法理解最终的身份验证流程(我认为这是我的主要问题)。

目前,如果我点击 SPA,它将仅使用当前的 ADAL 配置进行身份验证,但当它点击 API 时,会被重定向到 https://login.microsoftonline.com/{TenantId}/oauth2/v2.0/authorize? 和 ID token 。

它卡在重定向上,并且是 CORS 错误,因为源为空。我知道这是预期的,因为 SPA 未正确配置。

API 确实调用 MS Graph API 来获取用户的组(但使用客户端 ID 和客户端 key 来获取访问 token 来调用 MS Graph),所以我不认为这意味着我需要使用代表流程(我确实看到了这篇文章 Authenticating against Microsoft Graph with SPA and then using token in Web API )?

我看过这个例子https://github.com/Azure-Samples/ms-identity-javascript-angular-spa-aspnetcore-webapi隐式拨款流量。

我确实注意到该示例中的身份验证方案是 JwtBearerDefualts ,这很有意义,因为 ID token 是 JWT,因此这让我质疑我的 API 启动配置。

这里是在 API 中调用 MS Graph 的部分,可能需要它来最好地回答我应该使用两个流程中的哪一个(它再次获取带有客户端 key 的访问 token )。

private async Task<IReadOnlyCollection<string>> LoadReportGroupsCurrentUserCanRead()
{
var objectID = claimsPrincipal
.Claims
.FirstOrDefault(c => c.Type == "http://schemas.microsoft.com/identity/claims/objectidentifier")
?.Value;

var graphServiceClient = await GetGraphServiceClient();

var groups = await graphServiceClient
.Groups
.Request()
.GetAsync();

var memberGroups = await graphServiceClient
.Users[objectID]
.GetMemberGroups(true)
.Request()
.PostAsync();

return memberGroups.Select(mg => groups.SingleOrDefault(g => g.Id == mg))
.Where(g => g?.DisplayName?.EndsWith(" Report Group", StringComparison.InvariantCultureIgnoreCase) == true)
.Select(g => g.Description)
.Where(name => !string.IsNullOrWhiteSpace(name))
.ToArray();
}

private async Task<GraphServiceClient> GetGraphServiceClient()
{

string authority = new Uri(microsoftLogin, tenantID).AbsoluteUri;
var authenticationContext = new AuthenticationContext(authority);
var clientCredential = new ClientCredential(clientID, clientSecret);

var authenticationResult = await authenticationContext.AcquireTokenAsync("https://graph.microsoft.com", clientCredential);

var authProvider = new DelegateAuthenticationProvider(requestMessage =>
{
requestMessage.Headers.Authorization = new AuthenticationHeaderValue("bearer", authenticationResult.AccessToken);
return Task.CompletedTask;
});
return new GraphServiceClient(authProvider);
}

最后,我认为我们的 SPA 使用的 Angular 版本不支持 Angular MSAL。我可以只使用 Vanilla MSAL JS(我们现在没有时间升级 Angular)吗?

最佳答案

您应该使用implicit flowmsal-angular 。它支持从 4 到 9 的 Angular。此外,我不建议在 Angular 中使用普通库,除非别无选择。

ADAL 已弃用,并且不支持融合应用程序模型(工作+个人帐户),因此您需要迁移到 MSAL。

关注Create web APIs with ASP.NET CoreMigrate from ASP.NET Core 2.2 to 3.0删除这样的代码:

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

而是将您的 Controller 设置为 Controller and decorate them with ApiController attribute .

还有这个,因为它是 .NET 3.1:

.SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

您的 MS Graph 身份验证正在通过 client credentials 进行身份验证这是当前应用程序架构的常见方法。前提是您没有添加太多highly privileged permissions那么应该没问题。

关于azure - 使用 Microsoft Identity 通过 Core 3.1 Web API 进行客户端 SPA 身份验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61684410/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com