gpt4 book ai didi

azure-active-directory - 在使用 Azure Active Directory 的 WASM Blazor 中,我如何在开发过程中绕过 Auth

转载 作者:行者123 更新时间:2023-12-05 02:45:13 26 4
gpt4 key购买 nike

Microsoft 在他们的演练中很好地介绍了针对 Azure Active Directory 验证 WASM Blazor。他们没有涵盖的是之后的开发工作流程。作为已编译的应用程序,对 UI 的每次更改都是一个痛苦的停止-重新编译-启动过程,然后由 AAD 登录过程复合。我们如何简化这一过程并在开发过程中设置一组伪造的凭据?

最佳答案

这种方法目前对我有用,但我很想看看其他人是怎么做的。请注意,这主要用于开发,但我可以考虑将其扩展用于集成测试(这是我列表中的下一个)。

在客户端中,为自己制作一个伪造的 AuthenticationStateProvider 以替换您通常使用的 Remote 身份验证。

using System;
using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Components.Authorization;
using Microsoft.AspNetCore.Components.WebAssembly.Authentication;

namespace Blah.Client
{
public class FakeAuthStateProvider : AuthenticationStateProvider, IAccessTokenProvider
{
public override Task<AuthenticationState> GetAuthenticationStateAsync()
{
var identity = new ClaimsIdentity(new[]
{
new Claim(ClaimTypes.Name, ">> TEST USER <<"),
new Claim("directoryGroup","abc4567-890-1234-abcd-1234567890abc") //Should match your group you use to determine a policy
}, "Fake authentication type");


var user = new ClaimsPrincipal(identity);



return Task.FromResult(new AuthenticationState(user));
}

public async ValueTask<AccessTokenResult> RequestAccessToken()
{
return new AccessTokenResult(AccessTokenResultStatus.Success, new AccessToken() { Expires = DateTime.Now + new TimeSpan(365,0,0,0) }, "");
}

public async ValueTask<AccessTokenResult> RequestAccessToken(AccessTokenRequestOptions options)
{
return new AccessTokenResult(AccessTokenResultStatus.Success, new AccessToken() { Expires = DateTime.Now + new TimeSpan(365, 0, 0, 0) }, "");
}
}
}

在client program.cs中,debug时关闭auth:

#if DEBUG
SetupFakeAuth(builder.Services);
#else
builder.Services.AddMsalAuthentication<RemoteAuthenticationState, CustomUserAccount>(options =>
{
builder.Configuration.Bind("AzureAd", options.ProviderOptions.Authentication);
options.ProviderOptions.DefaultAccessTokenScopes.Add("api://1234567-890-1234-abcd-1234567890abc/API.Access");
})
.AddAccountClaimsPrincipalFactory<RemoteAuthenticationState, CustomUserAccount, CustomAccountFactory>();
#endif
.....
private static void SetupFakeAuth(IServiceCollection services)
{
//https://github.com/dotnet/aspnetcore/blob/c925f99cddac0df90ed0bc4a07ecda6b054a0b02/src/Components/WebAssembly/WebAssembly.Authentication/src/WebAssemblyAuthenticationServiceCollectionExtensions.cs#L28

services.AddOptions();
services.AddAuthorizationCore();
services.TryAddScoped<AuthenticationStateProvider, FakeAuthStateProvider>();


services.TryAddTransient<BaseAddressAuthorizationMessageHandler>();
services.TryAddTransient<AuthorizationMessageHandler>();

services.TryAddScoped(sp =>
{
return (IAccessTokenProvider)sp.GetRequiredService<AuthenticationStateProvider>();
});

services.TryAddScoped<IAccessTokenProviderAccessor, FakeAccessTokenProviderAccessor>();
services.TryAddScoped<SignOutSessionStateManager>();
}

...并定义 FakeAuthState 提供程序,它只是 Microsoft 注册的内部类的一个副本:

// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.

using System;
using Microsoft.Extensions.DependencyInjection;

namespace Microsoft.AspNetCore.Components.WebAssembly.Authentication.Internal
{
internal class FakeAccessTokenProviderAccessor : IAccessTokenProviderAccessor
{
private readonly IServiceProvider _provider;
private IAccessTokenProvider _tokenProvider;

public FakeAccessTokenProviderAccessor(IServiceProvider provider) => _provider = provider;

public IAccessTokenProvider TokenProvider => _tokenProvider ??= _provider.GetRequiredService<IAccessTokenProvider>();
}
}

这应该会导致客户端上的登录用户像往常一样具有名称和范围。

服务器端:

在 Startup.cs 中

    #if DEBUG            
services.AddSingleton<IPolicyEvaluator, FakePolicyEvaluator>();
#else
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddMicrosoftIdentityWebApi(Configuration.GetSection("AzureAd"));

#endif

和一个新类:

using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Authorization.Policy;
using Microsoft.AspNetCore.Http;

namespace Blah.Server
{
public class FakePolicyEvaluator : IPolicyEvaluator
{
public virtual async Task<AuthenticateResult> AuthenticateAsync(AuthorizationPolicy policy, HttpContext context)
{
const string testScheme = "FakeScheme";
var principal = new ClaimsPrincipal();
principal.AddIdentity(new ClaimsIdentity(new[] {
new Claim("Permission", "CanViewPage"),
new Claim("Manager", "yes"),
new Claim(ClaimTypes.Role, "Administrator"),
new Claim(ClaimTypes.NameIdentifier, "John")
}, testScheme));
return await Task.FromResult(AuthenticateResult.Success(new AuthenticationTicket(principal,
new AuthenticationProperties(), testScheme)));
}

public virtual async Task<PolicyAuthorizationResult> AuthorizeAsync(AuthorizationPolicy policy,
AuthenticateResult authenticationResult, HttpContext context, object resource)
{
return await Task.FromResult(PolicyAuthorizationResult.Success());
}
}
}

希望对某人有所帮助。我现在将着手改进它并使其在测试场景中发挥作用。

关于azure-active-directory - 在使用 Azure Active Directory 的 WASM Blazor 中,我如何在开发过程中绕过 Auth,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66063572/

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