How to integrate Userauth and UserauthDetail with my tables


I find SS has default tables for authentication, but i use database first and i want to migrate my webapi to SS, could you tell me how to integrate Userauth and UserauthDetail with my authenticated tables.

  1. Can i use my tables and ignore SS feature?
  2. I use token to give client’s permission. what’s parts of SS feature i can reuse?


See this answer for extending ServiceStack Authentication.

ServiceStack has Roles and Permissions for limiting access that you may be able to use.

I find code below, Does it mean i do not need to create table in the datebase, i just need to extracting UserAuth info into my own custom tables.

All the things i need to do is calling this. suppose my table is “user”:
var user = session.TranslateTo();

Am i right?

Extracting UserAuth info into your own custom tables

Another option is to do what the SocialBootstrapApi example demo is doing and extract the UserAuth info into your own custom tables by overriding the OnAuthenticated hook in your own custom UserSession which get’s called each time a user successfully authenticates.

Here’s the SocialBootstrapApi example of copying the session data into a custom user POCO and saving it in a different table.

public class CustomUserSession : AuthUserSession
public string CustomId { get; set; }

public override void OnAuthenticated(IServiceBase authService, IAuthSession session, 
    IOAuthTokens tokens, Dictionary<string, string> authInfo)
    base.OnAuthenticated(authService, session, tokens, authInfo);

    //Populate all matching fields from this session to your own custom User table
    var user = session.TranslateTo<User>();
    user.Id = int.Parse(session.UserAuthId);
    user.GravatarImageUrl64 = !session.Email.IsNullOrEmpty()
        ? CreateGravatarUrl(session.Email, 64)
        : null;

    //Resolve the DbFactory from the IOC and persist the user info
    authService.TryResolve<IDbConnectionFactory>().Exec(dbCmd => dbCmd.Save(user));

The UserAuth RDBMS tables (if you’re using OrmLiteAuthRepository) has to exist in order for the UserAuth data to be persisted. The CustomUserSession is instead stored in the ICacheClient and gets hydrated from the UserAuthRepository during Authentication.

If the ICacheClient is cleared then all User Sessions are lost but users are still able to login to re-create the Session. But if rows in UserAuth tables are deleted then there’s no record of the user and they will no longer be able to login.

Thanks for your patient.

  1. I want to know the relation among UserAuth, UserAuthDetails and UserAuthRole.

  2. And i already have a User table with data. How do i migrate my data into those tables?

I find this answer, but i still want to you answer my question 2.

It’s a 1 to Many relationship where UserAuth = Combined/Summary User Info whilst UserAuthDetails = Login Details for a single OAuth provider (e.g. twitter, facebook, etc). You don’t need to extend both tables. –


See the last section Extracting UserAuth info into your own custom tables which just shows how you can copy the User Auth information from the Session and Auth Events into your own tables every time a User Authenticates.

Sorry, i do not explain my question clearly.

I have a user table which store my customers’s information, but i do not encrypt password before, it’s not safe.
I find UserAuth table has Salt, PasswordHash, DigestHa1hash, Roles, Permissions, i want to know how to migrate my pity users’ account to SS UserAuth.

My service should support App and website, Which provider should i use? Is there one auth provider could satisfy both Native App and website. I find CredentialsAuthProvider for html forms, it’s not suitable for app, BasicAuthProvider seams not safe, Is DigestAuthProvider the best choice? Or i should follow

So I have three questions here:

  1. i want to know how to migrate my pity users’ account(store password without encrypting) to SS UserAuth.
  2. Which provider should i use? Is DigestAuthProvider the best choice for authenticating cross platform? Or i should use different methods to support different platforms.
  3. is a good idea, i think the method is simple, i can give my app a secret to generate token, is it safe in javascript?

Thanks again

Please refer to the high-level Authentication Overview Diagram to see how the different Authentication components fit together.

If you want to import User Information containing UserNames and Passwords you would use a IUserAuthRepository which if you want to store them in a RDBMS then you would use the OrmLiteAuthRepository in ServiceStack.Server NuGet package.

You can then use the IUserAuthRepository API to Create new users which will add them to the underlying RDBMS UserAuth tables.

When Authenticating with UserNames or Passwords you can use any of the AuthProviders which accept and validate UserNames/Passwords for Authentication:

  • CredentialsAuthProvider - Most popular: authenticate via Browser / HTML Forms / Ajax Request
  • BasicAuthProvider - Only if you want to allow auth via HTTP Basic Auth
  • DigestAuthProvider - Only if you want to allow auth via HTTP Digest Auth

You’ll normally want CredentialsAuthProvider and only the other 2 if you need it.

Together this will look something like:

//Register which RDBMS you want to use
    new OrmLiteConnectionFactory(dbConnString, SqlServerDialect.Provider));

// Tell ServiceStack you want to enable Authentication with UserName/Password
Plugins.Add(new AuthFeature(
    () => new CustomUserSession(), //Use your own typed Custom UserSession type
    new IAuthProvider[] {
         //HTML Form post of UserName/Password credentials
        new CredentialsAuthProvider()

//Tell ServiceStack you want to persist User Info in the registered RDBMS
container.Register<IUserAuthRepository>(c =>
    new OrmLiteAuthRepository(c.Resolve<IDbConnectionFactory>()));

//Resolve instance of configured IUserAuthRepository
var userAuth = container.Resolve<IUserAuthRepository>();

//Create any missing UserAuth RDBMS tables

Now to import your data you can use the above registered dependencies, e.g:

// Open DB Connection to RDBMS
using (var db = container.Resolve<IDbConnectionFactory>().Open())
    //Example of fetching old Users out of a custom table (use your table instead)
    var oldUsers = db.Select<OldUserInfo>();

    //Go through and create new User Accounts using Old User Info
    foreach (var oldUser in oldUsers)
        //Create New User Info from Old Info
        var newUser = new UserAuth {
            UserName = oldUser.UserName,
            Email = oldUser.Email,

        //Create New User Account with oldUser Password
        authRepo.CreateUserAuth(newUser, oldUser.Password);

After this you’ll have new User Accounts from your old User Info which you can sign in with. For more information about configuring Authentication and registering users see the Authentication developer guide on HttpBenchmarks

very clear, thank you very much. :grin:


I get error “A connection was successfully established with the server, but then an error occurred during the pre-login handshake. (provider: SSL Provider, error: 0 - The wait operation timed out.)” when i call authRepo.CreateUserAuth(newUser, oldUser.Password);

Do you know what’s the problem?

oldUsers = db.SelectLazy();

I find should use lazy api…

I googled this and found:

I have extend UserAuth table and i want to register user now. But i find the example give me a Register POCO without my customer fields. For example, if i add “field1” in the UserAuth, how could i fill the field then register a new user. How do i register an new user ?

Could i do this :smile:
var newUserRegistration = new MyRegister
UserName = “UserName” + userId,
DisplayName = “DisplayName” + userId,
Email = “user{0}”.Fmt(userId),
FirstName = “FirstName” + userId,
LastName = “LastName” + userId,
Password = “Password” + userId,
AutoLogin = autoLogin,
Field1 = "my customer field"

I want to know where to fill field in the server code.

The exception because the table is large, i should use Db.SelectLazy();
I want to know how the SelectLazy generate the sql to get rows one by one .

I have check the log and find the sql is select XXX from XXX table where Id = @Id. I confused how to get all Ids. Maybe get all ids is not effective…

Please refer to the original answer on different ways of extending Auth Tables

The Register DTO’s are concrete DTO’s which can’t be extended.

Since RegisterService.cs is just a single class you can instead use your own copy of RegisterService, customized with all the additional fields you would like to add which you would then use instead of ServiceStack’s built-in Register Service.