diff --git a/packages/Gotrue/Gotrue.Tests/SignOut/AdminSignOutAccessTokenTests.cs b/packages/Gotrue/Gotrue.Tests/SignOut/AdminSignOutAccessTokenTests.cs
new file mode 100644
index 00000000..21611760
--- /dev/null
+++ b/packages/Gotrue/Gotrue.Tests/SignOut/AdminSignOutAccessTokenTests.cs
@@ -0,0 +1,33 @@
+#region
+
+using System;
+using System.Threading.Tasks;
+using FluentAssertions;
+using Microsoft.VisualStudio.TestTools.UnitTesting;
+using Supabase.Gotrue;
+
+#endregion
+
+namespace Gotrue.Tests.SignOut;
+
+///
+/// The access-token check made before an admin sign-out leaves the SDK.
+///
+[TestClass]
+[TestCategory("Unit")]
+public class AdminSignOutAccessTokenTests
+{
+ private static readonly AdminClient Admin = new("service-role-jwt", new ClientOptions { Url = "http://localhost" });
+
+ [TestMethod]
+ [DataRow(null)]
+ [DataRow("")]
+ [DataRow(" ")]
+ public async Task SignOutAsync_ShouldThrowArgument_GivenBlankAccessToken(string? accessToken)
+ {
+ var signOut = () => Admin.SignOutAsync(accessToken!);
+ await signOut.Should().ThrowExactlyAsync()
+ .WithMessage("*access token is required*", "without a token the auth server can only answer 401 no_authorization")
+ .WithParameterName("accessToken");
+ }
+}
diff --git a/packages/Gotrue/Gotrue.Tests/SignOut/AdminSignOutContractTests.cs b/packages/Gotrue/Gotrue.Tests/SignOut/AdminSignOutContractTests.cs
new file mode 100644
index 00000000..985c554c
--- /dev/null
+++ b/packages/Gotrue/Gotrue.Tests/SignOut/AdminSignOutContractTests.cs
@@ -0,0 +1,96 @@
+#region
+
+using System;
+using System.Net.Http;
+using System.Threading;
+using System.Threading.Tasks;
+using FluentAssertions;
+using Gotrue.Tests.Support;
+using Microsoft.VisualStudio.TestTools.UnitTesting;
+using Supabase.Gotrue;
+using Supabase.Gotrue.Exceptions;
+using WireMock.RequestBuilders;
+using WireMock.ResponseBuilders;
+using static Supabase.Gotrue.Constants;
+
+#endregion
+
+namespace Gotrue.Tests.SignOut;
+
+///
+/// Pins the wire contract of signing a user out as an admin against a stubbed auth server: the scope, the user's
+/// token as the credentials instead of the service key, failures, and cancellation.
+///
+[TestClass]
+[TestCategory("Contract")]
+public class AdminSignOutContractTests
+{
+ private const string ServiceKey = "service-role-jwt";
+ private const string UserAccessToken = "user-access-token";
+
+ private MockGotrueServer server = null!;
+
+ [TestInitialize]
+ public void TestInitialize() => this.server = new MockGotrueServer();
+
+ [TestCleanup]
+ public void TestCleanup() => this.server.Dispose();
+
+ [TestMethod]
+ public async Task SignOutAsync_ShouldPostToLogoutWithUserAccessTokenAndConfiguredApiKey()
+ {
+ this.AnswerLogoutWith(204);
+ await this.Admin.SignOutAsync(UserAccessToken);
+ this.server.VerifySingleReceivedRequest()
+ .WithMethod(HttpMethod.Post)
+ .WithPath("/logout")
+ .WithHeader("Authorization", $"Bearer {UserAccessToken}")
+ .WithHeader("apikey", MockGotrueServer.ApiKey);
+ }
+
+ [TestMethod]
+ public async Task SignOutAsync_ShouldSendGlobalScope_GivenNoScope()
+ {
+ this.AnswerLogoutWith(204);
+ await this.Admin.SignOutAsync(UserAccessToken);
+ this.server.VerifySingleReceivedRequest().WithQueryParam("scope", "global");
+ }
+
+ [TestMethod]
+ [DataRow(SignOutScope.Global, "global")]
+ [DataRow(SignOutScope.Local, "local")]
+ [DataRow(SignOutScope.Others, "others")]
+ public async Task SignOutAsync_ShouldSendTheRequestedScope(SignOutScope scope, string expected)
+ {
+ this.AnswerLogoutWith(204);
+ await this.Admin.SignOutAsync(UserAccessToken, scope);
+ this.server.VerifySingleReceivedRequest().WithQueryParam("scope", expected);
+ }
+
+ [TestMethod]
+ public async Task SignOutAsync_ShouldThrowSessionNotFound_GivenSessionAlreadyRevoked()
+ {
+ this.AnswerLogoutWith(403, """{"code":403,"error_code":"session_not_found","msg":"Session from session_id claim in JWT does not exist"}""");
+ var signOut = () => this.Admin.SignOutAsync(UserAccessToken);
+ await signOut.Should().ThrowExactlyAsync()
+ .Where(failure => failure.ErrorCode == "session_not_found",
+ "unlike a client's own sign-out, an admin sign-out reports a session that is already gone");
+ }
+
+ [TestMethod]
+ public async Task SignOutAsync_ShouldNotSendRequest_GivenCancelledToken()
+ {
+ using var cancelled = new CancellationTokenSource();
+ cancelled.Cancel();
+ var signOut = () => this.Admin.SignOutAsync(UserAccessToken, cancellationToken: cancelled.Token);
+ await signOut.Should().ThrowAsync();
+ this.server.CountReceivedRequests().Should().Be(0, "a cancelled token must stop the request before it reaches the wire");
+ }
+
+ private AdminClient Admin =>
+ new(ServiceKey, new ClientOptions { Url = this.server.Url, Headers = { ["apikey"] = MockGotrueServer.ApiKey } });
+
+ private void AnswerLogoutWith(int status, string body = "") =>
+ this.server.Given(Request.Create().WithPath("/logout").UsingPost())
+ .RespondWith(Response.Create().WithStatusCode(status).WithHeader("Content-Type", "application/json").WithBody(body));
+}
diff --git a/packages/Gotrue/Gotrue.Tests/SignOut/AdminSignOutTests.cs b/packages/Gotrue/Gotrue.Tests/SignOut/AdminSignOutTests.cs
new file mode 100644
index 00000000..2a6e0fdf
--- /dev/null
+++ b/packages/Gotrue/Gotrue.Tests/SignOut/AdminSignOutTests.cs
@@ -0,0 +1,52 @@
+#region
+
+using System;
+using System.Threading.Tasks;
+using FluentAssertions;
+using Gotrue.Tests.Admin;
+using Gotrue.Tests.Support;
+using Microsoft.VisualStudio.TestTools.UnitTesting;
+using Supabase.Gotrue.Exceptions;
+using static Gotrue.Tests.TestUtils;
+using static Supabase.Gotrue.Constants;
+
+#endregion
+
+namespace Gotrue.Tests.SignOut;
+
+///
+/// End-to-end admin sign-out against the live stack: each test signs up its own user, and the admin client ends
+/// that user's sessions from their access token.
+///
+[TestClass]
+[TestCategory("E2E")]
+public class AdminSignOutTests : AdminFixture
+{
+ [TestMethod]
+ public async Task SignOutAsync_ShouldRevokeUserSession()
+ {
+ var accessToken = await SignUpUser();
+ await this.Admin.SignOutAsync(accessToken);
+ var lookup = () => this.Admin.GetUser(accessToken);
+ await lookup.Should().ThrowAsync()
+ .Where(failure => failure.ErrorCode == "session_not_found",
+ "the auth server deletes the token's session on a global sign-out, so the token no longer authenticates");
+ }
+
+ [TestMethod]
+ public async Task SignOutAsync_ShouldThrowSessionNotFound_GivenSessionAlreadyRevoked()
+ {
+ var accessToken = await SignUpUser();
+ await this.Admin.SignOutAsync(accessToken, SignOutScope.Local);
+ var signOutAgain = () => this.Admin.SignOutAsync(accessToken);
+ await signOutAgain.Should().ThrowAsync()
+ .Where(failure => failure.ErrorCode == "session_not_found",
+ "the auth server answers 403 session_not_found to a token whose session was revoked");
+ }
+
+ private static async Task SignUpUser()
+ {
+ var session = await TestClients.AgainstCliStack().SignUp(RandomEmail(), Password);
+ return session?.AccessToken ?? throw new InvalidOperationException("The local stack returned no session on sign-up.");
+ }
+}
diff --git a/packages/Gotrue/Gotrue/AdminClient.cs b/packages/Gotrue/Gotrue/AdminClient.cs
index f5d1f693..1cc9b2ea 100644
--- a/packages/Gotrue/Gotrue/AdminClient.cs
+++ b/packages/Gotrue/Gotrue/AdminClient.cs
@@ -64,6 +64,11 @@ public Func>? GetHeaders
///
public Task GetUser(string jwt) => this.api.GetUser(jwt);
+ ///
+ [ImplementedCapability("auth.admin.sign_out")]
+ public Task SignOutAsync(string accessToken, Constants.SignOutScope scope = Constants.SignOutScope.Global, CancellationToken cancellationToken = default) =>
+ this.api.SignOutAsync(RequireAccessToken(accessToken), scope, cancellationToken);
+
///
[ImplementedCapability("auth.admin.invite_user")]
public async Task InviteUserByEmail(string email, InviteUserByEmailOptions? options = null)
@@ -144,6 +149,11 @@ public async Task DeleteUser(string uid, bool shouldSoftDelete = false)
public Task DeleteCustomProviderAsync(string identifier, CancellationToken cancellationToken = default) =>
this.api.DeleteCustomProviderAsync(this.serviceKey, identifier, cancellationToken);
+ private static string RequireAccessToken(string accessToken) =>
+ string.IsNullOrWhiteSpace(accessToken)
+ ? throw new ArgumentException("A user's access token is required to sign them out.", nameof(accessToken))
+ : accessToken;
+
///
[ImplementedCapability("auth.admin.create_provider")]
public Task CreateCustomProviderAsync(NewCustomProvider provider, CustomProviderOptions? options = null, CancellationToken cancellationToken = default) =>
diff --git a/packages/Gotrue/Gotrue/Api.cs b/packages/Gotrue/Gotrue/Api.cs
index 10b7df66..d4875a70 100644
--- a/packages/Gotrue/Gotrue/Api.cs
+++ b/packages/Gotrue/Gotrue/Api.cs
@@ -723,12 +723,15 @@ public async Task UnlinkIdentity(string token, UserIdentity userIdentity)
///
///
///
- public Task SignOut(string jwt, SignOutScope scope = SignOutScope.Global)
- {
- var data = new Dictionary();
+ public Task SignOut(string jwt, SignOutScope scope = SignOutScope.Global) => this.SendSignOut(jwt, scope, CancellationToken.None);
- return this.MakeRequestAsync(HttpMethod.Post, $"{this.Url}/logout?scope={Core.Helpers.GetMappedToAttr(scope).Mapping}", data, this.CreateAuthedRequestHeaders(jwt));
- }
+ ///
+ public Task SignOutAsync(string jwt, SignOutScope scope = SignOutScope.Global, CancellationToken cancellationToken = default) =>
+ this.SendSignOut(jwt, scope, cancellationToken);
+
+ private Task SendSignOut(string jwt, SignOutScope scope, CancellationToken cancellationToken) =>
+ this.MakeRequestAsync(HttpMethod.Post, $"{this.Url}/logout?scope={Core.Helpers.GetMappedToAttr(scope).Mapping}", new Dictionary(),
+ this.CreateAuthedRequestHeaders(jwt), cancellationToken);
///
/// Gets User Details
diff --git a/packages/Gotrue/Gotrue/Interfaces/IGotrueAdminClient.cs b/packages/Gotrue/Gotrue/Interfaces/IGotrueAdminClient.cs
index c19e923c..fbf0c7e2 100644
--- a/packages/Gotrue/Gotrue/Interfaces/IGotrueAdminClient.cs
+++ b/packages/Gotrue/Gotrue/Interfaces/IGotrueAdminClient.cs
@@ -49,6 +49,33 @@ public interface IGotrueAdminClient : IGettableHeaders
///
Task GetUser(string jwt);
+ ///
+ /// Signs a user out on the server from their access token, revoking the refresh tokens of the sessions in
+ /// . Access tokens already issued stay valid until they expire. Call it from a server,
+ /// for example to end a user's sessions after a password reset or a ban.
+ ///
+ /// The user's access token. It authenticates the request: the service key is not sent.
+ ///
+ /// Which sessions to revoke: (the default) revokes every session of the
+ /// user, only the token's session, and
+ /// every session but the token's.
+ ///
+ /// Cancels the request.
+ /// is null, empty or whitespace. Nothing is sent.
+ ///
+ /// The server rejected the token. is session_not_found
+ /// when the token's session was already revoked and user_not_found when its user was deleted;
+ /// is
+ /// (error code bad_jwt) when the token is expired, malformed or not a user's token.
+ ///
+ ///
+ ///
+ /// var admin = new AdminClient(serviceRoleKey, new ClientOptions { Url = authUrl, Headers = { ["apikey"] = anonKey } });
+ /// await admin.SignOutAsync(userAccessToken, Constants.SignOutScope.Global);
+ ///
+ ///
+ Task SignOutAsync(string accessToken, Constants.SignOutScope scope = Constants.SignOutScope.Global, CancellationToken cancellationToken = default);
+
///
/// Gets a user by ID from the server using the admin key (not the anonymous key).
///
diff --git a/packages/Gotrue/Gotrue/Interfaces/IGotrueApi.cs b/packages/Gotrue/Gotrue/Interfaces/IGotrueApi.cs
index f06913aa..d3fa36d5 100644
--- a/packages/Gotrue/Gotrue/Interfaces/IGotrueApi.cs
+++ b/packages/Gotrue/Gotrue/Interfaces/IGotrueApi.cs
@@ -42,6 +42,15 @@ public interface IGotrueApi : IGettableHeaders
Task SignInWithSSO(Guid providerId, SignInWithSSOOptions? options = null);
Task SignInWithSSO(string domain, SignInWithSSOOptions? options = null);
Task SignOut(string jwt, SignOutScope scope = SignOutScope.Global);
+
+ ///
+ /// Revokes the sessions of the user who owns , within .
+ ///
+ /// The user's access token.
+ /// Which of the user's sessions to revoke.
+ /// Cancels the request.
+ /// The server rejected the request.
+ Task SignOutAsync(string jwt, SignOutScope scope = SignOutScope.Global, CancellationToken cancellationToken = default);
Task SignUpWithEmail(string email, string password, SignUpOptions? options = null);
Task SignUpWithPhone(string phone, string password, SignUpOptions? options = null);
Task UpdateUser(string jwt, UserAttributes attributes);
diff --git a/packages/Gotrue/Gotrue/PublicAPI.Unshipped.txt b/packages/Gotrue/Gotrue/PublicAPI.Unshipped.txt
index e0013c85..2c0e4de1 100644
--- a/packages/Gotrue/Gotrue/PublicAPI.Unshipped.txt
+++ b/packages/Gotrue/Gotrue/PublicAPI.Unshipped.txt
@@ -138,3 +138,7 @@ Supabase.Gotrue.CreateCustomProvider.NewCustomProvider.Type.get -> Supabase.Gotr
Supabase.Gotrue.CreateCustomProvider.NewCustomProvider.UserInfoUrl.get -> System.Uri?
Supabase.Gotrue.Interfaces.IGotrueAdminClient.CreateCustomProviderAsync(Supabase.Gotrue.CreateCustomProvider.NewCustomProvider! provider, Supabase.Gotrue.Common.CustomProviderOptions? options = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task!
Supabase.Gotrue.Interfaces.IGotrueApi.CreateCustomProviderAsync(string! jwt, Supabase.Gotrue.CreateCustomProvider.NewCustomProvider! provider, Supabase.Gotrue.Common.CustomProviderOptions? options = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task!
+Supabase.Gotrue.AdminClient.SignOutAsync(string! accessToken, Supabase.Gotrue.Constants.SignOutScope scope = Supabase.Gotrue.Constants.SignOutScope.Global, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task!
+Supabase.Gotrue.Api.SignOutAsync(string! jwt, Supabase.Gotrue.Constants.SignOutScope scope = Supabase.Gotrue.Constants.SignOutScope.Global, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task!
+Supabase.Gotrue.Interfaces.IGotrueAdminClient.SignOutAsync(string! accessToken, Supabase.Gotrue.Constants.SignOutScope scope = Supabase.Gotrue.Constants.SignOutScope.Global, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task!
+Supabase.Gotrue.Interfaces.IGotrueApi.SignOutAsync(string! jwt, Supabase.Gotrue.Constants.SignOutScope scope = Supabase.Gotrue.Constants.SignOutScope.Global, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task!