Code Monkey home page Code Monkey logo

Comments (14)

henalbrod avatar henalbrod commented on August 10, 2024 1

I see, I guess the httpContextAccessor is reading the user session status from a different place, maybe we're missing a proxy that feeds the HttpContext with the user session info

from blazor.auth0.

henalbrod avatar henalbrod commented on August 10, 2024

Hi,

Glad to know the library have been useful for you.

In order to answer your question, I would like to know which Blazor hosting model are you using, is it Client Side, Server Side or AspNetCore Hosted?

Also, would you mind sharing the code you're using in the ConfigureServices method of your Startup.cs?

from blazor.auth0.

ITninja04 avatar ITninja04 commented on August 10, 2024

Thanks for the response, we're using Server Side. Here is our ConfigureServices method:

`public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<Data.DataContext>(options => options.UseSqlServer(Configuration.GetConnectionString("MainDB")).EnableSensitiveDataLogging(), ServiceLifetime.Transient);
services.AddHangfire(configuration => configuration.UseSqlServerStorage(Configuration.GetConnectionString("MainDB_HF")));

        services.AddHangfireServer();
        services.AddOptions();

        services.AddRazorPages();
        services.AddServerSideBlazor();
        services.AddBlazoredModal();
        services.AddScoped<HttpClient>();

        services.AddScoped((sp) =>
        {
            return new Blazor.Auth0.Shared.Models.ClientSettings()
            {
                Auth0Domain = Configuration["Auth0:Domain"],
                Auth0ClientId = Configuration["Auth0:Client_ID"],
                //LoginRequired = true,
                GetUserInfoFromIdToken = true,
                RedirectAlwaysToHome = true,
                Auth0Audience = "https://api.##########.com"
            };
        });


        services.AddScoped<Blazor.Auth0.ServerSide.Authentication.AuthenticationService>();

        services.Configure<AzureSearchSettings>(Configuration.GetSection("AzureSearch"));
        services.AddSingleton<IConfiguration>(Configuration);

        services.AddScoped<AzureSearchSettings>();


        services.AddScoped<Microsoft.AspNetCore.Components.AuthenticationStateProvider, Blazor.Auth0.ServerSide.Authentication.AuthenticationStateProvider>();
        services.AddFileReaderService();

        services.AddTransient<Services.IBlobStorageService, Services.BlobStorageService>();

        services.AddScoped<Services.IComponentUpdater, Services.ComponentUpdater>();

        services.AddTransient<IEmailSender, EmailSender>();
        services.AddTransient<Data.IDataContextFactory, Data.DataContextFactory>();

        services.AddSweetAlert2();

        services.AddAuthorization(options =>
        {
            options.AddPolicy("ExternalUser", policy => policy.RequireClaim("permission:read:external"));
            options.AddPolicy("AdminUser", policy => policy.RequireClaim("permission:read:admin"));
            options.AddPolicy("SuperAdmin", policy => policy.RequireClaim("permission:read:superadmin"));
            options.AddPolicy("ReadOnly", policy => policy.RequireClaim("permission:read:readonly"));
        });
    }`

from blazor.auth0.

henalbrod avatar henalbrod commented on August 10, 2024

Hi,

It looks like your missing a reference to HttpContextAccessor.

In your ConfigureServices method please add:

services.AddHttpContextAccessor();

And in the desired component (if any) please add:

@using Microsoft.AspNetCore.Http
@inject IHttpContextAccessor httpContextAccessor

Please let me know if this works for you.

Source: StackOverflow Question

from blazor.auth0.

ITninja04 avatar ITninja04 commented on August 10, 2024

AspNetCore_Hangfire_Blazor

I gave that a shot, but the user is still not coming through for some reason :|

from blazor.auth0.

henalbrod avatar henalbrod commented on August 10, 2024

How does your App.razor looks like?

from blazor.auth0.

ITninja04 avatar ITninja04 commented on August 10, 2024

<CascadingAuthenticationState> <Router AppAssembly="typeof(Startup).Assembly"> <NotFoundContent> <p>Sorry, there's nothing at this address.</p> </NotFoundContent> </Router> </CascadingAuthenticationState>

from blazor.auth0.

ITninja04 avatar ITninja04 commented on August 10, 2024

If you have a moment I could do a zoom meeting and show it to you.

from blazor.auth0.

ITninja04 avatar ITninja04 commented on August 10, 2024

Actually, I sent the wrong app.razor. Here's what I have in the actual one:

`
@using Blazor.Auth0.Shared.Models.Enumerations
@using Blazor.Auth0.ServerSide.Components
@using Blazor.Auth0.ServerSide.Authentication
@Inject AuthenticationService _authService
@Inject Microsoft.AspNetCore.Components.IUriHelper UriHelper
@Inject Data.DataContext dbContext
@Inject IJSRuntime JsRuntime

<AuthorizedContent>
    <CascadingAuthenticationState>
        <CascadingValue Value="@UserData" Name="User">
            <Router AppAssembly="typeof(Startup).Assembly">
                <NotFoundContent>
                    <div id="notfound">
                        <div class="notfound">
                            <div class="notfound-404">
                                <h1>404</h1>
                                <h2>Page not found</h2>
                            </div>
                            <a href="/">Homepage</a>
                        </div>
                    </div>
                </NotFoundContent>
            </Router>
            <Fish_Partner_Portal.Shared.Components.ModalContainer />
        </CascadingValue>

    </CascadingAuthenticationState>

</AuthorizedContent>

<NotAuthorizedContent>
    <div id="notfound">
        <div class="notfound">
            <div class="notfound-404">
                <h1>401</h1>
                <h2>Unauthorized</h2>
            </div>
            <a href="@_authService.BuildAuthorizeUrl()">Login</a>
        </div>
    </div>
</NotAuthorizedContent>
`

from blazor.auth0.

henalbrod avatar henalbrod commented on August 10, 2024

Sorry, not able for calling just now :(

Would you please test the following?

[CascadingParameter] Task<AuthenticationState> authenticationStateTask { get; set; }

public async Task<bool> Authorize(){

        var authState = await authenticationStateTask;

        var user = authState.User;

        return user.Identity.IsAuthenticated;

}

Also, I think that the CascadingAuthenticationState component should the outer-most element

from blazor.auth0.

henalbrod avatar henalbrod commented on August 10, 2024

Ok, I think I found a dirty work-around:

Create new CustomHttpContextAccessor class

    public class CustomHttpContextAccessor: IHttpContextAccessor
    {

        private readonly Microsoft.AspNetCore.Components.AuthenticationStateProvider authenticationStateProvider;
        private readonly IHttpContextAccessor httpContextAccessor;

        public CustomHttpContextAccessor(Microsoft.AspNetCore.Components.AuthenticationStateProvider authenticationStateProvider, IHttpContextAccessor httpContextAccessor)
        {
            this.authenticationStateProvider = authenticationStateProvider ?? throw new ArgumentNullException(nameof(authenticationStateProvider));
            this.httpContextAccessor = httpContextAccessor ?? throw new ArgumentNullException(nameof(httpContextAccessor));
        }

        public HttpContext HttpContext { get {

                var authState = Task.Run(async ()=> await authenticationStateProvider.GetAuthenticationStateAsync()).Result;

                httpContextAccessor.HttpContext.User = authState.User;

                return httpContextAccessor.HttpContext;

            } set {

                httpContextAccessor.HttpContext = value;

            }
        }

    }

In Startup.cs

public void ConfigureServices(IServiceCollection services)
{

    // ------------- other services  ------------------->>>
    services.AddHttpContextAccessor();            
    services.AddScoped<CustomHttpContextAccessor>();
    // ------------- other services  ------------------->>>

}

In your .razor

@inject CustomHttpContextAccessor httpContextAccessor

// ------------- other code ----------------->>>

@code {

    public bool IsAuthorized()
    {

        var httpContext = httpContextAccessor.HttpContext;   
        
        return httpContext.User.Identity.IsAuthenticated;

    }
}

from blazor.auth0.

ITninja04 avatar ITninja04 commented on August 10, 2024

@Pegazux tried that and we're still not getting the logged in user back.

from blazor.auth0.

henalbrod avatar henalbrod commented on August 10, 2024

@ITninja04 this issue will be resolved with the next version for server side

from blazor.auth0.

henalbrod avatar henalbrod commented on August 10, 2024

The new release is now alive.

from blazor.auth0.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.