How to logout a logged in user

Hi,

i am using my my own Credentialsprovider as im using old aspnet_users tables for login.
How do i logout an logged in user?

      private void ConfigureAuthentication(Container container)
    {
        // TODO: Migrate users to something sensible
        // Register our user repository, a bridge implementation to
        // read users from ASP.NET Membership. 

        var apiKeyFilter = new ApiKeyRequestFilter(container.Resolve<IDbConnectionFactory>());

        var userRep = new AspNetMembershipAuthRepository(
            container.Resolve<IMembershipProviderWrapper>(),
            container.Resolve<IRoleProviderWrapper>(),
            container.Resolve<IDbConnectionFactory>());
        container.Register<IUserAuthRepository>(userRep);

        var authSession = new AspnetMembershipAuthSession(container.Resolve<IRoleProviderWrapper>(),userRep);

        var authProviders = new IAuthProvider[] {new BasicAuthProvider(), new MyCredentialsAuthProvider(), new ApiKeyAuthProvider() };

        var authFeature = new AuthFeature(() => authSession, authProviders);



        // See: https://servicestack.uservoice.com/forums/176786-feature-requests/suggestions/6440387-authfeature-serviceroutes-option-to-hide-route
        authFeature.DeleteSessionCookiesOnLogout = true;
        authFeature.IncludeRegistrationService = false;
        authFeature.IncludeAssignRoleServices = false;
        authFeature.GenerateNewSessionCookiesOnAuthentication = false;
        authFeature.ServiceRoutes[typeof (AuthenticateService)] = new[]
        {
            "/authenticate",
            "/authenticate/{provider}"
        };

        //Register all Authentication methods you want to enable for this web app.
        Plugins.Add(authFeature);
    }

See the Authentication docs for logging out a user, which you can logout with the C# Service Clients with:

client.Post(new Authenticate { provider = "logout" });

Or sending an empty POST request to /auth/logout route.

Thx mytz,

but it seems that my session is not cleared as the same session id is kept after.

In my code Id and id2 is the same

  public override void OnLogout(IServiceBase authService)
    {
        var id = authService.GetSessionId();
        authService.RemoveSession();
        var id2 = authService.GetSessionId();

        base.OnLogout(authService);
    }

Removing a Session, removes the session from the Cache so the user is no longer authenticated but it doesn’t change the SessionId that’s identified by the Cookie on the incoming HTTP Request. The Logout() Service then clears the Session Ids by returning a HTTP Response which expires the Session Cookies.

The next HTTP Request will then no longer use the existing Session Cookies and will be issued new ones.

I still have problems with my sessions not being logged out.
I think i’m doing something wrong.

In my apphost i send back some userdata on authenticate and after logout my session still seeems to be active

As the user object still contains the data after the logout is called
Also it seems that i sometimes will get another users sessions as it returns data that belongs to another company

 private void ConfigureRequestFilters(Container container)
    {

        var apiKeyFilter = new ApiKeyRequestFilter(container.Resolve<IDbConnectionFactory>());

        
        var basicAuthFilter = new BasicAuthPreAuthFilter();

        container.Register(apiKeyFilter);
        container.Register(basicAuthFilter);

        GlobalRequestFilters.Add(apiKeyFilter.Verify);
        GlobalRequestFilters.Add(basicAuthFilter.Verify);
        
        
        //Add customer authentication repsonse metadata properties for user
        this.GlobalResponseFilters.Add((req, res, responseDto) =>
        {
            if (res.Dto.GetType() == typeof(AuthenticateResponse))
            {
                var user = ((BokaMera.API.ServiceInterface.Security.AspNetMembership.AspnetMembershipAuthSession)res.Request.GetSession());
                var cs = (BokaMera.API.ServiceInterface.Security.AspNetMembership.AspnetMembershipAuthSession)req.GetSession();

                Dictionary<string, string> customUserData = new Dictionary<string, string>();
                customUserData.Add("CompanyUserId", user.CompanyUserId.ToString());
                customUserData.Add("CustomerId", user.CustomerId.ToString());
                customUserData.Add("FirstName", user.FirstName);
                customUserData.Add("LastName", user.LastName);
                customUserData.Add("Language", user.Language);
                customUserData.Add("ReferrerUrl", user.ReferrerUrl);
                customUserData.Add("SessionExpires", DateTime.Now.ToString());
                
                ((AuthenticateResponse)res.Dto).Meta = customUserData;
            }
        });
    }

I can’t tell what you’re doing wrong either, but calling /auth/logout does Logout the Authenticated User for that Request (identified by the Session Cookies on the HTTP Request).

You can test this by calling /auth after calling /auth/logout which should return a 401 HTTP Error Response indicating the logged out User is no longer authenticated.

Hi Mythz,
thx for your fast reply.

I tried it and got a 200 response and also my DTO.

Is it possible to hire you or another developer on a hourly rate to have a look on my project through teamviewer? I quite desperate to get this to work. Would be very appriceated

{

“UserId”: “0”,
“SessionId”: “usaOSfR1dj8devMhTnyQ”,
“UserName”: “demo3@bokamera.se”,
“DisplayName”: “demo3@bokamera.se”,
“ResponseStatus”: {},
“Meta”: {
“CompanyUserId”: “00000000-0000-0000-0000-000000000012”,
“CustomerId”: “00000000-0000-0000-0000-000000000012”,
“FirstName”: “Kalle”,
“LastName”: “Persson”,
“Language”: “en-GB”,
“SessionExpires”: “2017-01-19 15:45:09”
}
}

Then there’s something wrong with your custom auth setup.

Unfortunately we don’t have the spare bandwidth to offer any Consulting Services, we’re all busy focused on shipping the next release out.

But I’m happy if anyone else here would take you up on your offer.

1 Like

Thx Mythz, i have full undestanding for this. I will have to search further on this.
If you get any time left please let me know!