0

I'm trying to get an integration test going for an API with authentication. Because some API functions call other API's on behalf of the user and this allows us to test everything before publishing.

The problem is I keep getting a 302 redirect even though I pass the token in the header. I'm not familiar with OpenID so perhaps I'm filling in the wrong header(s)? I've pretty much copy pasted the Startup from the sample found here. Can someone please point me in the right direction?

FYI everything works without the AuthorizeAttribute on my controller.

public class Startup
{
    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        app.UseAuthentication();
    }

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddAuthentication(sharedOptions =>
            {
                sharedOptions.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
                sharedOptions.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
            })
            .AddOpenIdConnect(options =>
            {
                options.Authority = "hidden";
                options.ClientId = "hidden";
                options.CallbackPath = "/signin-oidc";
                options.RequireHttpsMetadata = false;
                options.UseTokenLifetime = true;
            })
            .AddCookie();
    }
}

[TestClass]
public class Tests
{
    [TestMethod]
    public void Test()
    {
        // Get access token for API.
        var httpClient = new HttpClient();
        var formContent = new FormUrlEncodedContent(new[]
            {
                new KeyValuePair<string, string>("resource", "hidden"),
                new KeyValuePair<string, string>("client_secret", "hidden"),
                new KeyValuePair<string, string>("username", "hidden"),
                new KeyValuePair<string, string>("password", "hidden"),
                new KeyValuePair<string, string>("client_id", "hidden"),
                new KeyValuePair<string, string>("grant_type", "password")
            })
        var result = httpClient.PostAsync(new Uri("https://login.microsoftonline.com/hidden.onmicrosoft.com/oauth2/token", formContent).Result;
        var content = result.Content.ReadAsStringAsync().Result;
        var accessToken = JObject.Parse(content)["access_token"].ToString();

        // Create client calling the API.
        var builder = new WebHostBuilder()
            .UseStartup<Startup>();
        var testServer = new TestServer(builder);

        var client = testServer.CreateClient();
        client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
        var response = client.GetAsync("/hidden").Result; // Receiving a 302 redirect
        var content = response.Content.ReadAsStringAsync().Result;

        Console.WriteLine(content);

        Assert.IsTrue(response.IsSuccessStatusCode);
    }
}
Vqf5mG96cSTT
  • 2,561
  • 3
  • 22
  • 41
  • Where does that redirect go (what is in the Location header?). Also, if that code n your Test method is meant to be async/await then you need to make it so. If that `Result` property is what I think it is you might be in for [surprises](https://stackoverflow.com/questions/15021304/an-async-await-example-that-causes-a-deadlock) – rene Aug 23 '18 at 18:11
  • @rene I've had some problems with async await in test methods before but maybe they are fixed with dotnetcore. Thanks for the tip. In my Location header there is: https://login.microsoftonline.com/db000123-d321-123a-bd1b-123f93f41d57/oauth2/authorize?client_id=123eb1e-123a-1239-123e-123178b9b811&redirect_uri=http%3A%2F%2Flocalhost%2Fsignin-oidc&response_type=id_token&scope=openid%20profile&response_mode=form_post&nonce=hidden&state=hidden&x-client-SKU=ID_NETSTANDARD1_4&x-client-ver=5.2.0.0. – Vqf5mG96cSTT Aug 23 '18 at 18:31
  • @bdebaere Have you found the solution – S2K Oct 30 '18 at 09:23
  • Have you found the solution – Eric Jan 15 '19 at 09:21

0 Answers0