Sunday, September 15, 2013

OAuth continued

I ran into another small problem: I was trying to do a POST request to get access to the API using the access token. This is a GET. I wasted about an hour.

After you get everything back, I needed to have everything stored into my application.
My question was how to redirect the user to the appropriate location.

Here's how you do it

Usually, the method that receives the Rest call says
@Produces("application/xml")
or
@Produces("application/pdf")
@Produces("text/plain")

turns out, you can do 
@Produces("text/html")
(for more on producible MIME types, see this)

Then, when your response is served to the client, it tells the browser to interpret it as an html. This is pretty neat! You can include a script tag inside the response and do a location.href = '/location_here'

I realized that this is just like saving the file with a .html extension. Neat!
So, we get a little lesson about how browsers read files.

That's about it! Everything seems pretty clear to me now. It's just a bunch of mop up work.

Google OAuth 2

Well, this is the thing I've been trying to avoid for awhile.
I finally got it figured out (mostly)

I've found that the documentation is really annoying, since it's trying to sell you the APIs when you're just looking for simple authentication and authorization. (Incidentally, I'm only using OAuth for authentication, and I'm authorizing on my own). The pages are each written nicely, but the links are a mess.

I've found the following two links to be most useful:
Overview
Playground

Of course, Google also gives you some "help" by providing example java clients (or your preferred fill in the blank back end service)

Turns out the first step to getting the access code is stupid. You just put a link with the right queryparams and Google pulls through that part for you, giving you the auth code as a get query parameter in the redirect uri. The next part was the annoying part for me.

Since I have a restful web service, I needed to do another post request with the auth code that Google gave me and send my client id and secret back to Google. I bootlegged a vanilla java post request thing from the web and muscled through it. It uses HttpsUrlRequest or something.

Be sure that your parameters are correct here, Google likes to throw 400s when you misbehave.
Two examples:

  1. you try to post twice. It'll only work if you get it right on the first try. If you mess up, you have to re-authorize.
  2. if you mess up the redirect uri. I'm dumb.
Finally, you get the access_token.

You do another call with that to get the info. This call is easy (finally).

You celebrate, as you've gotten the info from Google that you need. Now everything is handed back to your application.

More to come! As I figure the rest out.