Adam Wilson
Adam Wilson

Reputation: 299

Add scopes to AuthenticationTicket?

Is there a way to add scopes to an AuthenticationTicket, i am working integration tests and the controller endpoint I am testing requires a scope to be present.

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

Currently I have a Test AuthenticationHandler as shown below.

 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);
        }
    }

Upvotes: 5

Views: 1002

Answers (1)

sdecoodt
sdecoodt

Reputation: 41

I ran into the same question when adding authorization to an existing solution.

The scope value is eventually sourced from a claim. So the trick is finding the claimType of a scope claim, not adding the scope directly to the ticket. The below code sample did the trick for me.

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

for a controller that was guarded with

[RequiredScope("mySuperSecretStuff")]

Hope this saves someone some time

Upvotes: 4

Related Questions