Search code examples
c#asp.net-coreazure-active-directoryasp-net-core-spa-services

ASP.Net Core React.js Template Azure AD Authentication & Authorization


I have set my Startup.cs as per these docs.

The thing is that my SPA is located at https://localhost:5000 and my API is located at https://localhost:5000/api. When I access the SPA URL I get some errors, but if I go to the API URL, then I'm redirected to the https://login.microsoftonline.com/...rest where I can perform the login. After that, I get a cookie set, then my SPA application works.

My question is the following, how can I access the SignIn/SignOut functionalities at will. From these docs I see that there is an Account controller which can be accessed. But I tried navigating to it by "guessing" the URL and I didn't manage to do so.

I see that the controller's functionalities can be accessed by defining some Razor pages, e.g.:

<ul class="navbar-nav">
  @if (User.Identity.IsAuthenticated)
  {
    <li class="nav-item">
        <span class="navbar-text text-dark">Hello @User.Identity.Name!</span>
    </li>
    <li class="nav-item">
        <a class="nav-link text-dark" asp-area="MicrosoftIdentity" asp-controller="Account" asp-action="SignOut">Sign out</a>
    </li>
  }
  else
  {
    <li class="nav-item">
        <a class="nav-link text-dark" asp-area="MicrosoftIdentity" asp-controller="Account" asp-action="SignIn">Sign in</a>
    </li>
  }
</ul>

How can I do this from React? I'm not sure that I follow the appropriate docs.


Solution

  • For anyone landing here and being a bit confused as I was here is what docs I followed to set this up:

    1. https://learn.microsoft.com/en-us/azure/active-directory/develop/quickstart-v2-aspnet-core-web-api
    2. https://github.com/Azure-Samples/ms-identity-javascript-react-tutorial/tree/main/3-Authorization-II/1-call-api (provided by @juunas).

    Also read the comments for more info.