如何给AuthenticationTicket添加scope以满足集成测试接口的权限校验要求
完全可以实现,RequiredScope 特性的校验逻辑本质就是读取 AuthenticationTicket 关联的身份声明中对应scope字段的值,只要在构造测试身份时添加对应声明即可通过校验。
修改后的测试身份处理器代码
你只需在构造Claim列表时增加scope相关声明即可,参考如下实现:
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 List<Claim> { new Claim(ClaimTypes.Name, "Test user"), // 适配微软官方Azure AD校验逻辑默认用的scope声明类型 new Claim("http://schemas.microsoft.com/identity/claims/scope", "替换为你AzureAd:Scopes配置的实际scope值"), // 兼容部分自定义校验逻辑用短名称scope的场景,无需的话可以删除 new Claim("scope", "替换为你AzureAd:Scopes配置的实际scope值") }; 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); } }
补充说明
如果你配置的AzureAd:Scopes包含多个权限值,直接用空格分隔写到同一个scope声明的value中即可,比如多个scope的写法为 new Claim("scope", "access_as_user user.read")。
内容的提问来源于stack exchange,提问作者Adam Wilson
相关产品推荐
相关产品推荐

