Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings
Discussion options

Not sure where I am getting lost on this but I can't get auth to perist past the current session. I am following the "Blazor WASM Template using Supabase" as an example. My CustomAuthStateProviderand CustomSupabaseSessionHandler are identical to the example. When I load the page I can see the stored token in the browser local storage but unlike the live demo page if I leave and come back to the page the user is not logged in anymore.

You must be logged in to vote

Replies: 2 comments · 8 replies

Comment options

Looking into it further the issue seems to be that despite all the provider code matching when the GetAuthenticationStateAsync() method from CustomAuthStateProvider class is called it hits await _client.InitializeAsync(); but this isn't causing the created loadSession() function in the CustomSupabaseSessionHandler class from being called.

You must be logged in to vote
5 replies
@wiverson
Comment options

At least in my code I load the session via load session manually as part of the init process.

@infraction
Comment options

Yep I figured out the issue. Not sure still while the template example seems to work when my code wasn't but changing the loadSession to be synchronous and calling it during the init process and its working now.

@salsa2k
Comment options

hey @infraction what changes you did? I'm not able to make it work.

@salsa2k
Comment options

@wiverson not sure if I get it, can you give me some example?

@wiverson
Comment options

Here's my Supabase manager for Unity - https://gist.github.com/wiverson/23e53b328977d6a8cd0e8665b3147614 - it's what I'm using for the apps up on https://dayboard.io/ - FYI I have Android apps waiting for approval by Google right now.

Comment options

Hey @wiverson, I tried like you did by adding to my Index.razor:

AuthService._client.Auth.LoadSession();

also tried calling from my MauiProgram.cs, but my app kind of "froze". I got a white page instead in both files.
But no errors.

I was trying to do what @infraction mentioned but I'm not sure how to transform it in asynchronous because of the GetItemAsync.

        public Session? LoadSession()
        {
            var session = _localStorage.GetItemAsync<Session>(SessionKey).Result;
            return session?.ExpiresAt() <= DateTime.Now ? null : session;
        }

The problem is... if I try to make it async:

        public async Task<Session?> LoadSession()
        {
            var session = await _localStorage.GetItemAsync<Session>(SessionKey);
            return session?.ExpiresAt() <= DateTime.Now ? null : session;
        }

I get:
Error CS0738 'SupabaseSessionHandler' does not implement interface member 'IGotrueSessionPersistence.LoadSession()'. 'SupabaseSessionHandler.LoadSession()' cannot implement 'IGotrueSessionPersistence.LoadSession()' because it does not have the matching return type of 'Session'.

Does anybody have any idea what could I do?

You must be logged in to vote
3 replies
@salsa2k
Comment options

Looks like this way will not work with MAUI Blazor Hybrid.

when LoadSession tries to get from the storage using:

_localStorage.GetItemAsync<Session>(SessionKey)

the local storage is not ready yet.
I did a test adding in the AuthService a method that gets the information from the local storage and it works, it has access.
But for some reason, I don't understand, it doesn't work from the CustomSupabaseSessionHandler.

I'm still trying to figure out

@salsa2k
Comment options

I found a way to do it, feel free to add as example.

  1. I changed from Blazored.LocalStorage to MAUI Preferences.
  2. CustomSupabaseSessionHandler
using Microsoft.Extensions.Logging;
using Shared.Services;
using Supabase.Gotrue;
using Supabase.Gotrue.Interfaces;

namespace Shared.Provider
{
    public class CustomSupabaseSessionHandler : IGotrueSessionPersistence<Session>
    {
        private const string SessionKey = "SUPABASE_SESSION";
        private readonly ILogger<CustomSupabaseSessionHandler> _logger;

        public CustomSupabaseSessionHandler(ILogger<CustomSupabaseSessionHandler> logger)
        {
            _logger = logger;
        }

        public void SaveSession(Session session)
        {
            StoreService.Set(SessionKey, session);
        }

        public void DestroySession()
        {
            StoreService.Delete(SessionKey);
        }

        public Session? LoadSession()
        {
            var session = StoreService.Get<Session>(SessionKey);
            return session?.ExpiresAt() <= DateTime.Now ? null : session;
        }
    }
}
  1. StoreService:
using Newtonsoft.Json;
using Xamarin.Essentials;

namespace Shared.Services
{
    public static class StoreService
    {
        public static void Set(string key, object value)
        {
            string keyvalue = JsonConvert.SerializeObject(value);

            if (keyvalue != null && !string.IsNullOrEmpty(keyvalue))
            {
                Preferences.Set(key, keyvalue);
            }
        }

        public static T Get<T>(string key)
        {
            T UnpackedValue = default;
            string keyvalue = Preferences.Get(key, string.Empty);

            if (keyvalue != null && !string.IsNullOrEmpty(keyvalue))
            {
                UnpackedValue = JsonConvert.DeserializeObject<T>(keyvalue);
            }

            return UnpackedValue;
        }

        public static void Delete(string key)
        {
            Preferences.Remove(key);
        }

        public static bool ContainsKey(string key)
        {
            return Preferences.ContainsKey(key);
        }

        public static void ClearAll()
        {
            Preferences.Clear();
        }
    }
}
  1. MauiProgram.cs: call LoadSession()
            // Supabase
            builder.Services.AddScoped<Supabase.Client>(
                provider =>
                {
                    var session = new CustomSupabaseSessionHandler(provider.GetRequiredService<ILogger<CustomSupabaseSessionHandler>>());

                    var client = new Supabase.Client(
                        url,
                        supabaseKey,
                        new Supabase.SupabaseOptions
                        {
                            AutoRefreshToken = true,
                            AutoConnectRealtime = true,
                            SessionHandler = session
                        }
                    );

                    client.Auth.LoadSession();

                    return client;
                }
            );

Now everything works ;)

@wgrs
Comment options

@salsa2k

Any idea how to go about this with a web api?

I am trying to enable .net 8 auth in the webapi and rely on the JWT issued by supabase. I tried adding bearer token auth in the web api but it always returns 401 ( unauthorised ).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
🙏
Q&A
Labels
None yet
4 participants
Morty Proxy This is a proxified and sanitized view of the page, visit original site.