Persist to UserAuth when using AspNetWindowsAuthProvider

Is there a simple way to persist all Windows user names that access my service using AspNetWindowsAuthProvider?

Plugins.Add(new AuthFeature(() => new AuthUserSession(), new IAuthProvider[] { new AspNetWindowsAuthProvider(this) { PersistSession = true, AllowAllWindowsAuthUsers = true, LoadUserAuthFilter = LoadUserAuthInfo }  } ));

I think in a previous version it would do this automatically, but my reading of the Authentication & Authorization docs indicates that the windowsauth no longer persists to the UserAuth table.

Ideally I would like to allow all Windows authenticated users to access my service and be automatically registered in the UserAuth table so that these can be used to assign roles and monitor who is accessing the service.

It may have persisted the Session but I don’t believe it ever saved to the UserAuth table.

But you should be able to manually save and populate/create the Session if it doesn’t exist with something like:

new AspNetWindowsAuthProvider(this)
    PopulateUserRoles = (req, principal, session) =>
        var authRepo = HostContext.AppHost.GetAuthRepository(req);
        var userAuth = authRepo.GetUserAuth(session, tokens:null);
        if (userAuth == null)
            userAuth = authRepo.GetUserAuth(session, tokens:null);
        session.PopulateSession(userAuth, authTokens:null);

That sounds like it will do perfectly, but I am getting System.NullReferenceException: 'Object reference not set to an instance of an object.' on the authRepo.SaveUserAuth(session); line.

Am I missing something obvious?

StackTrace    "   at ServiceStack.Auth.OrmLiteAuthRepositoryBase`2.<>c__DisplayClass25_0.<SaveUserAuth>b__0(IDbConnection db)\r\n   at ServiceStack.Auth.OrmLiteAuthRepository`2.Exec(Action`1 fn)\r\n   at Grip.AppHost.<>c.<Configure>b__1_4(IRequest req, IPrincipal principal, IAuthSession session) in C:\\Code\\mapdojo\\Grip\\Grip\\Grip\\AppHost.cs:line 145\r\n   at ServiceStack.Auth.AspNetWindowsAuthProvider.Authenticate(IServiceBase authService, IAuthSession session, Authenticate request)\r\n   at ServiceStack.Auth.AuthenticateService.Post(Authenticate request)\r\n   at ServiceStack.Auth.AspNetWindowsAuthProvider.PreAuthenticate(IRequest req, IResponse res)\r\n   at ServiceStack.AuthenticateAttribute.PreAuthenticate(IRequest req, IEnumerable`1 authProviders)\r\n   at ServiceStack.AuthenticateAttribute.<ExecuteAsync>d__12.MoveNext()"    string

I can’t see the issue, it’s just calling:

You can try converting it to a UserAuth and saving that instead which should do the same thing, e.g:

userAuth = session.ConvertTo<UserAuth>();
1 Like

Thanks mate, that works perfectly!

I really appreciate the support :nerd_face::grin:

1 Like