Skip to content


Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP

Authentication and authorization

Demis Bellot edited this page · 115 revisions

  1. Getting Started

    1. Creating your first project
      1. Create Service from scratch
    2. Your first webservice explained
    3. ServiceStack's new API Design
    4. Designing a REST-ful service with ServiceStack
    5. Example Projects Overview
    6. Learning Resources
  2. Reference

    1. Order of Operations
    2. The IoC container
    3. Configuration and AppSettings
    4. Metadata page
    5. Rest, SOAP & default endpoints
    6. SOAP support
    7. Routing
    8. Service return types
    9. Customize HTTP Responses
    10. Plugins
    11. Validation
    12. Error Handling
    13. Security
    14. Debugging
    15. JavaScript Client Library (ss-utils.js)
  3. Clients

    1. Overview
    2. C#/.NET client
    3. Add ServiceStack Reference
      1. C# Add Reference
      2. F# Add Reference
      3. VB.NET Add Reference
      4. Swift Add Reference
    4. Silverlight client
    5. JavaScript client
      1. Add TypeScript Reference
    6. Dart Client
    7. MQ Clients
  4. Formats

    1. Overview
    2. JSON/JSV and XML
    3. ServiceStack's new HTML5 Report Format
    4. ServiceStack's new CSV Format
    5. MessagePack Format
    6. ProtoBuf Format
  5. View Engines

    1. Razor & Markdown Razor
    2. Markdown Razor
  6. Hosts

    1. IIS
    2. Self-hosting
    3. Messaging
    4. Mono
  7. Security

    1. Authentication/authorization
    2. Sessions
    3. Restricting Services
  8. Advanced

    1. Configuration options
    2. Access HTTP specific features in services
    3. Logging
    4. Serialization/deserialization
    5. Request/response filters
    6. Filter attributes
    7. Concurrency Model
    8. Built-in caching options
    9. Built-in profiling
    10. Form Hijacking Prevention
    11. Auto-Mapping
    12. HTTP Utils
    13. Virtual File System
    14. Config API
    15. Physical Project Structure
    16. Modularizing Services
    17. ServiceStack Integration
    18. Embedded Native Desktop Apps
    19. Auto Batched Requests
  9. Server Events

    1. Overview
    2. JavaScript Client
    3. C# Server Events Client
    4. Redis Server Events
  10. Plugins

    1. Auto Query
    2. Server Sent Events
    3. Swagger API
    4. Postman
    5. Request logger
    6. Sitemaps
  11. Tests

    1. Testing
    2. HowTo write unit/integration tests
  12. ServiceStackVS

    1. Install ServiceStackVS
    2. Add ServiceStack Reference
    3. AngularJS App Template
    4. ReactJS App Template
  13. Other Languages

    1. FSharp
      1. Add ServiceStack Reference
    2. VB.NET
      1. Add ServiceStack Reference
    3. Swift
      1. Swift Add Reference
  14. Deployment

    1. Deploy Multiple Sites to single AWS Instance
      1. Simple Deployments to AWS with WebDeploy
    2. Advanced Deployments with OctopusDeploy
  15. Install 3rd Party Products

    1. Redis on Windows
    2. RabbitMQ on Windows
  16. Use Cases

    1. Single Page Apps
      1. HTML, CSS and JS Minifiers
    2. Azure
      1. Connecting to Azure Redis via SSL
    3. Logging
    4. Bundling and Minification
    5. NHibernate
  17. Performance

    1. Real world performance
  18. How To

    1. Sending stream to ServiceStack
    2. Setting UserAgent in ServiceStack JsonServiceClient
    3. ServiceStack adding to allowed file extensions
    4. Default web service page how to
  19. Future

    1. Roadmap
Clone this wiki locally

Built into ServiceStack is an optional Authentication feature you can use to add Authentication to your services by providing web services to Authenticate existing users, Register new users as well Assign/UnAssign Roles to existing users (if you need them). It's highly pluggable and customizable where you can plug-in your own Auth logic, change the caching and session providers as well as what RDBMS is used to persist UserAuth data.

A minimal configuration needed to get Basic Authentication up and running is the following in AppHost.Config() (derived from the AuthTests unit test):

public override void Configure(Container container)
    Plugins.Add(new AuthFeature(() => new AuthUserSession(),
      new IAuthProvider[] { 
        new BasicAuthProvider(), //Sign-in with Basic Auth
        new CredentialsAuthProvider(), //HTML Form post of UserName/Password credentials

    Plugins.Add(new RegistrationFeature());

    container.Register<ICacheClient>(new MemoryCacheClient());
    var userRep = new InMemoryAuthRepository();

    //The IUserAuthRepository is used to store the user credentials etc.
    //Implement this interface to adjust it to your app's data storage

The high-level overview below shows how all the different parts fit together and which parts are customizable:

Authentication Overview

Auth Providers

From the overview we can see the built-in AuthProviders that are included:

  • Credentials - For authenticating with username/password credentials by posting to the /auth/credentials service
  • AspNetWindowsAuthProvider - Allowing users to authenticate with Windows Authentication
  • Basic Auth - Allowing users to authenticate with Basic Authentication
  • Digest Auth - Allowing users to authenticate with HTTP Digest Authentication
  • Custom Credentials - By inheriting CredentialsAuthProvider and providing your own Username/Password TryAuthenticate implementation
  • Twitter OAuth (open standard for authorization) - Allow users to Register and Authenticate with Twitter
  • Facebook OAuth - Allow users to Register and Authenticate with Facebook
  • GitHub OAuth - Allow users to Register and Authenticate with GitHub
  • Yammer OAuth - Allow users to Register and Authenticate with Yammer
  • Yandex OAuth - Allow users to Register and Authenticate with Yandex
  • VK OAuth - Allow users to Register and Authenticate with VK
  • Odnoklassni OAuth - Allow users to Register and Authenticate with Odnoklassni

OpenId Auth Providers

The ServiceStack.Authentication.OpenId NuGet package provides OpenId Auth Providers support to ServiceStack that includes:

  • Google OpenId - Allow users to Register and Authenticate with Google
  • Yahoo OpenId - Allow users to Register and Authenticate with Yahoo
  • MyOpenId - Allow users to Register and Authenticate with MyOpenId
  • OpenId - Allow users to Register and Authenticate with any custom OpenId provider

Find more info about OpenId 2.0 providers on the wiki.

OAuth2 Providers

The ServiceStack.Authentication.OAuth2 NuGet package provides OAuth2 Providers support to ServiceStack that includes:

  • Google OAuth2 - Allow users to Register and Authenticate with Google OAuth2
  • LinkedIn OAuth2 - Allow users to Register and Authenticate with LinkedIn OAuth2

OAuth Configuration

The OAuth providers below require you to register your application with them in order to get the ConsumerKey and ConsumerSecret required, at the urls below:

AuthWebTests is a simple project that shows all Auth Providers configured and working in the same app. See the AppHost for an example of the code and the Web.config for an example of the configuration required to enable each Auth Provider.

Once you have the ConsumerKey and ConsumerSecret you need to configure it with your ServiceStack host, via Web.config, e.g:

<add key="oauth.twitter.RedirectUrl"    value=""/>
<add key="oauth.twitter.CallbackUrl"    value=""/>    
<add key="oauth.twitter.ConsumerKey"    value="3H1FHjGbA1N0n0aT5yApA"/>
<add key="oauth.twitter.ConsumerSecret" value="MLrZ0ujK6DwyjlRk2YLp6HwSdoBjtuqwXeHDQLv0Q"/>

Note: Each OAuth Config option fallbacks to the configuration without the provider name. This is useful for reducing repetitive configuration that's shared by all OAuth providers like the RedirectUrl or CallbackUrl, e.g:

<add key="oauth.RedirectUrl"    value=""/>
<add key="oauth.CallbackUrl"    value="{0}"/>    

Or via configuration in code when you register the AuthFeature in your AppHost, e.g:

Plugins.Add(new AuthFeature(() => new AuthUserSession(), new IAuthProvider[] {
    new TwitterAuthProvider(appSettings) { 
        RedirectUrl = "",
        CallbackUrl = "",
        ConsumerKey = "3H1FHjGbA1N0n0aT5yApA",
        ConsumerSecret = "MLrZ0ujK6DwyjlRk2YLp6HwSdoBjtuqwXeHDQLv0Q",

Note: The Callback URL in each Application should match the CallbackUrl for your application which is typically:{Provider}, e.g. for Twitter.

Built-In Auth Providers

By default the CredentialsAuthProvider and BasicAuthProvider validate against users stored in the UserAuth repository. The registration service at /register allow users to register new users with your service and stores them in your preferred IUserAuthRepository provider (below). The SocialBootstrapApi uses this to allow new users (without Twitter/Facebook accounts) to register with the website.

A good starting place to create your own Auth provider that relies on username/password validation is to subclass CredentialsAuthProvider and override the bool TryAuthenticate(service, username, password) hook so you can add in your own implementation. If you want to make this available via BasicAuth as well you will also need to subclass BasicAuthProvider with your own custom implementation.

UserAuth Persistence - the IUserAuthRepository

The Authentication module allows you to use your own persistence back-ends but for the most part you should be able to use one of the existing InMemory, Redis, OrmLite or MongoDB adapters. Use the OrmLite adapter if you want to store the Users Authentication information in any of the RDBMS's that OrmLite supports, which as of this writing includes Sql Server, Sqlite, MySql, PostgreSQL and Firebird.

Caching / Sessions - the ICacheClient

Once authenticated the AuthUserSession model is populated and stored in the Cache using one of ServiceStack's supported Caching providers. ServiceStack's Sessions simply uses the ICacheClient API so any new provider added can be used for both Session and Caching options. Which currently include the following implementations:

The Auth Feature also allows you to specify your own custom IUserAuthSession type so you can attach additional metadata to your users session which will also get persisted and hydrated from the cache.

Note: If you're using Custom Sessions and have JsConfig.ExcludeTypeInfo=true, you need to explicitly enable it with JsConfig<TCustomSession>.IncludeTypeInfo=true.

After authentication the client will receive a cookie with a session id, which is used to fetch the correct session from the ICacheClient internally by ServiceStack. Thus, you can access the current session in a service:

public class SecuredService : Service
    public object Get(Secured request)
        IAuthSession session = this.GetSession();
        return new SecuredResponse() { Test = "You're" + session.FirstName };

ServiceStack's Authentication, Caching and Session providers are completely new, clean, dependency-free testable APIs that doesn't rely on and is devoid of ASP.NET's existing membership, caching or session provider models.

Live Demos

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

Custom authentication and authorization

The classes in ServiceStack have been designed to provide default behavior out the box (convention over configuration). They are also highly customizable. Both the default BasicAuthProvider and CredentialsAuthProvider (which it extends) can be extended, and their behavior overwritten. An example is below:

using ServiceStack;
using ServiceStack.Auth;

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";

        return null;

Then you need to register your custom credentials auth provider:

//Register all Authentication methods you want to enable for this web app.
Plugins.Add(new AuthFeature(() => new AuthUserSession(),
    new IAuthProvider[] {
        new CustomCredentialsAuthProvider(), //HTML Form post of User/Pass

By default the AuthFeature plugin automatically registers the following (overrideable) Service Routes:

new AuthFeature = {
  ServiceRoutes = new Dictionary<Type, string[]> {
    { typeof(AuthService), new[]{"/auth", "/auth/{provider}"} },
    { typeof(AssignRolesService), new[]{"/assignroles"} },
    { typeof(UnAssignRolesService), new[]{"/unassignroles"} },

Auth Provider Routes

The AuthService is registered at paths /auth and /auth/{provider} where the Provider maps to the IAuthProvider.Provider property of the registered AuthProviders. The urls for clients authenticating against the built-in AuthProviders are:

  • /auth/credentials - CredentialsAuthProvider
  • /auth/basic - BasicAuthProvider
  • /auth/twitter - TwitterAuthProvider
  • /auth/facebook - FacebookAuthProvider
  • /auth/github - GithubAuthProvider
  • /auth/yammer - YammerAuthProvider
  • /auth/googleopenid - GoogleOpenIdOAuthProvider
  • /auth/yahooopenid - YahooOpenIdOAuthProvider
  • /auth/myopenid - MyOpenIdOAuthProvider
  • /auth/openid - OpenIdOAuthProvider (Any Custom OpenId provider)
  • /auth/linkedin - LinkedInOAuth2Provider
  • /auth/googleoauth - GoogleOAuth2Provider
  • /auth/yandex - YandexAuthProvider
  • /auth/vkcom - VkAuthProvider
  • /auth/odnoklassniki - OdnoklassnikiAuthProvider

e.g. to Authenticate with your CustomCredentialsAuthProvider (which inherits from CredentialsAuthProvider) you would POST:

POST localhost:60339/auth/credentials?format=json

    "UserName": "admin",
    "Password": "test",
    "RememberMe": true

When the client now tries to authenticate with the request above and the auth succeeded, the client will retrieve some cookies with a session id which identify the client on each Web Service call.

ServiceStack uses the Cache Provider which was registered in the IoC container:

//Register to use an In Memory Cache Provider (default)
container.Register<ICacheClient>(new MemoryCacheClient());

//Configure an alt. distributed persisted cache, E.g Redis:
//container.Register<IRedisClientsManager>(c => 
//    new RedisManagerPool("localhost:6379"));

Tip: If you've got multiple servers which run the same ServiceStack service, you can use Redis to share the sessions between these servers.

Please look at SocialBootstrapApi to get a full example.

Of course you can also implement your own - custom - authentication mechanism. You aren't forced to use the built-in ServiceStack auth mechanism.

The Authenticate attribute

But how does ServiceStack know, which service needs authentication? This happens with the AuthenticateAttribute.

You simply have to mark your request dto with this attribute:

//Authentication for all HTTP methods (GET, POST...) required
public class Secured
    public bool Test { get; set; }

Now this service can only be accessed if the client is authenticated:

public class SecuredService : Service
    public object Get(Secured request)
        IOAuthSession session = this.GetSession();
        return new SecuredResponse() { Test = "You're" + session.FirstName };

    public object Put(Secured request)
        return new SecuredResponse() { Test = "Valid!" };

    public object Post(Secured request)
        return new SecuredResponse() { Test = "Valid!" };

    public object Delete(Secured request)
        return new SecuredResponse() { Test = "Valid!" };

If you want, that authentication is only required for GET and PUT requests for example, you have to provide some extra parameters to the Authenticate attribute.

[Authenticate(ApplyTo.Get | ApplyTo.Put)] 

Of course Authenticate can also be placed on top of a service instead on top of a DTO, because it's a normal filter attribute.

RequiredRole and RequiredPermission attributes

ServiceStack also includes a built-in permission based authorization mechanism. More details about how Roles and Permissions work is in this StackOverflow Answer.

Your request DTO can require specific permissions:

//All HTTP (GET, POST...) methods need "CanAccess"
[RequiredPermission(ApplyTo.Put | ApplyTo.Post, "CanAdd")]
[RequiredPermission(ApplyTo.Delete, "AdminRights", "CanDelete")]
public class Secured
    public bool Test { get; set; }

Now the client needs the permissions...

  • "CanAccess" to make a GET request
  • "CanAccess", "CanAdd" to make a PUT/POST request
  • "CanAccess", "AdminRights" and "CanDelete" to make a DELETE request

If instead you want to allow access to users in ANY Role or Permission use:

[RequiresAnyRole(ApplyTo.Post, "Admin","Owner","Member")]
[RequiresAnyPermission(ApplyTo.Delete, "AdminRights", "CanDelete")]
public class Secured
    public bool Test { get; set; }

Normally ServiceStack calls the method bool HasPermission(string permission) in IAuthSession. This method checks if the list List<string> Permissions in IAuthSession contains the required permission.

IAuthSession is stored in a cache client as explained above

You can fill this list in the method OnAuthenticated you've overriden in the first part of this tutorial.

As with Authenticate, you can mark services (instead of DTO) with RequiredPermission attribute, too.

Enabling Authentication at different levels

Using the [Authenticate] Attribute

You can protect services by adding the [Authenticate] attribute on either the Action:

class MyService : Service {
    public object Get(Protected request) { ... }

The Request DTO

class Protected { ... }

Or the service implementation

class MyService : Service {
    public object Get(Protected request) { ... }

Or by inheriting from a base class

class MyServiceBase : Service { ... }

class MyService : MyServiceBase {
    public object Get(Protected request) { ... }

Using a Global Request Filter

Otherwise you can use a global Request Filter if you wanted to restrict all requests any other way, e.g something like:

appHost.RequestFilters.Add((httpReq, httpResp, requestDto) =>
    if (IsAProtectedPath(httpReq.PathInfo)) {
        new AuthenticateAttribute().Execute(httpReq, httpResp, requestDto);

Extending UserAuth tables

Different customization and extension points and strategies to extend the UserAuth tables with your own data are explained in this StackOverflow answer.

Customizing AuthProviders

Customizing User Roles and Permissions

The default implementation of User Roles and Permissions on AuthUserSession shows how ServiceStack's [RequiredRole] and [RequiredPermission] Roles and Permission attributes are validated:

public virtual bool HasPermission(string permission)
    var managesRoles = HostContext.TryResolve<IAuthRepository>() as IManageRoles;
    if (managesRoles != null)
        return managesRoles.HasPermission(this.UserAuthId, permission);

    return this.Permissions != null && this.Permissions.Contains(permission);

public virtual bool HasRole(string role)
    var managesRoles = HostContext.TryResolve<IAuthRepository>() as IManageRoles;
    if (managesRoles != null)
        return managesRoles.HasRole(this.UserAuthId, role);

    return this.Roles != null && this.Roles.Contains(role);

These APIs are virtual so they can be overridden in both your Custom AuthUserSession. They default to looking at the Roles and Permissions collections stored on the Session. These collections are normally sourced from the AuthUserRepository when persisting the UserAuth and UserAuthDetails POCO's and are used to populate the UserAuthSession on successful Authentication. These collections can be further customized by AuthProviders which is what AspNetWindowsAuthProvider does to add Authenticated WindowsAuth Roles.

As seen above Roles/Permissions can instead be managed by AuthProviders that implement IManageRoles API which is what OrmLiteAuthProvider uses to look at distinct RDBMS tables to validate Roles/Permissions:

IManageRoles API

The IManageRoles API can be implemented by any IAuthRepository to provide an alternative strategy for querying and managing Users Roles and permissions.

This API is being used in the OrmLiteAuthRepository to provide an alternative way to store Roles and Permission in their own distinct table rather than being blobbed with the rest of the User Auth data. You can enable this new behavior by specifying UseDistinctRoleTables=true when registering the OrmLiteAuthRepository, e.g:

container.Register<IAuthRepository>(c =>
    new OrmLiteAuthRepository(c.Resolve<IDbConnectionFactory>()) {
        UseDistinctRoleTables = true,

When enabled, roles and permissions are persisted in the distinct UserAuthRole table instead of being blobbed on the UserAuth. The IAuthSession.HasRole() and IAuthSession.HasPermission() on the Users Session should be used to check if a User has a specified Role or Permission.

More examples of this are in ManageRolesTests.cs.


The CustomValidationFilter on all AuthProviders lets you add post verification logic after a user has signed in with an OAuth provider and their OAuth metadata is retrieved. The filter lets you return a IHttpResult to control what error response is returned, e.g:

new FacebookAuthProvider(appSettings) { 
    CustomValidationFilter = authCtx => CustomIsValid(authCtx) 
        ? authCtx.Service.Redirect(authCtx.Session.ReferrerUrl
        : null,

Saving Extended OAuth Metadata

The new SaveExtendedUserInfo property (enabled by default) on all OAuth providers let you control whether to save the extended OAuth metadata available (into UserAuthDetails.Items) when logging in via OAuth.


An IAuthMetadataProvider provides a way to customize the authInfo in all AuthProviders. It also allows overriding of how extended Auth metadata like profileUrl is returned.

public interface IAuthMetadataProvider
   void AddMetadata(IAuthTokens tokens, Dictionary<string,string> authInfo);

   string GetProfileUrl(IAuthSession authSession, string defaultUrl = null);

To override with a custom implementation, register IAuthMetadataProvider in the IOC


The LoadUserAuthFilter on AspNetWindowsAuthProvider lets you retrieve more detailed information about Windows Authenticated users during Windows Auth Authentication by using the .NET's ActiveDirectory services, e.g:

new AspNetWindowsAuthProvider(this) {
    LoadUserAuthFilter = LoadUserAuthInfo

public void LoadUserAuthInfo(AuthUserSession userSession, 
    IAuthTokens tokens, Dictionary<string, string> authInfo)
    if (userSession == null) return;
    using (PrincipalContext pc = new PrincipalContext(ContextType.Domain))
        var user = UserPrincipal.FindByIdentity(pc, userSession.UserAuthName);
        tokens.DisplayName = user.DisplayName;
        tokens.Email = user.EmailAddress;
        tokens.FirstName = user.GivenName;
        tokens.LastName = user.Surname;
        tokens.FullName = (String.IsNullOrWhiteSpace(user.MiddleName))
            ? "{0} {1}".Fmt(user.GivenName, user.Surname)
            : "{0} {1} {2}".Fmt(user.GivenName, user.MiddleName, user.Surname);
        tokens.PhoneNumber = user.VoiceTelephoneNumber;

Community Resources

Something went wrong with that request. Please try again.