wildbisu
wildbisu

Reputation: 172

How to get Azure AD Access Token from Unit test method?

I have a Web API registered in and secured with Azure AD. I am having a ASP.NET Core MVC Web application which consumes this API service. The controllers are automatically authenticated by use of Authorize attribute and I can get accessToken for current logged in user.

I am writing unit test for the UI web application. Can anyone help me with how to get Azure AD access token from unit test methods? Thanks in advance.

Upvotes: 0

Views: 2476

Answers (2)

Xavier John
Xavier John

Reputation: 9437

You can have a test fixture that will add test authentication.

Example:

    public static class AuthenticationBuilderExtensions
    {
        internal static AuthenticationBuilder AddTestAuthentication(this AuthenticationBuilder builder, Action<TestAuthenticationOptions> configureOptions)
        {
            return builder.AddScheme<TestAuthenticationOptions, TestAuthenticationHandler>(TestAuthenticationOptions.DefaultScheme, configureOptions);
        }
    }

Now in your tests you can add the test authentication.

var client = _factory
    .WithTestSchemeAuth(new List<Claim>() {
           new Claim("scp", "access_as_user")
    })
    .CreateClient();

Checkout the full sample I created for this purpose. https://github.com/xavierjohn/WeatherForcastWithAuth

Upvotes: 0

RasmusW
RasmusW

Reputation: 3461

Since your unit tests probably want to run without user interaction, you need to use a different authentication flow.

Some APIs support username/password authentication, where your code has access to a set of credentials that can be used (see http://www.cloudidentity.com/blog/2014/07/08/using-adal-net-to-authenticate-users-via-usernamepassword/).

If you want something a little more secure, you can use certificate based authentication. It is somewhat more complicated to setup and implement (https://github.com/Azure-Samples/active-directory-dotnet-daemon-certificate-credential), but gives access to more APIs (e.g. Exchange Web Services user impersonation requires it).

Upvotes: 1

Related Questions