Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a service for client authentication with servicestack?

I have a couple of applications (mobile and desktop) that I need a simple webservice created for authentication and to post information back to the clients.

After having man problems trying to figure out how to create a membership database or even find a previous one to check against with the WCF service I am using, I have stumbled upon service stack. So I have a couple of questions.

Does service stack have an out of the box database and provider so that I can simply add authentication for the clients, and have it create the database itself. So I do not have to create it from scratch.

Is their an example of a servicestack service and database already so I can use as a foundation?

The whole WCF services thing is having me confused. Basically all I am looking for is a service that I can use to authorize a mobile app and desktop app, and maybe later on add some extra functionality to it. It would need its own db since it won't be run from an existing website, and a way for me to manage them.

With WCF it seems overly complex for the task and I haven't found any examples with a database already to use and a way to manage them. Ideally I would of liked to have a blank website set up just so I could administer the accounts and have the WCF service use the same database.

Can this all be done easily with service stack, and could anyone point to an example for it already? If you have any tips on my current approach that would help aswell.

like image 838
user1632018 Avatar asked Mar 19 '13 22:03

user1632018


1 Answers

I recommend reading the Authentication and authorization wiki which explains the Authentication support built-into ServiceStack.

Backend Repository options

It describes all the potential backend repositories you can persist the authenticated UserData to, long-term:

  • OrmLite: OrmLiteAuthRepository in ServiceStack
  • Redis: RedisAuthRepository in ServiceStack
  • In Memory: InMemoryAuthRepository in ServiceStack
  • Mongo DB: MongoDBAuthRepository in ServiceStack.Authentication.MongoDB
  • Raven DB: RavenUserAuthRepository in ServiceStack.Authentication.RavenDB
  • NHibernate: NHibernateUserAuthRepository in ServiceStack.Authentication.NHibernate

Short-term Session / Caching providers

As well as all the different caching options that's used for fast, short-term data-access of authenticated client sessions:

  • In Memory: MemoryCacheClient in ServiceStack
  • Redis: RedisClient, PooledRedisClientManager or BasicRedisClientManager in ServiceStack.Redis
  • Memcached: MemcachedClientCache in ServiceStack.Caching.Memcached
  • Azure: AzureCacheClient in ServiceStack.Caching.Azure

By default the MemoryCacheClient is used if one isn't specified.

Example project

You can look at the source code for the SocialBootstrap API project which is deployed on http://bootstrapapi.apphb.com which is an example demo that showcases all of ServiceStack's supported authentication options enabled in a web application.

I'll re-post the code and documentation from the AppHost.ConfigureAuth(), since it already does a good job explaining how to configure it.

The AppSettings is used by most Auth Providers to access additional information stored the Web.Config:

var appSettings = new AppSettings();

You use the AuthFeature plugin to Register all Authentication methods you want to enable for this web app:

Plugins.Add(new AuthFeature(
    () => new CustomUserSession(), //Use your own typed Custom UserSession type
    new IAuthProvider[] {
        new CredentialsAuthProvider(),              //HTML Form post of UserName/Password credentials
        new TwitterAuthProvider(appSettings),       //Sign-in with Twitter
        new FacebookAuthProvider(appSettings),      //Sign-in with Facebook
        new DigestAuthProvider(appSettings),        //Sign-in with Digest Auth
        new BasicAuthProvider(),                    //Sign-in with Basic Auth
        new GoogleOpenIdOAuthProvider(appSettings), //Sign-in with Google OpenId
        new YahooOpenIdOAuthProvider(appSettings),  //Sign-in with Yahoo OpenId
        new OpenIdOAuthProvider(appSettings),       //Sign-in with Custom OpenId
    }));

ServiceStack allows you to specify your own typed CustomUserSession which is what it will use to persist the UserAuth data into the Session.

If you want to enable Registration services for new users so they can register and login with their supplied credentials:

Plugins.Add(new RegistrationFeature());

You can optionally override the default registration validation with your own custom implementation:

//container.RegisterAs<CustomRegistrationValidator, IValidator<Registration>>();

If you are using an OrmLite RDBMS backend repository you need to register a DB Factory, in this case it's configured to access the UserAuth SQL Server DB:

var connStr = appSettings.Get("SQLSERVER_CONNECTION_STRING", //AppHarbor or Local connection string
    ConfigUtils.GetConnectionString("UserAuth"));
container.Register<IDbConnectionFactory>(
    new OrmLiteConnectionFactory(connStr, //ConnectionString in Web.Config
        SqlServerOrmLiteDialectProvider.Instance) {
            ConnectionFilter = x => new ProfiledDbConnection(x, Profiler.Current)
        });

The above ConnectionFilter is optional, but allows you to profile the DB queries with ServiceStack's built-in Mini Profiler.

Now that you've registered your RDBMS connection above, you can hook it up so it becomes the IUserAuthRepository for the Authentication Feature:

//Use OrmLite DB Connection to persist the UserAuth and AuthProvider info
container.Register<IUserAuthRepository>(c =>
    new OrmLiteAuthRepository(c.Resolve<IDbConnectionFactory>())); 

If you use the OrmLiteAuthRepository, it can automatically create the backend User Auth tables required by the AuthFeature:

//Drop and re-create all Auth and registration tables
var authRepo = (OrmLiteAuthRepository)container.Resolve<IUserAuthRepository>();
if (appSettings.Get("RecreateAuthTables", false))
    authRepo.DropAndReCreateTables(); 
else
    authRepo.CreateMissingTables(); //Create only the missing tables
like image 125
mythz Avatar answered Sep 30 '22 11:09

mythz