Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ServiceStack web services security

Hi I am new to working with Servicestack and have downloaded their very comprehensive bootstrapapi example and am working with it, but am still having some issues. The issue is with security, what is happening is I am getting 405 errors when trying to access the protected services. Using the authenticate service it appears that I am authenticating correctly. Please help and explain. Here is the code:

public class Hello
{
    public string Name { get; set; }
}

public class AuthHello
{
    public string Name { get; set; }
}

public class RoleHello
{
    public string Name { get; set; }
}
public class HelloResponse
{
    public string Result { get; set; }
}

The Services:

public class HelloService : ServiceBase<Hello> 
{
    //Get's called by all HTTP Verbs (GET,POST,PUT,DELETE,etc) and endpoints JSON,XMl,JSV,etc
    protected override object Run(Hello request)
    {
        return new HelloResponse { Result = "Hello, Olle är en ÖL ål " + request.Name };
    }
}

[Authenticate()]
public class AuthHelloService : RestServiceBase<AuthHello>
{
    public object Execute(Hello request)
    {
        return new HelloResponse { Result = "Hello, " + request.Name };
    }
}

[RequiredRole("Test")]
public class RoleHelloService : RestServiceBase<RoleHello>
{
    public object Execute(Hello request)
    {
        return new HelloResponse { Result = "Hello, " + request.Name };
    }
}

Here is the AppHost:

public class HelloAppHost : AppHostBase
    {
        //Tell Service Stack the name of your application and where to find your web services

        public HelloAppHost() : base("Hello Web Services", typeof(HelloService).Assembly) { }

        public override void Configure(Container container)
        {

            //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 UserName/Password credentials
            }));
        container.Register<ICacheClient>(new MemoryCacheClient() { FlushOnDispose = false });

            //register user-defined REST-ful urls
            Routes
              .Add<Hello>("/hello")
              .Add<Hello>("/hello/{Name}")
              .Add<AuthHello>("/AuthHello")
              .Add<RoleHello>("/RoleHello");
        }
    }

UPDATE

Everything works as expect if you replace : RestServiceBase with : ISevice so now the question is why.

like image 431
Chris Avatar asked Aug 23 '12 15:08

Chris


1 Answers

Check the wiki documentation first

I would first go through the documentation in ServiceStack's Authentication Wiki to get a better idea about how ServiceStack's Authentication works. There's a lot of documentation in the wiki, so if you're unsure of something you should refer to that first. It's a community wiki so feel free to expand whats there if you think it can help others.

Refer to the implementation in the source code if behavior is not clear

If you're unsure of what something does you should refer to the RequiredRole source code as the master authority as how it works. RequiredRole is just a Request Filter Attribute which gets run before every service that has the attribute.

The RequiredRole attribute just calls your session.HasRole() method as seen here:

public bool HasAllRoles(IAuthSession session)
{
    return this.RequiredRoles
        .All(requiredRole => session != null
            && session.HasRole(requiredRole));
}

Because it just calls your session you can override the implementation of session.HasRole() if you have a custom session.

Registering and Implementing a CustomUserSession

The Social BootstrapApi project does implement its own CustomSession that it registers here but does not override the HasRole() implementation so it uses the built-in implementation in the base AuthUserSession.HasRole() which simply looks like the Roles collection to see if the user has the specified role in their Session POCO:

public virtual bool HasRole(string role)
{
    return this.Roles != null && this.Roles.Contains(role);
}

Session properties populated by AuthUserRepository

The Roles property (as well as most other properties on a users Session) is populated by the AuthUserRepository that you have specified e.g. if you're using the OrmLiteAuthRepository like SocialBootstrapApi does here than the Roles attribute is persisted in the Roles column in the UserAuth RDBMS table. Depending on the AuthUserRepository you use the UserAuth / UserOAuthProvider POCOs get stored as RDBMS tables in OrmLite or as text blobs in Redis, etc.

Manage roles and permissions with AssignRoles / UnAssignRoles services

So for a user to have the required role (and authorization to pass), it should have this Role added to its UserAuth db row entry. ServiceStack's AuthFeature includes 2 services for managing users permissions and roles:

  • /assignroles
  • /unassignroles

How to initially give someone the Admin Role

These services does require a user with the Admin Role to be already authenticated. You can do this by manually changing a specific users UserAuth.Role column to include the value "Admin". The Social Bootstrap API project instead does this by handling the OnAuthenticated() event on its CustomUserSession that simply checks to see if the authenticated username is declared in the Web.Config and if it is, calls the AssignRoles service giving that authenticated user the Admin Role:

if (AppHost.Config.AdminUserNames.Contains(session.UserAuthName)
    && !session.HasRole(RoleNames.Admin))
{
    var assignRoles = authService.ResolveService<AssignRolesService>();
    assignRoles.Execute(new AssignRoles {
        UserName = session.UserAuthName,
        Roles = { RoleNames.Admin }
    });
}
like image 98
mythz Avatar answered Sep 20 '22 09:09

mythz