Web App Login - ob1dev/Auth0 GitHub Wiki

Now let's add functionality that will sign a user in and out.

Visual Studio

Add controller

Create a new class AccountController under the folder Controllers, with two actions Signin and Signout.

[Route("[controller]/[action]")]
public class AccountController : Controller
{
  [HttpGet]
  public async Task Signin(string returnUrl = "/")
  {
    await HttpContext.ChallengeAsync("Auth0", new AuthenticationProperties()
    {
      RedirectUri = returnUrl
    });
  }

  [HttpGet]
  public async Task Signout()
  {
    await HttpContext.SignOutAsync("Auth0", new AuthenticationProperties
    {
      RedirectUri = Url.Action("Index", "Home")
    });

    await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
  }
}

NOTE

In the method Startup.ConfigureServices, I set the option LoginPath to value /Account/Signin. That's because the default path is /Account/Login, but I need it to be /Account/Signin.

Add partial view

Create a new partial view _LoginPartial under the folder Views\Shared, to render Sign in and Sign out links/buttons.

@using Microsoft.AspNetCore.Authentication
@using Microsoft.Extensions.Options

@if (User.Identity.IsAuthenticated)
{
  <ul class="nav navbar-nav navbar-right">
    <li><a asp-controller="Account" asp-action="Signout">Sign out</a></li>
  </ul>
}
else
{
  <ul class="nav navbar-nav navbar-right">
    <li><a asp-controller="Account" asp-action="Signin">Sign in</a></li>
  </ul>
}

Insert partial view

Modify the view _Layout under the folder Views\Shared, to insert the partial view _LoginPartial.

    <div class="navbar-collapse collapse">
      <ul class="nav navbar-nav">
      ...
      </ul>
      @await Html.PartialAsync("_LoginPartial")
    </div>
  </div>
</nav>
<div class="container body-content">
  @RenderBody()
  <hr />
  <footer>
    <p>&copy; 2018 - OneGit</p>
  </footer>

Summary

Now the Web App can sing in and sign out a user delegating the heavy work to Auth0. In the following tutorial, you'll learn how to protect pages for non-authorized and authorized user based on a user's role.

What's next?

Web App - Profile

⚠️ **GitHub.com Fallback** ⚠️