hammadmirza
hammadmirza

Reputation: 156

Cookieless authentication using ServiceStack

I am building a REST API using ServiceStackV3 hosted in ASP.NET MVC 4 Project. Want to use HttpBasic Authentication over SSL.

I want to achieve the following using ServiceStackV3:

even if it means username/password be supplied in each request without maintaining any session or cache.

Should i do it using:

here is what i did already and working fine, not sure if its a good way:

(keep in mind that i am running ServiceStack on /api)

protected void Application_Start()
{
    AreaRegistration.RegisterAllAreas();
    RouteConfig.RegisterRoutes(RouteTable.Routes);
    //Initialize your application
    (new ServiceAppHost()).Init();
}

protected void Application_AuthenticateRequest(object sender, EventArgs e)
{
    var segments = Request.Url.Segments;
    //someone is at /api/something but metadata should be consumed by everyone
    if (segments.Length > 2 
        && segments[1] == "api/" 
        && segments[2].Replace("/", "") != "metadata")
    {
        //need to authenticate
        int UserID = -1;
        bool authorized = false;
        string authorization = Request.Headers["Authorization"];
        if (!string.IsNullOrWhiteSpace(authorization))
        {
            string[] parts = authorization.Split(' ');
            if (parts[0] == "Basic")//basic authentication
            {
                authorization = UTF8Encoding.UTF8.GetString(Convert.FromBase64String(parts[1]));
                string username = authorization.Split(':')[0], password = authorization.Split(':')[1];
                if (username == "mustermann" && password == "johndoe")
                {
                    authorized = true;
                    UserID = 13;//get from database
                    Request.Headers.Add("X-UserID", UserID + "");
                }
            }
        }

        if (!authorized)
        {
            HttpContext.Current.Items["NeedAuthenticate"] = true;
            Response.End();
        }
    }
}

void Application_EndRequest(object sender, EventArgs e)
{
    if ((bool?)HttpContext.Current.Items["NeedAuthenticate"] == true)
    {
        Response.Clear();
        Response.AddHeader("WWW-Authenticate", string.Format("Basic realm=\"{0}\"", Request.Url.Host));
        Response.SuppressContent = true;
        Response.StatusCode = (int)System.Net.HttpStatusCode.Unauthorized;
        Response.End();
    }
}

public class MyBasicAuthProvicer : BasicAuthProvider
{
    public override bool TryAuthenticate(IServiceBase authService,
    string userName, string password)
    {
        //username & password were already validated in Global.asax
        return true;
    }
}

public class CustomUserSession : AuthUserSession
{
    //some properties of my own
    //public Kunden CurrentKunden {get;set;}

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

        int UserID = 0;
        if (int.TryParse(authService.Request.Headers["X-UserID"], out UserID))
        {
            //get user by ID from DB and assign to CurrentKunden
            //or maybe put Kunden object in Session from Global.asax?!?
        }
    }
}

Upvotes: 2

Views: 263

Answers (1)

jklemmack
jklemmack

Reputation: 3636

I'm doing something similar, using the ServiceStack v4 API. In my world, the REST API uses HTTP basic credentials over SSL, and only the "password" part (PIN #) is used for authentication. Here's the relevant parts of my Configure(container) method:

IAuthProvider authProvider = new BasicAuthProvider();
AuthFeature authFeature = new AuthFeature(
    () =>
      {
        return new AuthUserSession();
      },
    new IAuthProvider[] { authProvider }
    );
authFeature.IncludeAssignRoleServices = false;
authFeature.IncludeRegistrationService = false;
authFeature.IncludeAuthMetadataProvider = false;
Plugins.Add(authFeature);

// **** MY CUSTOM AUTH REPO
container.Register<IUserAuthRepository>(new BMSUserAuthRepository(() => dbFactory.OpenDbConnection()));

Another tidbit is that sometimes the Session isn't accessible. This global filter ensures the session is available, including username, auth roles, etc.

// Add a request filter storing the current session in HostContext to be
// accessible from anywhere within the scope of the current request.
this.GlobalRequestFilters.Add((httpReq, httpRes, requestDTO) =>
{
    var session = httpReq.GetSession();
    RequestContext.Instance.Items.Add("Session", session);
});

And finally, a snippet or two from my Auth repository. Note that a sane person would use caching, vs. looking up user auth data on every single HTTP request.

public class BMSUserAuthRepository : IUserAuthRepository
{
    private IDbConnection Db
    {
        get
        {
            return this.createDb();
        }
    }
    Func<IDbConnection> createDb;

    public BMSUserAuthRepository(Func<IDbConnection> dbConnectionFunc)
    {
        this.createDb = dbConnectionFunc;
    }

    ...

    public bool TryAuthenticate(string userName, string password, out IUserAuth userNameuserAuth)
    {
        User user = Db.Select<User>(u => /*u.UserName == userName && */ u.PIN == password).SingleOrDefault();
        if (user == null)
        {
            userNameuserAuth = new UserAuth();
            return false;
        }

        userNameuserAuth = new UserAuth()
        {
            FirstName = user.FirstName,
            LastName = user.LastName,
            Id = user.Id,
            UserName = user.UserName
        };
        return true;
    }

    public IUserAuth GetUserAuth(string userAuthId)
    {
        int id = Int32.Parse(userAuthId);
        User user = Db.SingleById<User>(id);

        List<string> roles = null;
        if (user != null) roles = Db.SqlList<string>(Db.From<Role>().Where<Role>(r => r.Id >= user.RoleId).Select(r => r.RoleName));

        return new UserAuth()
        {
            FirstName = user.FirstName,
            LastName = user.LastName,
            Id = user.Id,
            UserName = user.UserName,
            Roles = roles
        };
    }

    ...

}

Upvotes: 3

Related Questions