Pain-free OAuth with AppEngine

meme-5828337892065280

I do a lot of side projects (or at least start them) and implementing authentication is always like chewing on razor blades. I started another project recently using AppEngine and, bracing myself with a lot of caffeine and “suck it up, princess” attitude, I started doing “oauth appengine” searches.

After digging through some documentation, I realized that AppEngine actually does OAuth right. All you have to do is add the following to your src/main/webapp/WEB-INF/web.xml file:

    <security-constraint>
        <web-resource-collection>
           <web-resource-name>my-thing</web-resource-name>
           <url-pattern>/members-only/*</url-pattern>
        </web-resource-collection>
        <auth-constraint>
           <role-name>*</role-name>
        </auth-constraint>
    </security-constraint>

The <url-pattern>/members-only/*</url-pattern> means that when someone goes to any page under members-only/, they’ll have to go through the “login with Google” flow.

On the server side, there’s no annoying URL encodings to get right or tokens to keep track of. You can just access the logged-in person’s username, e.g., in Java:

public class DemoServlet extends HttpServlet {
    @Override
    public void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws IOException {
    	String account = req.getUserPrincipal().getName();
 
        ...
    }
}

That’s it! This is such a killer feature to me, I can’t believe I never knew about about it before.

(One other thing that I can’t believe I never knew about is SimpleHTTPServer. python -m SimpleHTTPServer will serve static files from the current directory. I’m pretty sure everyone already knows about this, but just in case there’s someone else out there…)

kristina chodorow's blog