Kakashi_Hatake Kakashi_Hatake - 1 year ago 232
ASP.NET (C#) Question

User Authentication in ServiceStack

I did not get the Authentication and Authorization concept in servicestack.
I have been watching pluralsight tutorial but still i am not getting the point about how we can authenticate the username and password from our existing sql server database.

For Example if we authenticate user in asp.net with SQL server. there we provide connectionstring and then we write queries behind the button but in service stack how the plugins will work without knowing connectionstring and how user can logged in.

Please help me :(

Answer Source

If you're unsure how ServiceStack Authentication works I recommend looking to see how some of the Live Demos that use Authentication works:

Live Demos

To illustrate Authentication integration with ServiceStack, see the authentication-enabled live demos below:

but in service stack how the plugins will work without knowing connectionstring and how user can logged in.

ServiceStack doesn't guess, if you're using an RDBMS backend data store you'll need to tell ServiceStack by registering an OrmLiteAuthRepository which you'll need to pass it the IDbConnectionFactory that's configured with the DB ConnectionString and DB Type you want to use, e.g:

container.Register<IDbConnectionFactory>(c => new OrmLiteConnectionFactory(
    dbConnectionString, PostgreSqlDialect.Provider));

container.Register<IAuthRepository>(c =>
    new OrmLiteAuthRepository(c.Resolve<IDbConnectionFactory>()));

//Create any UserAuth tables that are missing

Authenticating with an existing Database

But if you want to authenticate with an existing Database you can't use ServiceStack's existing User Auth Repositories and will instead need to implement a Custom Auth Provider implementing TryAuthenticate() to validate the userName and password against your database yourself.

public class CustomCredentialsAuthProvider : CredentialsAuthProvider
    public override bool TryAuthenticate(IServiceBase authService, 
        string userName, string password)
        //Add here your custom auth logic (database calls etc)
        //Return true if credentials are valid, otherwise false

    public override IHttpResult OnAuthenticated(IServiceBase authService, 
        IAuthSession session, IAuthTokens tokens, 
        Dictionary<string, string> authInfo)
        //Fill IAuthSession with data you want to retrieve in the app eg:
        session.FirstName = "some_firstname_from_db";

        //Call base method to Save Session and fire Auth/Session callbacks:
        return base.OnAuthenticated(authService, session, tokens, authInfo);

        //Alternatively avoid built-in behavior and explicitly save session with
        //authService.SaveSession(session, SessionExpiry);
        //return null;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download