.NET Core Web App with Azure AD shows 404

35 Views Asked by At

I am following this microsoft tutorial to integrate web app with azure ad for sign in/sign out.
https://learn.microsoft.com/en-us/entra/identity-platform/tutorial-web-app-dotnet-call-api?tabs=visual-studio%2Cdotnet6

I created a sample .net core razor page web app and ran the web app using https localhost:7100 and it worked fine.
Then I modified the app as it given in the tutorials. Deleted the dummy code and added the sample code, setup client ID,tenant ID, certification key etc. I have followed all steps as is given in the documentation.

The problem is when i run the web app as https it gives me 404 error.

1

There are 1 best solutions below

0
Tiny Wang On

Let's create a new .net core web app, please don't forget to choose Microsoft Identity platform as the Authentication Type.

enter image description here

Then we need to follow the tutorial to replace the builder.Services.AddAuthentication with codes below.

IEnumerable<string>? initialScopes = builder.Configuration["DownstreamApi:Scopes"]?.Split(' ');
builder.Services.AddMicrosoftIdentityWebAppAuthentication(builder.Configuration, "AzureAd")
    .EnableTokenAcquisitionToCallDownstreamApi(initialScopes)
        .AddDownstreamApi("DownstreamApi", builder.Configuration.GetSection("DownstreamApi"))
        .AddInMemoryTokenCaches();

This will bring build error on AddDownstreamApi, let's install Microsoft.Identity.Web.DownstreamApi" Version="2.15.2" /> nuget package to solve it, by the way, we can upgrade the other packages as well. Open the csproj file(doule click the project name in vs), then the content should look like this now. Modify the file and rebuild the app to resolve the error.

<ItemGroup>
  <PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="7.0.13" NoWarn="NU1605" />
  <PackageReference Include="Microsoft.AspNetCore.Authentication.OpenIdConnect" Version="7.0.13" NoWarn="NU1605" />
  <PackageReference Include="Microsoft.Identity.Web" Version="2.15.2" />
  <PackageReference Include="Microsoft.Identity.Web.UI" Version="2.15.2" />
    <PackageReference Include="Microsoft.Identity.Web.DownstreamApi" Version="2.15.2" />
</ItemGroup>

Modify the Index.cshtml and Index.cshtml.cs to add API calling codes and the html content to display API response.

[AuthorizeForScopes(ScopeKeySection = "DownstreamApi:Scopes")]
public class IndexModel : PageModel
{
    private readonly ILogger<IndexModel> _logger;
    private readonly IDownstreamApi _downstreamWebApi;

    public IndexModel(ILogger<IndexModel> logger,
                    IDownstreamApi downstreamWebApi)
    {
        _logger = logger;
        _downstreamWebApi = downstreamWebApi;
    }

    public async Task OnGet()
    {
        using var response = await _downstreamWebApi.CallApiForUserAsync("DownstreamApi").ConfigureAwait(false);
        if (response.StatusCode == System.Net.HttpStatusCode.OK)
        {
            var apiResult = await response.Content.ReadFromJsonAsync<JsonDocument>().ConfigureAwait(false);
            ViewData["ApiResult"] = JsonSerializer.Serialize(apiResult, new JsonSerializerOptions { WriteIndented = true });
        }
        else
        {
            var error = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
            throw new HttpRequestException($"Invalid status code in the HttpResponseMessage: {response.StatusCode}: {error}");
        }
    }
}

<p><pre><code class="language-js">@ViewData["ApiResult"]</code></pre></p>

Then we need to modify appsettings.json file to complete the configurations. Here we require an Azure AD application which already configured the redirect url and created client secret. In Azure AD -> your registration app -> Authentication blade, we should add https://localhost/signin-oidc to the Web platform. And in Certificates & secrets blade, we should create our client secret, then the appsettings.json should be modified to

"AzureAd": {
  "Instance": "https://login.microsoftonline.com/",
  "Domain": "tenant_id",
  "TenantId": "tenant_id",
  "ClientId": "client_id",
  "ClientSecret": "client_secret",
  "CallbackPath": "/signin-oidc", 
  "SignedOutCallbackPath ": "/signout-callback-oidc"
},
"DownstreamApi": {
  "BaseUrl": "https://graph.microsoft.com/v1.0",
  "Scopes": "User.Read"
},

Then running your app, you would be asked to sign in, and getting below home page after logining in.

enter image description here