Add Authentication to Your ASP.NET Core MVC Application

Learn how to add authentication to your ASP.NET Core MVC Application by using Auth0.
Read more…

:writing_hand:t2: Brought to you by @andrea.chiarelli

1 Like

What are your thoughts guys? Share it in the comments! :technologist::speaking_head:

I just have one question, where is the callback URL used in the app? So the callback URL seems to be → https://localhost:7095/callback, where is it used?

Hi @venky76v :wave:,
Welcome to the Auth0 Community!

The callback URL is automatically handled by the Auth0 ASP.NET Core Authentication SDK. Well, actually it is handled by the underlying OpenID Connect middleware, which takes care of validating and decoding the tokens received from Auth0 and all the protocol-related stuff.
Usually, you don’t need to change this standard behavior, but the SDK lets you customize it if you really need it.

1 Like

Thanks Andrea for the response, really like and appreciate your tutorials. In fact I look forward to reading them. Thanks for the explanation about the callback URL. What you say makes sense, but what I don’t understand, maybe you can explain, is the call back url, is it passed back to the MVC / Razor app in the as a part of the authentication process? Does the set up need a callback URL to work with and what will happen if I don’t configure a call back URL while setting up the app on Auth0 dashboard?

Thanks for your kind words, @venky76v :slightly_smiling_face:

I really appreciate that you want to learn more about what happens under the hood. I think that developers should have at least a high-level idea of what an SDK, framework, protocol, etc. do. So, your question is welcome! :raised_hands:

The need for the callback URL has to do with the OpenID Connect/OAuth2 flows. In this specific case, we are using the Implicit Flow.
The following image outlines the interaction between the user, the application, and Auth0:

Step 5 is where Auth0 uses the callback URL. In this step, Auth0 redirects your user’s browser to that callback URL and provides the ID token, i.e., the token that proves that the authentication was successful and contains the user’s data.

The need for registering the callback URL on the Auth0 side is a required security measure to prevent an attacker can get your ID token by redirecting to another URL. Auth0 will redirect users only to registered URLs.
If you don’t register a callback URL, your users’ authentication attempt will fail.

I hope this helps you understand better the underlying flow.

2 Likes

By chance does anyone have an idea on how I can get it to show the user email on the profile page in my app? I am only getting null despite following the instructions on this tutorial (asp.net core 6 mvc).

Hello @metalkonsc,
Welcome to the Auth0 Community.

As far as I can see, the problem is in this assignment:

EmailAddress = User.Claims.FirstOrDefault(c => c.Type == "email")?.Value,

The default type name for the email claim is not "email". It’s "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress", as documented here.

For this reason I compare the type name with the ClaimTypes.Email field in my article.
The correct assignment should be as follows:

EmailAddress = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Email)?.Value,
1 Like

This is a great documentation and I have accomplished a lot with it. I have multiple clients under the same tenant. Three of the clients used this example to add Auth0 authentication. Single sign on is working great but however, it has been tough to implement Single Logout. Auth0 sessions are cleared out if I look at the logs in Auth0, but the application session still remains. How could I sync Auth0 session with the app session in the above example? Your help would be highly appreciated.
Thanks

1 Like

Hey @spoudel,
Happy to learn that this article was helpful to you!

Regarding the logout problem, if I correctly understand, you are trying to implement Single Logout (SLO), i.e., you want that when a user logs out of an app, they log out of all the apps.

If that is the case, I’m afraid that currently you can’t do it out-of-the-box.
Unfortunately, SLO is currently available for SAML but not for OIDC. As suggested in this document, you will need to implement the logout service yourself. This document outlines two possible solutions.

I hope this helps.

2 Likes

Great article!

I was able to get auth0 going most of the way, including by customising our claims by settings up an event handler in the option.OpenIdConnectEvents:

builder.Services.AddAuth0WebAppAuthentication(options =>
{
    // ...
    options.OpenIdConnectEvents =
        new OpenIdConnectEvents
        {
            OnTokenValidated = context =>
            { 
                // ...
                var claimsIdentity = tc.Principal.Identities.First();
                claimsIdentity.AddClaim(new Claim("PreferredCurrency", "EUR"));

                return Task.CompletedTask;
            }
        };
}

Where I got stuck with is sharing the auth0 identity cookie across subdomains.

I need to be able to sign in on mydomain.com and then navigate to sub.mydomain.com without having to authenticate again.

I tried settings either the Cookie.Domain value or the CookieManager in ConfigureApplicationCookie.

builder.Services
       .ConfigureApplicationCookie(options =>
                                   {
                                       options.Cookie.Domain = ".mydomain.com";
                                       options.CookieManager = new MySubdomainEnabledCookieManager();
                                   });

With the configuration above, Auth0 (or possibly Identity Core?) doesn’t use the settings.

This stackoverflow answer helped me:

Instead of calling builder.Services.ConfigureApplicationCookie(/*...*/);, call this to configure the cookie settings for the same scheme auth0 uses CookieAuthenticationDefaults.AuthenticationScheme:

builder.Services
      .Configure<CookieAuthenticationOptions>(CookieAuthenticationDefaults.AuthenticationScheme,
          options =>
          {
              options.Cookie.Domain = ".watchdoghq.com";
              options.CookieManager = new BrandedSubdomainEnabledCookieManager()
          });

Hi @bounav,
To clarify, you are not working with Auth0 cookies here. You are working with cookies created by your ASP.NET Core application. You are not even using ASP.NET Core Identity, so ConfigureApplicationCookie() has no effect.

I’m not sure if the solution from StackOverflow worked for you :thinking:

Anyway, I think you should configure the cookie middleware with something similar to the following (disclaimer: I didn’t try):

builder.Services.AddAuth0WebAppAuthentication(options =>
  {
    ...
  })
    .AddCookie(  CookieAuthenticationDefaults.AuthenticationScheme,
 options =>
    {
        options.Cookie.Domain = ".mydomain.com";
    });

I hope it helps.

By the way, regarding the addition of a new claim to the ID token, do you know you can use Auth0 Actions?

Yes. And the trick here is when you pass the string CookieAuthenticationDefaults.AuthenticationScheme as the name for the cookies options instance. Which happens to be same one auth0 uses internally.

.AddCookie() is not available to call after .AddAuth0WebAppAuthentication(/*...*/) for me?

The code in my previous reply worked.

Re: auth0 actions

I’m aware of the feature but in our use-case it would force us to expose an API so that we can load stuff from our database from where the auth0 action runs which would be a lot of work and silly to do compared to just settings our custom claims within the app itself.

1 Like