【问题标题】:Add scopes to AuthenticationTicket?向 AuthenticationTicket 添加范围?
【发布时间】:2021-09-08 19:30:43
【问题描述】:

有没有办法向 AuthenticationTicket 添加范围,我正在进行集成测试,而我正在测试的控制器端点需要存在范围。

    [Authorize]
    [RequiredScope(RequiredScopesConfigurationKey = "AzureAd:Scopes")]

目前我有一个如下所示的测试 AuthenticationHandler。

 public class TestAuthHandler : AuthenticationHandler<AuthenticationSchemeOptions>
    {
        public TestAuthHandler(IOptionsMonitor<AuthenticationSchemeOptions> options,
            ILoggerFactory logger, UrlEncoder encoder, ISystemClock clock)
            : base(options, logger, encoder, clock)
        {
        }

        protected override Task<AuthenticateResult> HandleAuthenticateAsync()
        {
            var claims = new[] { new Claim(ClaimTypes.Name, "Test user") };
            var identity = new ClaimsIdentity(claims, "Test");
            var principal = new ClaimsPrincipal(identity);
            var ticket = new AuthenticationTicket(principal, "Test");
            var result = AuthenticateResult.Success(ticket);

            return Task.FromResult(result);
        }
    }

【问题讨论】:

    标签: c# asp.net-web-api oauth-2.0 integration-testing


    【解决方案1】:

    在向现有解决方案添加授权时,我遇到了同样的问题。

    范围值最终来源于声明。所以诀窍是找到范围声明的 claimType,而不是将范围直接添加到票证中。下面的代码示例对我有用。

    new Claim("http://schemas.microsoft.com/identity/claims/scope", "mySuperSecretStuff")
    

    对于被保护的控制器

    [RequiredScope("mySuperSecretStuff")]
    

    希望这可以节省一些时间

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多