What is Blazor? A Tutorial on Building Web Apps with Authentication

Excellent article andrea.chiarelli.

Very helpful for me. Im trying my best, but struggling to get the User credentials from an API endpoint.
Ive seen a lot of people use AuthenticationStateProvider but im having issues with it working on Blazor Server as scoped:

If i use

services.AddSingleton<AuthenticationStateProvider, ServerAuthenticationStateProvider>();

I can get the User and all of their Claims etc from a controller this way

private readonly AuthenticationStateProvider auth;

    {
        this.auth = auth;
    }
var authState = await auth.GetAuthenticationStateAsync();
            var user = authState.User;```

However its using AddSIngleton, which puts ALL users in a loop as i would need this as AddScoped which comes back with an error of : 
'GetAuthenticationStateAsync was called before SetAuthenticationState.'

Whats the best (and suggested easiest) way i can get the Users info in a controller ?? 

THanks for all of your work on this :)

Hey @acusu , thank you for appreciating my article :slight_smile: and welcome to the Auth0 Community! :wave:

Regarding your request, Iā€™m not sure what is your scenario actually?

struggling to get the User credentials from an API endpoint.

Are you trying to get the userā€™s credentials? From what API endpoint? And why? :thinking:
This is not clear to me.

Maybe you want to implement an API endpoint returning the userā€™s profile data. Is it so?
In that case, please, can you share your full implementation (better if a GitHub repo) to have more context? Thanks :pray:

2 Likes

Sorry for being Vague :slight_smile:

Basically what I need is a way of recording user activity in my Database on all CRUD activities, So i would like the users Auth0 id so i can search the DB for the user and store accordingly (I use the Machine2Machine Auth0 to sync up userā€™s)

If i use the singleton of :
services.AddSingleton<AuthenticationStateProvider, ServerAuthenticationStateProvider>();

it works as expected, but not AddScoped.

Sorry @acusu, I understand the issue you have due to using AddSingleton instead of AddScoped, but itā€™s not clear the overall applicationā€™s architecture to me.
Is your application a Blazor Server application? Why are you using Machine2Machine flow? Iā€™m missing the overall picture, so Iā€™m not sure I can help you. Sorry!

Anyway, taking a closer look at the code snippet you provided, it looks like you are using a non-initialized AuthenticationStateProvider instance:

private readonly AuthenticationStateProvider auth;

// maybe here is other code...
{
       this.auth = auth;
 }
var authState = await auth.GetAuthenticationStateAsync();
var user = authState.User;

Since I havenā€™t the full controllerā€™s code, I canā€™t say what you are trying to do here. It looks like you declared your private auth variable and are trying to get the authentication state from it. That variable is not initialized, so it throws that exception.

Since you registered the AuthenticationStateProvider service, you need to inject that instance into your controller. You donā€™t have to declare a new variable.
At least, thatā€™s what I guess from the information available to me.

1 Like

Very sorry,

I wrote this question also in stack overflow, and forgot to include all of the page.

Here is the full Controller of the Blazor Server App, simply the only addon to your current GitHub:

namespace QuizManager.Controllers
{
    [Route("api/[controller]/[Action]")]
    [ApiController]
    public class UserController : ControllerBase
    {


        private readonly AuthenticationStateProvider auth;

        public UserController( AuthenticationStateProvider auth)
        {
           
            this.auth = auth;
        }

        [HttpGet]
        public async Task<IActionResult> GetUserInfo()
        {

          
     var authState = await auth.GetAuthenticationStateAsync();
            var user = authState.User;
           

            return Ok("SUCCESS");
        }



    }
}

Ignoring the Machine to Machine element, I just need the Users Login email or Auth0 ID and im happy :stuck_out_tongue:

Hey @acusu,
Unfortunately I donā€™t have an out-of-the-box solution for your problem.
I looked around and found many devs having the same problem.
The most authoritative discussion for this problem seems to be this one, but I donā€™t feel it provides a clear solution.
I read elsewhere that the Blazor authentication infrastructure cannot be used in API controllers and they suggest using HttpContext.User instead of GetAuthenticationStateAsync. You could try this way.

1 Like

Yeah, I followed that discussion too. :frowning:

No worries i will keep cracking on and see how I get on with the HttpContext.User option instead.

Thanks again for all of your help. :smiley:

1 Like

No worries weā€™re here for you!

1 Like

Hey folks, this blog post has been updated to .NET 6.0! :fire:
Also, the sample project uses the new Auth0 ASP.NET Core Authentication SDK now :tada: .
A lot of simplification! :rocket:

2 Likes

Wooohooo thanks Andrea for sharing that!

2 Likes

I see in the forum here you planned to show us how to connect our Blazor Server to an API server. Can we please get a link to that? I keep finding tutorials on connecting ASP.NET Core Web API only and Blazor Server only, but not the combination of the two.

Thanks

Hi @LuckyWolf19,
Thank you for joining the Auth0 Community.

These days Iā€™m actually working on a tutorial showing how to call a protected API from an ASP.NET Core application. The sample application will be an ASP.NET Core MVC application, but the approach is the same for any ASP.NET Core application, including Blazor Server and Razor Pages apps.

I hope to publish it in the next few weeks. Thank you for your patience :pray:

1 Like

Hey @LuckyWolf19,
As promised, here is the article on how to call a protected API from an ASP.NET Core application.
Let me know if anything is not clear.
Have a good reading!

1 Like

Good day!

I am struggling just a bit. I was able to get everything working just fine in my VS2022 debugger, but when I deployed the app to my development server, I started receiving a ā€œCallback URL mismatchā€ error when attempting to log in. Upon closer inspection, I found that the absolute url being generated is an ā€œhttpā€ scheme rather than the ā€œhttpsā€ used to connect to the site (and is properly configured in my Auth0 Application settings). Iā€™m concerned that this is because I have deployed the site behind an Apache reverse proxy server, so while the connection to Apache is https, the internal connection is http. And so the HttpContext is seeing an http connection rather than https, and so generating an absolute URL of the incorrect type because of it. Is there a way to override the automatically generated absolute URL and use one that I generate in my code? Iā€™m also open to other explanations, of course.

Edit:
I have just found the answer I sought on this thread: Cannot authenticate Regular App using .NET Core SDK deployed in k8s behind reverse proxy with SSL termination - #4 by konrad.sopala

Evidently, by setting ā€œHttpContext.Request.IsHttps = true;ā€ before calling the ChallengeAsync method, I can force it to generate an https redirect_uri and all is well.

Hey @lassanter,
Welcome to the Auth0 Community !:wave:

Iā€™m happy you found a solution to your problem.
More in general, for issues related to reverse proxies, you may find helpful this document from Microsoft.
Maybe in your case, you could configure X-Forwarded-Proto header as described here and keep your code more environment-agnostic.

Of course, it adds a little more complexity to your code :slightly_smiling_face:

1 Like

Thanks! Iā€™ll check that out, now. I do not fear complexity :wink:

1 Like

Good day,

I have found success to date. However, is there a mechanism by which I can add Claims in my code after the user has successfully logged in? I have seen such a mechanism when one is using the Open Id libraries, but there donā€™t appear to be any extension methods with that idea in mind from the Auth0 libraries. Or, at least, I havenā€™t been able to find it, and my Google Fu has thus far failed me.

Hi @lassanter,
If you want to add custom claims to the ID and/or access token right after the user has successfully authenticated but before your application receives it, you can use Actions.
Check this document to learn how to do it.
This blog post provides you with a practical example.

1 Like

Hello, please help me!
Can you provide an example of how to configure the use of roles in blazor server application?

Hey @den783245,
Welcome to the Auth0 Community!

To enable role-based authorization in your Blazor application, follow the instructions in this document. I suggest using Actions to add the roles to the token instead of rules.

After this, you can use the authorization components as explained here.

I hope this helps.

1 Like