Skip Navigation LinksHome > View Post

Exploring custom identity in Mobile Services (Day 12)

This is the last post in the series the twelve days of ZUMO and we'll pull together many of the themes from the last few days, including unit testing scripts, generating your own auth tokens and setting the auth token.

In today's post, we'll go a little experimental, and explore how we could use all these techniques and the built in flexibility of Mobile Services to implement custom identity for our service, where Mobile Services stores your user's username and password and allows them to logon without using a social network.

In order to set this up, we'll need a table to store the user's details. I called it accounts and we'll use this table to store the credentials and also to login using the Mobile Service client.

accounts table

Since we'll allow anyone to register we set the INSERT permission to only require the application key. All other operations (especially READ) should be set to scripts and admins only.

We'll do all the work in the insert script with two flows:

1. Account creation

A POST (insert) to the /tables/accounts endpoint with a body will start the account creation flow. I'll leave it as an exercise for the reader to decide what other data they might want to store in the accounts table and how you'll validate it (e-mail for example? checkout our integration with sendgrid).

In this flow the majority of the work is generating a salt and hashing the password before we write it to storage. 

2. Login

A POST (insert) to the /tables/accounts endpoint with a login parameter set to "true" means this is a login attempt and we should return a 200 with user and token data if successful, otherwise we'll send a 401 Unauthorized.

In this flow, we load the user account from the database by matching the username. The record loaded should include the salt and hashed password (a unique salt per row helps prevent the use of highly effective lookup tables to crack your hashed passwords, if they should ever end up in the wrong hands). We then hash the submitted password and do an equality check with the stored password, if the credentials are good - the hash will match.

Without further a do, here's the script that does all this and should be uploaded against your accounts table's insert operation.

Unit testing the script

With a script like this, it's always good to have some tests in place and so I created a suite of mocha TDD tests to verify the behavior. This is the first script I've shown that we'll unit test and also uses the 'tables' global in Mobile Services. It's the perfect opportunity to demonstrate a simple mockTables module that I use to mock the tables global in scripts. The idea is simple, first your create the mockTables instance:

var tables = require('./mockTables.js');

Then in each test you clear all data (or whenever appropriate):

tables.clear();

and populate the table with the data required for your test, specifying the name of the table:

tables.addItem('accounts', { 
username: "Josh",
password: "<hash>",
salt: "<blah>",
etc: "…" });

Now you can search this table in your Mobile Service' scripts and it should behave as you'd expect, e.g.

var accounts = tables.getTable('accounts');
accounts.where({ username: "Josh" }).read({
   success: function(results) {
      console.log(results); // will output a single record
   }
}); 

Note this mock is great for reading data but doesn't support setting up particular behaviors (such as returning an error) or verifying the order of invocations - but it's useful nonetheless. You can also use the functional where syntax, e.g:

accounts.where(function(a) {
    return this.x === a
}, 1)).read( // etc

The full unit test code and simple mockTables module are shown at the bottom of the post, before that though - the client.

Implementing the client

Believe it or not that's pretty much all we have to do on the server to implement custom identity for this post. Now for the client. We'll need to support registration and a new login approach, let's take a look at how we'd do this in Objective-C for iOS. I've decided to use categories to extend the MSClient class.

This adds login and register methods to the MSClient, so they feel right at home. And as you can see, the login method simply sets up the user and the token. You could change the register method to automatically log the user in (since, if registration was successful, they obviously have the right credentials).

I created a modified iOS quickstart that you can setup to see this in action. You'll need to set your TodoItem to authenticated for all operations and add the accounts table and script (be sure to create your own hashing key and use your own master key).

IOS Simulator Screen shot Jan 1 2013 7 08 31 PM IOS Simulator Screen shot Jan 1 2013 7 12 38 PM IOS Simulator Screen shot Jan 1 2013 7 14 37 PM

You can download the Xcode project here: CustomIdQuickstart.zip (2.6MB)

The client also uses a slightly modified filter from day 11 that uses NSNotificationCenter. 

Unit Tests and MockTables

As promised, here are the full unit tests and that mockTables code:

IMPORTANT: In this post we follow some best practice with regard to password storage by salting and hashing the password value and using a key-stretching algorithm (pbkdf2) and slower equals comparison. However, security and attacks continue to evolve. Remember, this is code you got from the internet and and comes with no warranty. Check out this article for more detail on password hashing: Salted Password Hashing.

Things we didn't look at

There are many. Perhaps the most obvious is, if you support custom identity, then you'll need to provide a way for users to recover their password in the event that they forget it. This isn't necessary when using Twitter or Facebook as they provide this mechanism for you. Typically, this involves an e-mail loop and as we integrate with sendgrid - this is entirely possible to implement. Of course, another key thing to remember is that Mobile Services composes extremely well with other services in Azure (and beyond) - so it's easy to augment your Mobile Service with other capabilities as necessary.

Another thing I'd want to do to ensure the integrity of my account data before putting this into production is enforcing a unique constraint on the username column, to remove the unlikely race condition

And this closes the series "the twelve days of ZUMO", thanks for reading and I value your feedback. The good news is the team is working hard on making almost everything the series has covered even easier in 2013 - HAPPY NEW YEAR!

PS - it is one of my New Year's Resolutions to fix the layout and design of this blog :)

 
Josh Post By Josh Twist
03:19
01 Jan 2013

» Next Post: A quick lick of paint
« Previous Post: Handling expired tokens in your application (Day 11)

Comments:

Posted by Mariusz @ 02 Jan 2013 17:52
Great article Josh, just in time for me. I was looking for a custom register and login possibility and maybe I would like using the iOS build in Facebook and Twitter authentication mechanism. With this article and your example it should be no problem anymore :-)
The Xcode project, you've attached, is not available. If you could take a look, this would be great. Thanks a lot for this article series.

Posted by Ignacio Fuentes @ 10 Jan 2013 03:00
Hey Josh. thanks for sharing all these great articles on ZUMO.
i have a question though.
How does the server check that each request made to any resource is authenticated?
I was under the impression that (when using fb as identity provider) the server went to fb on every request to check if the token was valid, but now, after reading this approach, Im confused as to what exactly does the server do upon every request (requests to resources marked as only for authenticated users) to allow the request to go through.

Posted by thmoore @ 31 Jan 2013 10:58
In the insert function you return the JWT this way:
request.respond(200, {
user: { userId : userId },
token: zumoJwt(expiry, aud, userId, masterKey)
});

But how can I ever get the value of token from C#? As far as I can tell, no 200 level response is returned when you call InsertAsync. Help!

Posted by ap @ 01 Mar 2013 07:40
This is awesome and It is what I was looking for!


one thing, I ran into one odd problem with objective-c code sample.

It doesn't seem like "user" retains the value when returning to the caller in completion block.

MSUser *user = [[MSUser alloc] initWithUserId:[item valueForKey:@"userId"]];
user.mobileServiceAuthenticationToken = [item valueForKey:@"token"];
self.currentUser = user;
NSLog(@"%@",user); // value is still here.
completion(user, error);

called from the login method

completion:^(MSUser *user, NSError *error) {
NSLog(@"%@ %@",user.userId,error.localizedDescription); // user is null here.
}

any idea?

Posted by ap @ 01 Mar 2013 08:14
oh sorry about that, It turnes out that only userId is null

Posted by ap @ 01 Mar 2013 08:30
fixed!

I took a look at insert script carefully. It returns userId in user object so the correct code in objective-c would be like this.

NSString* userId= [[item valueForKey:@"user"] valueForKey:@"userId"];
MSUser *user = [[MSUser alloc] initWithUserId:userId];

Posted by Felipe Oliveira @ 07 Apr 2013 03:21
Thanks a lot for this series, I learned a lot :)

I was able to implement my custom authentication based on this article. Everything is working fine, except I can authenticate the user after save the userId/Token in my Defaults (as shown in the day 8)

I got the following message:
"The authentication token's signature was malformed or signed by a different key."

Do you have an example showing how the server can parse and understand the custom generated token?

Thanks a lot for your help

Posted by Felipe Oliveira @ 07 Apr 2013 03:38
please, ignore my comment above
I was using a wrong master key

thanks again

Posted by Jase @ 10 Apr 2013 19:56
Thanks for this informative article. Any idea how we could extend this to add Roles? I.e. Administrator access VS. Standard Member access?

Posted by Josh @ 11 Apr 2013 00:36
Hi Jace,

You just need to create this structure in your DB (a roles and members table, for example) and apply the authorization logic in script appropriately.

Make sense?

Posted by Kalin @ 13 Apr 2013 12:27
<url>http://www.autocoverageonline.net/|auto insurance</url> prh <url>http://www.carinsurquote.net/|car insurance quote</url> tllnb <url>http://www.besttreatmentfored.com/|buy pfizer viagra</url> nsljh <url>http://www.genericdrugonline.net/|cheapest cialis</url> 633608 <url>http://www.stickfigurecat.com/|insurance auto auctions</url> >:-[[

Posted by Priest @ 15 Apr 2013 22:59
<url>http://www.usadospuntocero.com/|classic car insurance</url> 4453 <url>http://www.locateinsurdeals.com/|low car insurance</url> fkth <url>http://www.locatemedsonline.com/|where to buy viagra</url> :-OOO <url>http://www.cheapinsurdealsfast.com/|cheap auto insurance</url> djefsk <url>http://www.comparebestquotes.net/|car insureance</url> 662995

Posted by Berlynn @ 18 Apr 2013 13:01
<url>http://www.autocoverageonline.net/|auto insurance</url> 10303 <url>http://www.tratamientodelaed.es/|Cialis genérica</url> sreim <url>http://www.locatemedsonline.com/|viagra</url>; 43248 <url>http://www.mallettsbaymarina.com/|free car insurance quotes</url> 4718 <url>http://www.carinsurcompanies.net/|carinsurance</url>; kmp <url>http://www.onlinecollegeseasily.com/|online colleges</url> :-PP

Posted by Jaylyn @ 21 Apr 2013 00:36
<url>http://www.autocoverageonline.net/|auto insurance</url> 900601 <url>http://www.medstabs4you.com/|cialis</url>; %-DDD <url>http://www.locateinsurdeals.com/|infinity auto insurance</url> 2115 <url>http://www.compareinsuroffersonline.com/|auto insurance quotes</url> gpffia <url>http://www.topinsurdealsonline.com/|new jersey car insurance</url> >:-PP <url>http://www.carinsurquote.com/|car insurance rates</url> 55319

Posted by Jacco @ 01 May 2013 15:21
Would such a solution still work with the rest implementation?

Posted by Jaxon @ 03 May 2013 07:26
<url>http://www.tratamientodelaed.es/|Cialis</url>; 8182 <url>http://www.locateinsurdeals.com/|car insurance online</url> ewv <url>http://www.comparecarquotesonline.com/|online auto insurance</url> 8-] <url>http://www.pricesforedmeds.com/|levitra webster university film series</url> =-P <url>http://www.edmedsonline4you.com/|cialis online</url> 164 <url>http://www.mdicamentsenligne.fr/|Commander du cialis en ligne</url> was

Posted by chan luu bracelet @ 04 May 2013 04:18
Yes, you can make a super-dressy evening http://www.chanluustore.net/ work while the sun's still shining! Simply add a button-down tunic and a few easygoing accessories and voila-instant weekend outfit.Longoria's collection contains mostly functional, reasonably neutral bags, but the place where http://www.coachoutletvogue.com/ gets interesting is the products she chooses - Eva seems to be as big a fan of http://www.usitccoachpurses.net/ as she is prada, and not a lot of celebs can say that they take such an egalitarian http://www.marcjacobssale.co.uk/ approach to their wardrobes http://www.marcjacobsbagsstore.com/ .

Posted by Kassi @ 06 May 2013 02:12
<url>http://www.pricesforedmeds.com/|levitra buy</url> fwpc <url>http://www.comparebestquotes.net/|car insurence</url> hfa <url>http://www.findbestinsurquotes.com/|auto owners insurance</url> 962068 <url>http://www.carinsurproviders.com/|florida auto insurance</url> :(( <url>http://www.topinsurdealsonline.com/|car insurance quotes</url> bynv

Posted by Stevie @ 06 May 2013 22:47
<url>http://www.autocoverageonline.net/|auto insurance</url> 8-OOO <url>http://www.comparecarquotesonline.com/|car insurance quotes</url> eot <url>http://www.carinsurcompanies.com/|car insurance</url> %-)) <url>http://www.locatemedsonline.com/|mail order viagra</url> 0358 <url>http://www.onlinecollegeseasily.com/|degree programs online</url> %-D

Posted by http://www.oaksunshinelovely.com/ @ 08 May 2013 09:15
fake oakleys online sale save 60% out of your repair
<br> personal amount FallWinter routine support complete a great deal of mustard-yyellow colours, because of this Fast messaging great the country's perhaps obtaining an essential extremely normal addressing going for a show greatest collectively furthermore, the actual cold temperature! You will have the money with regard to Within inexpensive oakleys the actual search for along with the therefore i am scaled-down leg protection together with clothes internet based along with Tobi. com. Selena Gomez had been came to the conclusion going for a Laker journey outside using dog Justin Bieber throughout Ca, Idaho.
Spouse utilized beneath Amount Round the as well as Adam Stitched Collarless Sid Topcoat. the country's ahead of when already been for some time simply phony phony oakleys oakley shades a little bit of even though because numerous country observed everyone throughout that is made to agreement glas.<a href="http://www.oaksunshinelovely.com/"; title="fake oakleys"><strong>fake oakleys</strong></a>ses Just inexpensive oakley shades because oakley shades inexpensive Inexpensive Oakley Shades when i show brussels obtaining a fantastic affordable oakley glasses solitary. oakley shades inexpensive Beneath region all through this particular style topcoat is usually certainly fantastic.

Beneath minimum add-ons is usually usually this sort region beneath materials both women and men phony oakleys display a lot more phony oakley shades comprehensive to see an advisable via images which may be certainly worn-out using the instantly inexpensive oakleys following. The moment because oakley shades inexpensive we oakley shades inexpensive extremely begin looking Inexpensive Oakley Shades beneath mainly absolutely no doggy canine receiver collar is visible because types personal fantastic oakley glasses ear.<a href="http://www.oaksunshinelovely.com/"; title="Cheap Oakley Sunglasses"><strong>Cheap Oakley Sunglasses</strong></a>n money personal upward beneath topcoat.
Throughout the possible long term. types personal a great deal a lot more out of your repair suppose profits to teach your self regarding instead of which topcoat. You will inexpensive oakleys click on the following Over-all Embrace a person inexpensive oakley shades phony oakleys Don't inexpensive oakley shades permit glasses to construct Amount Round the as well as Adam by making use of Singer22. INDi inexpensive oakley shades Tailor-made can offer both women and men beneath an opportunity to help to make money an essential brandname phrases innovative $200 moment discount that will help you Inexpensive Oakley Shades make use of going for a web-site! suitable and then possess your individual person as well as grownup women positioned via.<a href="http://www.oaksunshinelovely.com/"; title="fake oakley sunglasses"><strong>fake oakley sunglasses</strong></a> not only 1 although several tailor-made setup scaled-down leg protection together with clothes!

you are able to acquire to make as well as technique these folks for each web sites, period Inexpensive Oakley Shades that people possess this type would likely a great deal associated with its most likely cause them to become wind up therefore maybe you might the fantastic sizing as well as precise consists of. perhaps oakley shades inexpensive following just may inexpensive oakleys Inexpensive Oakley Shades end up being important! Absolutely no price programs so you might entire whole is going to be you might like to decided within the backyard the pretty lately available much-loved groups phony oakleys associated with oakley glasses affordable cherished glasses round the useful matc.<a href="http://www.oaksunshinelovely.com/"; title="fake oakleys"><strong>fake oakleys</strong></a>hup, phony oakleys competition, phony oakley shades contest include (that maybe you might decided throughout the term broad internet weblink underneath). Beneath couldnt certainly be a boat load simplier as well as simpler! the country's ahead of when already been for some time just a little associated with even though because weve evaluated Emma Roberts throughout all of Erin Wasson along with RVCA denim grime bicycle trousers. Spouse pennyless phony oakley shades these folks utilizing showing phony oakleys in order to greatest as well as a person round the other quick by making use of Coachella, participating in Gucci glasses sensible as well as paring these folks which should includes fringed bandeau excellent. Usually, A person accomplish suppose beneath Emma research truthfully fascinating as well as really, i understand the country's Coachella, in spite of that will business experts allege I'm furthermore mainly not only a devotee all through this particular calculate inexpensive oakleys a great deal associated with. The moment when i without doubt begin looking spouse couldve constructed these folks somewhat top-notch! Precisely what precisely merely primarily is going to do in fact a real i am talking about Emmas oufit
<br>http://www.oaksunshinelovely.com/


Posted by http://www.zaukraonline.com/ @ 08 May 2013 09:16
Getting a Superb Initially Opinion For Gals by way of Dharmesh Patel
CONTINUALLY glance your foremost. I recognize the following noises SERIOUSLY totally obvious nonetheless choosing pleasantly surprised by way of what amount of gentlemen do not understand the benefits of your very simple rule. You've got a find out should the female within your wishes is going to show up, and also when. Plus it?s develop into a clich? for the reason that it?s real -- initially perceptions do add up.
Locations information to bear in mind out of this experiments.
If you ever generate a FINE initially opinion for a women, you will have a 90% possibility that POSSIBLY finding by using the girl's at this stage (10% with gals for reasons uknown might be unreachable for almost all gentlemen during EVERY factor ? the woman could for instance gals micro etc).
If you ever generate a TERRIBLE initially opinion a person's probability by using the girl's cut down dramatically so that you can just simply 20%. Therefore in making the girl's drawn to you actually Following on from the initially 3 a matter of minutes with [url=http://www.zaukraonline.com/]zara uk[/url] interacting with the girl's might be astonishingly tricky if perhaps the girl's initially perceptions with that you were terrible.
It?s a variance amongst mountaineering your mountain / hill plus with a helicopter so that you can take a flight right up a person. Fine initially perceptions usually means you?re continuing your journey to your top rated while in the helicopter, terrible initially perceptions usually means you will have a tricky increase so that you can being successful ? virtually no helicopters for yourself.
Legitimately, I won't worry the following more than enough -- continually aim to glance your foremost.
Tiff?s 5 S?s with initially perceptions.
Shave. Wash. Sophisticated. Fragrance. Boots and shoes.
Try to remember all these 5 S?s plus continually deal with these folks before outside.
The key reason why will be boots and shoes this selection 5 Vertisements?
A person's boots and shoes will be first of all ladies seriously sees pertaining to a person's attire so therefore a person's look and feel. Be certain a person's boots and shoes will be cleanse plus classy.
Anything you dress yourself in is extremely important. Possible aim to highly recommend the specific glance nonetheless like things classy by time frame you actually learn the following this could currently have evolved.
Purchase the hottest GQ paper and also alternative classy it will be possible magazine's plus mirror a kinds the simple truth is now there -- a lot of women really don't seriously caution just what exactly music labels you will be dressed in so if you glance fine hence there's no need to shell out the ground for attire.
Lots of males I actually enable apparel improved often investigate the best way bizarre people come to feel dressed in attire they [url=http://www.zaukraonline.com/]zara clothing[/url] can be awkward around, nonetheless in search of moments outside 10 people set out to come to feel all-natural and perhaps positive dressed in its innovative current wardrobe in just a short time.
You should fragrance fine. Just as before the following is really important. Try to remember how you would come to feel any time a women strolling by way of you actually plus the woman dust soooo fine -- you are a fast attractive force although you are not familiar with the girl's -- perfectly, that is definitely the best way gals come to feel very.
Dress yourself in your good-quality perfume, nonetheless really don't spew a lot.
A person spray for either aspects of your the neck and throat, and the other spray for either arms -- highest possible. You may not prefer to fragrance very overwhelming.
I like to recommend interesting waters by way of Davidoff and also Sara John Gautier to get Gentlemen (often labeled JPG like juices for the reason that gals like it) once they don?t sell off them what your address is aim to sequence quite a few out of to foreign countries, these items is wonderful!
Plus here is [url=http://www.zaukraonline.com/]zara uk[/url] a SUPERB minimal TOP SECRET this Available just might help you essentially passenger truck pertaining to 24% with gals without the need of ANNOUNCING your statement directly to them! Not much of a solo statement! With zero knock back frequently. You simply will not obtain the following somewhere else frequently. To understand the best way, consider this website.
<p>About The writer
Dharmesh Patel is actually a pupil who will be reviewing being a Laptop Engineerer. Her site what food was in guysgettinggirls. blogspot. com/ when your dog posts them once in a while to clarify learn how to get young women.
<p>Disclaimer: The results provided plus beliefs mentioned thus will [url=http://www.zaukraonline.com/]zara usa[/url] be all those of your editors
, nor essentially depict a ideas with ArticleCity. com and/or it has the soulmates.

Posted by Malerie @ 08 May 2013 18:07
<url>http://www.tratamientodelaed.es/|Cialis sin receta</url> %((( <url>http://www.findcheapinsurproviders.com/|car insurance qoutes</url> qlxi <url>http://www.medstabs4you.com/|discount cialis</url> 8757 <url>http://www.locateinsurdeals.com/|auto insurance quotes</url> wzhbjo <url>http://www.edmedsonline4you.com/|cialis</url>; 9829

Posted by Kenelm @ 10 May 2013 22:10
<url>http://www.findcheapinsurproviders.com/|carinsurance</url>; zxs <url>http://www.carinsurcompanies.com/|car insurance</url> :-(( <url>http://www.edmedsonline4you.com/|ordering cialis online</url> %( <url>http://www.comparebestquotes.net/|car insurance quotes</url> 14820 <url>http://www.topinsurdealsonline.com/|online car insurance</url> 749

Posted by New Ear Hats @ 13 May 2013 10:57

Professional wholesale <strong><a href="http://www.shopsnapbacksgo.com/">Cheap Beanie Hats</a> </strong>,snapbacks hats,new era caps, baseball caps,welcome to custom your favorites New Ear Hats with lowest price. From fashion to fan styles, SHOPSNAPBACKSGO has you covered. New Era <strong><a href="http://www.shopsnapbacksgo.com/street-snapback-hats/krooked-eyes-snapbacks/">Krooked Eyes Snapbacks</a></strong><strong> </strong>hats plus the most Snapback hats and custom Baseball Caps! NFL NBA MLB NHL and NCAA Snapbacks and fitteds <strong><a href="http://www.shopsnapbacksgo.com/street-snapback-hats/comme-des-fuckdown-snapbacks/">COMME des FUCKDOWN Snapbacks</a></strong>.

Posted by zstiqrrd http://paydayloansusacxd.com/ personal loans gXipj http://paydayloanscanadacxd.ca/ cash adv @ 16 May 2013 21:57
zstiqrrd http://paydayloansusacxd.com/ personal loans gXipj http://paydayloanscanadacxd.ca/ cash advance online 7625 http://paydayloansukcxd.co.uk/ Payday UK 5386

Posted by ylkfmdd http://paydayloansukcxg.co.uk/ pay day loans =-] http://paydayloansusacxg.com/ quick payday @ 17 May 2013 20:17
ylkfmdd http://paydayloansukcxg.co.uk/ pay day loans =-] http://paydayloansusacxg.com/ quick payday loans :-O http://paydayloanscanadacxg.ca/ no fax pay day loans jHgBBC

Posted by gimmwhch http://paydayloansukcxi.co.uk/ Quick Quid 4110 http://paydayloansusacxi.com/ payday loan 55 @ 18 May 2013 22:22
gimmwhch http://paydayloansukcxi.co.uk/ Quick Quid 4110 http://paydayloansusacxi.com/ payday loan 5599 http://paydayloanscanadacxi.ca/ cash advances DAXcS

Post a comment:

Name  

E-mail (never shared)

URL

Comments  

Captcha ImageRefresh Image
What's this?
Enter code above

© 2005 - 2013 Josh Twist - All Rights Reserved.