[SalesForce] How to authenticate a JavaScript (e.g. AngularJS) client of an Apex @RestResource

I am working on an AngularJS mobile application that obtains its data from salesforce.com using REST calls to @RestResource Apex classes. (There are no conventional Visualforce/Apex controller pages.) This works fine when the Apex classes are exposed in an unauthenticated manner through a site.

However, the intention is that users (customers) will be able to self-register and that their access will be secured through the User created via Site.createPortalUser. Some testing and Googling suggests that the corresponding Site.login has no affect when invoked from a @RestResource class.

An alternate approach appears to be to make use of the Username-Password OAuth Authentication Flow and I am encouraged about using this for sites by this
OAuth for Portal Users blog. But the first link says that the security token must be appended to the password and I don't see how this token can be obtained for a portal user. And if it could it would be very hard for the user to enter. (That difficulty would seem to make it inappropriate for any type of interactive user.)

Has anyone solved this problem of providing username/password (without security token) authentication for users from JavaScript clients of @RestResource services?

Best Answer

The dev guide getting started section has some info about authenticating to a community.

You would link the user to the auth provider URL (see the proceeding page about setting that up) but use the community domain instead. If the example, Customers is the name of the community (that took me a second).

The user is redirected to the community login page (you can brand that).

Then have the oauth callback URL be normalpath/success, which lets you scrape the URL after # for a session Id AND a refresh token that you can use to get session IDs later.

If you had a portal, you probably got a free community when that came out that you can use, just making the customer portal profiles members of that community.

If you do use the username password flow (haven't tried it for a portal) then you can't get refresh tokens and user will have to do it every time.

Related Topic