Quantcast
Channel: Blog – Stormpath User Identity API
Viewing all 278 articles
Browse latest View live

Build a Java Web App with Instant User Management

$
0
0

Java SDK w/ Servlet Support

We just released a major upgrade of our Java SDK, which now includes Java Webapp (Servlet 3.0+) support with a ton of user automation. Just drop our Servlet plugin into your Java web application and boom – instant user management with little to no coding required.

This post is a quick tutorial to show you just how quickly you can build a Java web app with a complete set authentication and user management features and user interfaces.

If you’ve built a Java web application, you know the time and pain involved in building out proper authentication and user management. Even if you use a great framework like Apache Shiro or Spring Security, there’s still a lot of boring UI work and high risk backend work.
At a minimum, you have to build UI screens for registration, login, and forgot password in addition to controllers processing each view, logout handlers, etc. And then you have to worry about security issues like password hashing schemes, updating hashing algorithms as computation improves, CSRF protection, XSS attacks, and more.

Stormpath hooks into typical Java web applications and gives developers all that “user stuff” out-of-the-box so you can get on with what you really care about – your application. In fact, you get full user interfaces without writing a single line of code. Awesome.

By the time you’re done with this 15 minute tutorial you’ll have a fully-working Java web application. We will focus on our Stormpath-Servlet plugin that has a ton of user automation. You just drop a plugin into your web application and boom – instant user management with little to no coding required.

What You’ll Build

You’ll build a simple Java web application using the standard Servlet 3+ and JSP APIs. When you’re done, you’ll be able to:

  • Create a new user account with email and password
  • Validate the new user account’s registered email address
  • Login to your new account with email and password
  • Display a user account dashboard after login, only accessible to logged-in users.
  • Redirect unauthenticated users who try to access the dashboard to the login page.
  • Allow a logged-in user to logout.
  • Allow a user to reset their password via an email-based workflow.

And here’s the best part – for all of the above, you won’t have to write a single line of code – just some configuration!

But, just for fun, we will code a simple welcome page and a user account dashboard page that are likely to exist in real applications.

Sound good? Great! Let’s get started!

What You’ll Need

  • About 15 minutes of time
  • A Stormpath API Key to communicate with Stormpath
  • JDK 1.6 or later
  • Maven 3.0+ or Gradle 2.2+

How to Complete this Guide

You can start from scratch and complete each step or you can skip the basic setup steps you’re already familiar with.

Start From Scratch

If you’d like to start from scratch, you’ll need to first get a Stormpath API Key.

Then you’ll need to Build With Maven or Build With Gradle, depending on your preferences.

Get an API Key

All communication with Stormpath must be authenticated with an API Key.

  1. If you haven’t already, sign up for Stormpath for free. You’ll be sent a verification email.

  2. Click the link in the verification email.

  3. Log in to the Stormpath Admin Console using the email address and password you used during registration.

  4. Click the Manage API Keys link on the middle-right of the dashboard.

  5. Under Security Credentials, click Create API Key.

    This will generate your API Key and download it to your computer as an apiKey.properties file.

  6. Save the file in your home directory in the following location:

    • ~/.stormpath/apiKey.properties on Unix, Linux and Mac OS
    • C:\Users\YOUR_USERNAME\.stormpath\apiKey.properties on Windows
  7. Change the file permissions to ensure only you can read this file. For example:

     chmod go-rwx ~/.stormpath/apiKey.properties
    
  8. To be safe, you might also want to prevent yourself from accidentally writing/modifying the file:

     chmod u-w ~/.stormpath/apiKey.properties
    

On Windows, you can set file permissions similarly.

Build With Maven

Choose a directory that you wish to use for your project. Within that directory, create the following maven pom.xml file:

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.stormpath.samples</groupId>
    <artifactId>stormpath-webapp-tutorial</artifactId>
    <version>0.1.0</version>
    <packaging>war</packaging>

    <dependencies>
        <dependency>
            <groupId>com.stormpath.sdk</groupId>
            <artifactId>stormpath-servlet-plugin</artifactId>
            <version>1.0.RC3.1</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.0.1</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>
        <dependency>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-classic</artifactId>
            <version>1.0.13</version>
            <scope>runtime</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.tomcat.maven</groupId>
                <artifactId>tomcat7-maven-plugin</artifactId>
                <version>2.2</version>
                <configuration>
                    <path>/</path>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>

Build With Gradle

Choose a directory that you wish to use for your project. Within that directory, create the following build.gradle file:

build.gradle

buildscript {
    repositories {
        jcenter()
    }

    dependencies {
        classpath 'com.bmuschko:gradle-tomcat-plugin:2.0'
    }
}

apply plugin: 'java'
apply plugin: 'war'
apply plugin: 'com.bmuschko.tomcat'

sourceCompatibility = 1.6
version = '0.1.0'
war.baseName = 'stormpath-webapp-tutorial'

repositories {
    mavenLocal()
    mavenCentral()
}

dependencies {
    compile group: 'com.stormpath.sdk', name: 'stormpath-servlet-plugin', version: '1.0.RC3.1'
    compile group: 'javax.servlet', name: 'jstl', version: '1.2'
    providedCompile group: 'javax.servlet', name: 'javax.servlet-api', version: '3.0.1'
    runtime group: 'ch.qos.logback', name: 'logback-classic', version: '1.0.13'

    def tomcatVersion = '7.0.57'
    tomcat "org.apache.tomcat.embed:tomcat-embed-core:${tomcatVersion}",
            "org.apache.tomcat.embed:tomcat-embed-logging-juli:${tomcatVersion}"
    tomcat("org.apache.tomcat.embed:tomcat-embed-jasper:${tomcatVersion}") {
        exclude group: 'org.eclipse.jdt.core.compiler', module: 'ecj'
    }
}

tomcatRun.contextPath = '/'
tomcatRunWar.contextPath = '/'

task wrapper(type: Wrapper) {
    gradleVersion = '2.2.1'
}

Skip The Basics

Add the dependency to your web app (.war) project:

Maven:

<dependency>
    <groupId>com.stormpath.sdk</groupId>
    <artifactId>stormpath-servlet-plugin</artifactId>
    <version>1.0.RC3.1</version>
</dependency>

Gradle:

dependencies {
  compile 'com.stormpath.sdk:stormpath-servlet-plugin:1.0.RC3.1'
}

Build the App

We’ll need to create some files in various directories. Ensure the following directory structure exists under your project directory:

-- src/
 |-- main/
   |-- java/
   |   |-- tutorial/
   |-- webapp
     |-- WEB-INF/
       |-- jsp/
       |-- tags/

For example, on *nix operating systems:

mkdir -p src/main/java/tutorial
mkdir -p src/main/webapp/WEB-INF/jsp
mkdir -p src/main/webapp/WEB-INF/tags

Page Template

We’ll likely want our web app’s pages to have the same look and feel. We can do this easily using a page template. And because JSP 2.0 supports page templates automatically via JSP Tags, there is no need to pull in additional template libraries. Let’s create a new template tag file with the following contents:

src/main/webapp/WEB-INF/tags/page.tag

<%@tag description="Default Page template" pageEncoding="UTF-8"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
<%@attribute name="title" required="false" %>

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Stormpath Webapp Sample | <c:out value="${!empty title ? title : ''}"/></title>
    <link href="https://stormpath.com//maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css" rel="stylesheet">
    <%-- <link href="${pageContext.request.contextPath}/assets/css/style.css" rel="stylesheet" --%>
    <!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
    <!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
    <!--[if lt IE 9]>
    <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
    <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
    <![endif]-->
    <!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
    <script src="https://stormpath.com//maxcdn.bootstrapcdn.com/bootstrap/3.3.2/js/bootstrap.min.js"></script>
</head>
<body>
    <div class="container">

        <div class="header">

            <ul class="nav nav-pills pull-right">
                <c:set var="uri" value="${requestScope['javax.servlet.forward.request_uri']}"/>
                <li<c:if test="${fn:endsWith(uri,'/')}"> class="active"</c:if>><a href="${pageContext.request.contextPath}/">Home</a></li>

                <%-- Change upper right context menu depending on if the user is logged in or not: --%>
                <c:choose>
                    <c:when test="${!empty account}">
                        <li<c:if test="${fn:endsWith(uri,'dashboard')}"> class="active"</c:if>><a href="${pageContext.request.contextPath}/dashboard">Dashboard</a></li>
                        <li><a href="${pageContext.request.contextPath}/logout">Logout</a></li>
                    </c:when>
                    <c:otherwise>
                        <li<c:if test="${fn:endsWith(uri,'login')}"> class="active"</c:if>><a href="${pageContext.request.contextPath}/login">Login</a></li>
                    </c:otherwise>
                </c:choose>
            </ul>

            <h3 class="text-muted">Stormpath Webapp Sample</h3>

        </div>

        <jsp:doBody/>

    </div>
</body>
</html>

This is just a standard JSP file with a .tag extension instead of a .jsp extension. The <jsp:doBody/> element will be replaced with the page content for any page that uses this template.

Home Page

For security reasons, we like to ensure that JSP files themselves are never directly accessible during a request. Instead, we want a Controller to process the request and then render the JSP to the request. To do this, we’ll create a simple ‘Home’ controller that renders the internal home.jsp page:

src/main/java/tutorial/HomeController.java:

package tutorial;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class HomeController extends HttpServlet {

    public static final String VIEW_TEMPLATE_PATH = "/WEB-INF/jsp/home.jsp";

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.getRequestDispatcher(VIEW_TEMPLATE_PATH).forward(req, resp);
    }
}

src/main/webapp/WEB-INF/jsp/home.jsp:

<%@ page session="false"%>
<%@ page contentType="text/html;charset=UTF-8" pageEncoding="UTF-8" %>
<%@ taglib prefix="t" tagdir="/WEB-INF/tags" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

<t:page>
    <jsp:attribute name="title">Welcome!</jsp:attribute>
    <jsp:body>
        <div class="jumbotron" id="welcome">

            <h1>Welcome to the Stormpath Webapp Sample Application!</h1>

            <p class="lead">
                <br/>
                <br/>
                Welcome to this <i>gloriously simple</i>
                <a href="https://docs.stormpath.com/java/servlet-plugin/">Stormpath Java Webapp</a> sample application!
                <ul>
                    <li>First, take a look through this very basic site.</li>
                    <li>Then, check out this project's source code
                        <a href="https://github.com/stormpath/stormpath-sdk-java/examples/servlet">on GitHub</a>.</li>
                    <li>Lastly, integrate Stormpath into your own sites!</li>
                </ul>
            </p>

            <br/>
            <br/>

            <h2>What This Sample App Demonstrates</h2>

            <br/>
            <br/>

            <p>This simple application demonstrates how easy it is to register, login, and securely authenticate
                users on your website using the Stormpath Servlet Plugin.</p>

            <p>Not a Stormpath user yet? <a href="https://stormpath.com">Go signup now!</a></p>

            <br/>
            <br/>

            <p class="bigbutton"><a class="bigbutton btn btn-lg btn-danger"
                                    href="${pageContext.request.contextPath}/register" role="button">Register</a></p>
        </div>
    </jsp:body>
</t:page>

Finally, we’ll need to add a web.xml file to tell the servlet container to invoke our Home Controller when the web app’s default path is accessed:

src/main/webapp/WEB-INF/web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.1"
         xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd">

    <servlet>
        <servlet-name>HomeController</servlet-name>
        <servlet-class>tutorial.HomeController</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>HomeController</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

    <servlet-mapping>
        <servlet-name>default</servlet-name>
        <url-pattern>/assets/*</url-pattern>
    </servlet-mapping>

</web-app>

Try it!

Can you believe that after adding a single home page, you’d have a functional web application with full user management capability?

Don’t believe me? Let’s try it!

Using your build tool of choice, let’s start up the web application. For example:

Maven:

maven tomcat7:run

Gradle:

gradle tomcatRun

Open up a browser and visit http://localhost:8080. You’ll see the home page we just created above:

Stormpath Java Webapp Sample Home Page Screenshot

Pretty cool! Now, to be honest, this isn’t wildly exciting. That is what is supposed to happen after all. But the awesome features – the part you have been waiting for – is all the automatic stuff. For example, the login page!

Login Page

Click the Login button at the top right of the page, or manually visit http://localhost:8080/login, and you’ll see this:

Stormpath Java Webapp Plugin Login Page Screenshot

That’s right! A login page with best practice CSRF-protection built right in, and you didn’t have to write a single line of it. Now that is awesome! You can customize which fields are displayed in which order, as well as the entire look and feel if you wanted, with full internationalization (i18n) capabilities. That’s out of scope for this article, but you can read about customizing views later if you wanted.

It doesn’t stop there of course – you get all sorts of goodies, like user account registration, email verification and forgot password automation, token authentication and much more!

New User Registration Page

Now you can’t login until you create a user account, so go ahead and click the ‘Create Account’ link or manually visit the http://localhost:8080/register page and you’ll see this:

Stormpath Java Webapp Plugin Register Page Screenshot

Go ahead and fill out and submit the form – you’ll be given a new user account that you can use to log in right away.

Email Verification

Now, what about email verification? Many web applications want to ensure that newly registered users must verify their email address before they can login to the application. This helps ensure that:

  • Email addresses cannot be abused by people that do not own them
  • The application has a way of communicating with the user if necessary
  • The registration process was completed by a human being (and not a ‘bot’ performing automatic registration, which could be used for malicious purposes).

This is covered too! You just have to enable email verification as described in the documentation. Since this is a shorter tutorial, we’ll move on, but feel free to turn that on if you like and try it out.

Logout

If you are still logged in, click the logout button on the upper right. This will visit /logout, which will automatically log you out and then redirect you back to the web app’s context root page (/) by default (you can customize this next URI later).

We’ll also make one more change to the web app, so go ahead and shut down the application by pressing CTRL-C.

Forgot Password, Change Password, etc.

The plugin supports other views out of the box as well, which you can read about in the documentation. But we want to show you one more thing before we wrap up this tutorial: access control.

Access Control

The Stormpath Java Webapp Plugin also has the ability to enforce access control based on URI path. For example, you can ensure that only authenticated users may visit the /account URI within your application. Or that maybe only accounts within the admin group can visit the /admin URI.

To demonstrate this, we’ll create a /dashboard view that only authenticated users should be able to see. This represents a common ‘landing page’ that a user might be shown immediately after login.

Let’s create a ‘Dashboard’ controller:

src/main/java/tutorial/DashboardController.java

package tutorial;

import com.stormpath.sdk.account.Account;
import com.stormpath.sdk.directory.CustomData;
import com.stormpath.sdk.lang.Strings;
import com.stormpath.sdk.servlet.account.AccountResolver;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class DashboardController extends HttpServlet {

    private static final String VIEW_TEMPLATE_PATH = "/WEB-INF/jsp/dashboard.jsp";

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        String birthday = "";
        String color = "";

        Account account = AccountResolver.INSTANCE.getAccount(req);
        if (account != null) {
            CustomData data = account.getCustomData();
            birthday = (String)data.get("birthday");
            color = (String)data.get("color");
        }

        req.setAttribute("birthday", birthday);
        req.setAttribute("color", color);
        req.getRequestDispatcher(VIEW_TEMPLATE_PATH).forward(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        String birthday = req.getParameter("birthday");
        String color = req.getParameter("color");

        //get the currently-logged-in account:
        Account account = AccountResolver.INSTANCE.getAccount(req);
        if (account != null) {

            CustomData data = account.getCustomData();

            if (Strings.hasText(birthday)) {
                data.put("birthday", birthday);
            } else {
                data.remove("birthday");
            }

            if (Strings.hasText(color)) {
                data.put("color", color);
            } else {
                data.remove("color");
            }

            data.save();
        }

        req.setAttribute("birthday", birthday);
        req.setAttribute("color", color);
        req.getRequestDispatcher(VIEW_TEMPLATE_PATH).forward(req, resp);
    }
}

The DashboardController demonstrates a really nice Stormpath feature: the ability to ‘attach’ your own custom data directly to Stormpath REST resources, such as a user account’s birthday or favorite color.

Let’s create the view file that will be rendered by the controller:

src/main/webapp/WEB-INF/jsp/dashboard.jsp

<%@ page session="false"%>
<%@ page contentType="text/html;charset=UTF-8" pageEncoding="UTF-8" %>
<%@ taglib prefix="t" tagdir="/WEB-INF/tags" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

<t:page>
    <jsp:attribute name="title">Dashboard</jsp:attribute>
    <jsp:body>
        <div class="dashboard">
            <div class="row">
                <div class="col-lg-12">
                    <div class="jumbotron">
                        <h1>Dashboard</h1>

                        <br/>
                        <br/>

                        <p>Welcome to your user dashboard!</p>

                        <p>This page displays some of your account information and also allows you to change custom
                            data.</p>

                        <p>If you click the Logout link in the navbar at the top of this page, you'll be logged out
                            of your account and redirected back to the main page of this site.</p>
                        <br/>
                        <br/>

                        <h2>Your Account Custom Data</h2>
                        <br/>
                        <br/>

                        <p>Your Email: <span class="data">${account.email}</span></p>

                        <c:set var="noBirthday" value="You haven't entered a birthday yet!"/>
                        <p>Your Birthday: <span class="data">${!empty account.customData['birthday'] ? account.customData['birthday'] : noBirthday}</span></p>

                        <c:set var="noColor" value="You haven't entered a color yet!"/>
                        <p>Your Favorite Color: <span class="data">${!empty account.customData['color'] ? account.customData['color'] : noColor}</span></p>

                        <br/>
                        <br/>

                        <p>Stormpath allows you to store up to 10MB of custom user data on
                            each user account. Data can be anything (in JSON format). The above
                            example shows two custom fields (<code>birthday</code> and
                            <code>color</code>), but you can add whatever fields you'd like.</p>

                        <p>You can also store complicated nested JSON documents!</p>
                        <br/>
                        <br/>

                        <h2>Update Custom Data</h2>
                        <br/>
                        <br/>

                        <p>If you enter values below, we'll send and store these
                            values with your user account on Stormpath.</p>

                        <p>Please note, we are not doing any validation in this simple
                            example -- in a real world scenario, you'd want to check user input on the server side!</p>
                        <br/>
                        <br/>

                        <form method="post" class="bs-example form-horizontal" action="${pageContext.request.contextPath}/dashboard">
                            <div class="form-group">
                                <label for="birthday" class="col-lg-2 control-label">Birthday</label>

                                <div class="col-lg-4">
                                    <input type="text" class="form-control" id="birthday" name="birthday" placeholder="mm/dd/yyyy"
                                           value="${!empty account.customData['birthday'] ? account.customData['birthday'] : ''}">
                                </div>
                            </div>
                            <div class="form-group">
                                <label for="color" class="col-lg-2 control-label">Favorite Color</label>
                                <div class="col-lg-4">
                                    <input type="text" class="form-control" id="color" name="color" placeholder="color"
                                           value="${!empty account.customData['color'] ? account.customData['color'] : ''}">
                                </div>
                            </div>
                            <div class="form-group">
                                <div class="col-lg-10 col-lg-offset-2">
                                    <button type="submit" class="btn btn-primary">Update Custom Data</button>
                                </div>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </jsp:body>
</t:page>

And we’ll need to update web.xml to tell the Servlet Container about our new view. web.xml should now look like this:

src/main/webapp/WEB-INF/web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.1"
         xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd">

    <servlet>
        <servlet-name>HomeController</servlet-name>
        <servlet-class>tutorial.HomeController</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>HomeController</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
    <servlet>
        <servlet-name>DashboardController</servlet-name>
        <servlet-class>tutorial.DashboardController</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>DashboardController</servlet-name>
        <url-pattern>/dashboard</url-pattern>
    </servlet-mapping>


    <servlet-mapping>
        <servlet-name>default</servlet-name>
        <url-pattern>/assets/*</url-pattern>
    </servlet-mapping>

</web-app>

Stormpath Config

Notice that, until now, we did not need to configure the plugin itself at all: everything ‘just works’. But now that we have some application-specific enforcement rules, we’ll need to tell the plugin what to do via a simple stormpath.properties configuration file. Let’s create this file:

src/main/webapp/WEB-INF/stormpath.properties

stormpath.web.login.nextUri = /dashboard

stormpath.web.uris./dashboard = authc
  • The first line means “After the user successfully logs in, I want the next URI they visit to be /dashboard”. The plugin’s login controller will automatically redirect the newly authenticated user to this location.

  • The second line means “in order for anyone to visit the /dashboard URI, they must be authenticated (‘authc’ is short for ‘authenticated’). This enforces all requests to be authenticated by a valid user account before being allowed to continue. If they are not, they will be redirected to the login page to login first, and then automatically be redirected back to their originally requested URI.

Try it!

Now that we’ve added a dashboard view and controller, and a simple stormpath.properties file, let’s try it out!

If you haven’t already, shut down the application by pressing CTRL-C.

Now start it up:

Maven:

maven tomcat7:run

Gradle:

gradle tomcatRun

Now try to visit http://localhost:8080/dashboard – you will be redirected to login as expected. Log in with a user account you created previously and then it will automatically redirect you back to the dashboard. Nice!

Stormpath Java Webapp Plugin Dashboard Page Screenshot

Summary

Congratulations! You now have a complete web application, with automatic user registration, login, forgot password/reset workflows, logout, custom data editing, and access control enforcement!

But we’ve just scratched the surface of what you can do. Also supported:

  • Full default view customization with internationalization (i18n) support.
  • Authorization assertions (based on account data, like username, which groups they belong to, etc)
  • Token Authentication for Javascript and mobile clients (we implemented OAuth for you)
  • HTTP Basic Authentication for both username/password and API Keys
  • Event listeners to react to login, logout, registration, etc events.
  • Caching for enhanced performance.
  • Convienent filter chain definitions for custom authentication or authorization rules.
  • Easy Stormpath SDK Client configuration and request access
  • and more!

Please see the complete Stormpath Java Servlet Plugin Documentation for full information.


Automatically Populate Intercom with User Data

$
0
0

Stormpath Intercom Integration

We work with a lot of Startups SaaS companies, and they consistently run into a few challenges when it comes to managing their growing customer base:

  • Its hard to know who your users are
  • Its not always clear how they interact with your product
  • For them to get the most value and have the best experience, they need meaningful communication from your company.

There are no two tools better suited to manage the overall experience of your customers than Stormpath and Intercom. A mutual customer recently brought us a challenge – can we make it easy for Stormpath to integrate to Intercom?

Our new syncing tool, stormpath-intercom makes it incredibly easy to integrate both into any Node.js or Express app. The integration will automatically populate your Intercom setup with user data from Stormpath.

Intercom: Smart Customer Communication

Intercom is a lightweight, slick CRM system that allows you to:

  • Store up-to-date information on your users via their simple REST API.
  • Automatically pull down a user’s avatar and company information.
  • Schedule emails to users when certain events happen (e.g. 3 days after signup).
  • Easily add user messaging and chat to your website so users can connect with you where they are/
  • And lots more.

At a previous company, we massively increased user conversion — as well as proactively solve support issues, by heavily leveraging Intercom’s user segmenting and emailing features:

  • Intercom fired off an email to new users, welcoming them to the platform, and giving them relevant links to get started.
  • Intercom sent another email after a user made their first API call to our service, thanking them and giving them more useful information.
  • We’d also have Intercom fire off another email depending on what user-agent they made API requests with, sending them language-specific help documentation, etc.

Overall, this greatly increased the number of happy users, reduced support cases, and improved the quality of our customer communication.

Intercom Customer Dashboard

Store User Data in Stormpath

Unfortunately, while Intercom is amazingly useful — it’s only useful if it’s got access to all of your user’s data!

Let’s say you want to email all users who have made requests to your API service using the Ruby programming language, for instance. This could be a really great way to target your users with context relevant information!

But — there’s no way to do this without first loading this data into Intercom.

This is where stormpath-intercom comes into play.

If you’re storing your user accounts and securing your web applications with Stormpath, our stormpath-intercom tool will automatically sync all of your Stormpath user data with Intercom.

You’ll always have an up-to-date Intercom database, complete with any custom data from Stormpath to assist in segmenting and interacting with your users.

How Stormpath-Intercom Works

Here’s how it works.

First, you need to have Node.js installed and working on your computer (or server).

Once that’s done, you’ll need to install the stormpath-intercom tool by running:

$ npm install -g stormpath-intercom

The above command will download and install our syncing tool.

Lastly, you need to run the tool (passing in your Stormpath and Intercom API keys) — this will initiate the synchronization for you. Here’s an example:

$ stormpath-intercom \
    --stormpath-api-key-id=xxx \
    --stormpath-api-key-secret=xxx \
    --stormpath-app-name=myapp \
    --intercom-app-id=xxx \
    --intercom-api-key=xxx

We recommend you run this tool every hour using a system like cron. This way, your Intercom database will be at most 1 hour behind.

Learn More

If you’re looking to build an incredibly awesome web company, and aren’t yet using either Intercom or Stormpath, you should get started right now!

Got any other questions? Feel free to email us! =)

Token Based Authentication for Single Page Apps (SPAs)

$
0
0

If you’re confused about token-based authentication: this post is for you. We will cover access tokens, how they differ from session cookies, and why they make sense for single page applications (SPAs). This article is primarily written for those with an SPA backed by a REST API.

We’ll pay special attention to best practices for handling JWTs and security: successful token authentication system requires you to know the security details and possible tradeoffs.

Thankfully, we’ve wrapped up all the best-practice decisions into some libraries you can use: Stormpath Angularjs SDK to solve your Angularjs authentication challenges, and it’s back-end pair, the Stormpath Express SDK.

Single Page Applications: The Authentication Problem

Single page apps make a lot of sense for customer-centric applications that handle a lot of user data. SPAs are often tied to a RESTful API for a good reason: when your data makes sense, your experience makes sense. We just rebuilt our console – an Angularjs-based Single Page App – and spent a lot of time modeling out the REST API (the actual data model/structures).

With the user model mapped out, it’s much easier to build a UI for your API because the common things like list views, search boxes, sorting, etc – they just fall in place alongside your data model. Fronting a REST API with a single page app gives the assurance of sane data and the freedom to make your UI look and feel sexy. #winning

But it poses an authentication problem: how do you open up your API access in a secure way?

Before Tokens, the Cookie Session

Since we are championing tokens, we should visit their alternative: cookie-based sessions.

Most websites use a strategy that stores a cookie in the browser. After you login this cookie contains an ID that links you to a session maintained somewhere in the server. This session knows who you are when you make a request using that cookie.

There is nothing wrong with this practice as long as you use HTTPS only cookies that cannot be read by Javascript or non-secure transports.

But if you’re building a SPA, it still leaves access control as a question mark: how do you let your SPA know who this user is and what they can access?

JSON Web Tokens (JWT): A Crash Course

The best known solutions to authentication and authorization problems for APIs are the OAuth 2.0 spec, and tangentially the JWT specification, which are fairly dense. Cliff’s Notes Time! Here’s what you need to know:

  • Json Web Tokens (JWTs) are a great authentication mechanism. They give you a structured way to declare who a user is and what they can access. They can be encrypted and signed for verification.
  • The notion of scopes is powerful and yet incredibly simple: you have tons of freedom to design your own access control language.
  • Refresh tokens are horribly confusing and don’t really solve any security problems if you need high security. We’ll elaborate on this later.

If you encounter a token in the wild, it looks like this:

"dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk..."

This is a Base64 encoded string. If you break it apart you’ll actually find three separate sections:

eyJ0eXAiOiJKV1QiLA0KICJhbGciOiJIUzI1NiJ9
.
eyJpc3MiOiJqb2UiLA0KICJleHAiOjEzMDA4MTkzODAsDQogImh0dHA6Ly9leGFt
cGxlLmNvbS9pc19yb290Ijp0cnVlfQ
.
dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk

What you see is a header which describes the token, a payload which contains the juicy bits, and a signature hash that can be used to verify the integrity of the token (if you have the secret key that was used to sign it).

We’re going to magically decode the middle part, the payload, and we get this nice JSON object:

{
  "sub": "users/TzMUocMF4p",
  "name": "Robert Token Man",
  "scope": "self groups/admins",
  "exp": "1300819380"
}

This is the payload of your token, technically called the JWS Payload. It allows you to know the following:

  • Who this person is and the URI to their user resource (sub)
  • What this person can access with this token (scope)
  • When the token expires. Your API should be using this when it verifies the token.

These declarations are called claims and they are a set of assertions that can be used to “know” things about the subject. Because the token is signed with a secret key you can verify it’s signature and implictly trust what is claimed. This provides some interesting optimizations for your backend architecture, but there are some tradeoffs and we discuss them in a later section.

Tokens are given to your users after they present some hard credentials, typically a username and password but they could also provide API keys or even tokens from another service. Stormpath’s API Key Authentication Feature is an example of this. The idea is that you present your hard credentials once and then you get a token that you use in place of the hard credentials.

The JSON Web Token (JWT) specification is gaining traction quickly. It provides structure and security, but with the flexibility to modify it for your application. We highly recommend it and have a much longer article on them: Use JWT the Right Way!

Why JWTs Are Great for Single Page Applications

SPAs tend to have many faces: the logged in view, the logged out view, or the restricted view. It’s all about access control. Your users are all getting the same app but they may not have the same levels of access. You’ll find yourself building access control logic for your front end and your back end.

Because tokens contain all this information, they are very portable: they can be used by your UI and your backend to make decisions. You can share them with partner services as a means of building Single Sign On services that delegate users to the correct application.

There are some details that matter if you want to achieve this nirvana while maintaing security in the browser. We’ll get to that in the “Tokens Love Cookies” section.

How to Use JWTs Securely

If your tokens get stolen, all bets are off. Since we’re talking about SPAs we’re talking about web browsers, and we all know how many holes there are when it comes to securing data in a web brower.

But these problems have solutions, and this is what you must do:

  • Sign your tokens with a strong key that is available ONLY to the authentication service. Every time you use a token to authenticate a user, your server MUST verify that the token was signed with your secret key.

  • You should encrypt your tokens if you have to put sensitive, non-opaque information in them. This is called JSON Web Encryption or JWE

  • You should NEVER transmit tokens over a non-HTTPS connection. Man in the middle attacks are real.

  • You should store them in secure, HTTPS-only cookies. This prevents Cross-Site Scripting XSS attacks. We’ll cover this more in the section below, “Tokens Love Cookies”

But there is one catch: you have to decide how long your tokens are valid for and how you will revoke them if you need to.

Token Expiration & Revocation

The stateless benefit of simply checking the signature is great, but it does come with a problem: it means that the access token is essentially valid forever. How do you revoke the access token if you need to?

Your next level of defense is token expiration. You should set this to a value that makes sense for your application. If you’re a bank, that might be 15 minutes. If you are a social or mobile app, you might want the token to be valid forever. But what if you do need to take it away at some point?

The OAuth solution to this problem is a two-token approach, where a short-lived access token with a longer-lived refresh token is used to get more access tokens. Im my opinion, the two-token system is a very convoluted solution that feels like it was trying to address architecture optimizations and not to make security easy. For more detail I really suggest this stack overflow answer.

The real answer to token revokation is that you need to check more than just the signature and the expiration.

In the Stormpath product we provide a “status” field on all our account objects. This lets you verify that the subject of the token (the account) is not disabled.

Another option is to maintain a record of all the tokens you give out. You add a unique value to the jti field of the token and then retain that in your database, in such a way that they are linked to the users they were granted to. You can then add a layer in your system which allows you to declare a token invalid, and you check all incoming tokens against this blacklist.

Yes, with that last suggestion we have lost the holy grail of a stateless authentication check – but sometimes security requires tradeoffs.

Token Loves Cookie

I see a lot of discussions where cookies are pitted against access tokens. While we’ve all been burned by systems that store a session ID in a cookie, and that cookie is not secured and thus gets stolen. That sucks, but its not a reason to use tokens. Its a reason to avoid non-secure, non-https cookies.

Storing access tokens in HTTPS-only cookies is the best thing you can do. Never store access tokens in local storage, that storage area is very vulnerable to XSS attacks. Storing them in secure cookies achieves the following:

  • You don’t expose the token to the Javascript environment in the browser, which is vulnerable to XSS attacks

  • You don’t transmit the token over non-HTTPS connections, which are prone to man-in-the-middle attacks.

But, as always, there are tradeoffs – and there are two we care about:

The security tradeoff is that secure cookies are still vulnerable to CSRF AttacksPrevention_Cheat_Sheet) and you need to implement a CSRF token strategyPrevention_Cheat_Sheet#CSRF_Prevention_without_a_Synchronizer_Token) to combat this issue. This is quite trivial and our SDKs do this for you out of the box.

The application tradeoff is the loss of visibility into the token. All that great information about the subject and the claims is now hidden from your single page app. There are two ways to work around this:

Use the token to fetch the data your SPA needs

This is my preferred approach. You create a token that gives access to an endpoint such as /user/current. This endpoint should respond with the information you need to build the SPA for the user. When your SPA bootstraps, you attempt to access this endpoint. If you get back a successful response you continue with the bootstrap. If you do not, you know that the user needs to authenticate.

Use out-of-band information

Take advantage of the response body when you are responding to a credential exchange. At the same time you write the access token to a secure cookie you can also provide some information in the response body as well. My suggestion is this: put the payload of the JWT in the response body. This allows your JS application to get that information while not exposing the signature of the token.

It does, however, mean that you should not store sensitive information in the access token payload because you’re probably going to want to cache it in the browser for future reloads of the SPA.

Secure All The Things!

So many tradeoffs, so little time! My intention for this article is to give you the options for using tokens happily and securely in your single page app, so your team can make the best decisions.

Please leave your comments below and check out our new Stormpath Angular SDK and Stormpath Express SDK – they demonstrate how we put this into practice so it’s easy for you to take advantage of this new paradigm.

-Robert out

9 Ways to Build a Great Engineering Culture

$
0
0

Engineering Team

If you want to have a successful technology startup, you need more than just a great company culture, you specifically need a great engineering culture. A great culture gives you a tremendous advantage in recruiting top people, retaining those people, and subtly guiding their behavior to drive the business.

Contrary to the hype, culture is not about ping pong tables, softball leagues, and free lunches. Instead, culture is the set of implicit rules, guidelines, and values that a group of people guide themselves by. It’s the peer pressure that shapes behavior in powerful ways. And simply putting a bunch of core values on a wall somewhere isn’t enough. Culture is a living thing that requires ongoing care and feeding.

A culture works best when it’s aligned with a company or team’s strategy. For example, Stormpath is a high value authentication and user management service that many companies rely on for their applications to function. That means that customer trust, developer experience, and product reliability are paramount to our strategy. In turn, those issues have made their way into our culture. And while every culture should be different based on the team’s strategy, for all engineering teams there are some common elements found in the very best cultures.

1. Encourage Open Debate

“It’s important to me that I’m encouraged to have an opinion and that I’m being listened to” – Jose @ Stormpath

Tech startups are hard. Most of the time you’re building something no one has ever built or pioneering a new approach or a new market. The path is never clear and no one person has all the answers. Yet, your engineering team is a collection of very smart people who are committed enough to the vision to join the company and stick around for the roller coaster.

Their value goes beyond the ability to sling lines of code but share their thoughts and opinions on design, processes, architecture, features, etc. You may even be surprised with great ideas for sales and marketing. Not only will you benefit from their insight, but you also make them feel impactful and valued. That’s powerful. It drives better technical decisions. It helps identify hidden risks. It helps with knowledge sharing. It drives loyalty.

However, not everyone on the team will naturally speak up during a heated debate or contradict a senior manager on their own. It’s incumbent on your team leadership to make “room” for more reserved people. Watch for body language that indicates they have an opinion on a subject. Or maybe pause a debate and ask the people who aren’t vocal if they have anything to add. Or perhaps, you ask for input before or after the meeting so everyone has time to stop and put together their ideas in an email. Try it all, because well a functioning culture of debate includes everyone, not just the loud extroverts.

2. Build Commitment to Management Decisions

“Once a decision is made, we move — together. No looking back.” – Mario @ Stormpath

The culture of debate has a singular purpose — to make better decisions. And yet, its very hard to make good decisions via consensus. A strong team with a strong engineering culture has a bit of a dictatorial bent to it. One person gets the final say after the debate. CEO, CTO, Architect, Manager, Guru, whatever — this leader in the team not only needs the confidence and team skill to open and manage a true debate, but they also need the authority and confidence to stop the debate at the right point and make a firm decision. Even if it’s an unpopular decision. Harder still is instilling a sense of commitment to whatever decision is made because nothing is worse for a team than “I told you so” after a decision.

Achieving that level of commitment is hard. It’s first born out of trust in the leadership. To build that trust, make sure you’re listening and make a point to understand all the information and opinions offered. An easy test is whether you can replay the arguments back convincingly. After you’ve made your decision, don’t just announce the decision, explain why you took that path. You may be right, you may be wrong but the if team can understand “why”, then they can commit.

3. Hire for Humility

“Everyone here is really nice. The team has a good vibe and people are open to new ideas”- Jeff @ Stormpath

In order for open debate to really work in team, you need humble people. Humble people are are more focused on finding the right answer than winning an argument. Humble people have ideas and opinions but know they aren’t always right. Humble people make room for others to disagree with them and still respectfully engage. Humble people will commit to a decision counter to their opinion, so long as they feel their voice was heard. Humble people are easy to teach. Humble people are easy to work with — they’re inclusive, share credit, and tend to be open to new ideas.

Hiring for humility is more art form than science. Look out for how they talk about their former teams, how they describe their own strengths and weaknesses, and how they treat you and your team during the interview process. Do they share credit? blame? Do they make room for other people in the conversation? How do they react to a dumb question? to being contradicted?

4. Hire Smart People Who Get Sh*t Done

“We aren’t fooling around here. This is a team of professionals” – Tom @ Stormpath

If you’re a tech startup, you’re not just on a budget, you’re very limited on time. So, you need people who are worth every penny and will move fast — smart people who get shit done. To quote Joel Spolsky, “People who are Smart but don’t Get Things Done often have PhDs and work in big companies where nobody listens to them because they are completely impractical.” And “people who get things done but are not smart, will do stupid things, seemingly without thinking about them, and somebody else will have to come clean up their mess later. This makes them net liabilities to the company because not only do they fail to contribute, they also soak up good people’s time.”

If you think hiring for humility is hard, this is harder. Your tools are interview questions, programming tests, and reference checking.

The right interview questions are a great way to assess smarts. Steer clear of questions with right or wrong answers. Even the smartest candidate might forget some obscure theorem in the heat of an interview. Instead, ask questions that will expose how people tackle complex questions with no clear answer. You can take a pragmatic technical approach (like us), “How would you build a photo sharing application” or a more fanciful approach (like Microsoft) “How much tea is there in China?” Ask them to think out loud. Can they wrap their heads around the question? Find an angle of approach? Ask the right questions back to you? Are their solutions practical and based in reality? Is their path to an answer clear and internally consistent?

To determine if they can get stuff done, give them a take home programming exercise. One that’s just a little challenging, has a dozen or so requirements, and mimics your general environment. Were they able to complete it? Did they meet all the requirements? Did they take it seriously? Those are the easy checks. More importantly though, how did they organize their project? Did they document and test their code? Can you follow what they did? Did they apply an appropriate design pattern? Was the design any good?

5. Drive Customer Empathy into the Team

“I know who’s going to use our product, and what they’re trying to achieve with it. Knowing someone is going to use my code, I feel pressure to make it great.” – Robert @ Stormpath

If your engineers understand your customer and what they’re trying to achieve, they become a team of product developers. When User Experience (UX) becomes a deeper debate than just button colors, it becomes culture and leads to better product development with less meetings and management.

So how do you get there? It’s a big investment and the method depends on your business. At Stormpath, we put our engineers on support shifts so they have 1-on-1 interactions with customers to see how people are using the product, what they’re trying to do, and where they’re having issues. We encourage them to connect to the API as an end-user. It takes away from their development time but it’s an investment we feel pays for itself. What makes sense for you?

6. Encourage Exploration of New Technologies

“A artist that only sees the world in sixteen colors can only create art in sixteen colors” – Les @ Stormpath

Engineers solve problems. To do so, the very best engineers are always on the lookout for new skills and technologies to add to their toolbox. Embrace it and promote it. By letting new tech and methods into your organization you not only excite them with new challenges but you also force them to think in new ways. Consider NoSQL, a radically different and powerful way of thinking about data structures. Your particular project may not ultimately use it but by simply being exposed to it, your team’s skill has grown and may come up with a new novel solution to your next problem.

There’s a fine line between encouraging exploration and adopting new tech for the sake of new tech — which can cause a lot of problems. The way to stay on the right side of that line is to encourage your team to bring new technology to the table when they think it can have a meaningful impact to your work. Let the members share new tech in lunch and learns. And if it looks like there’s potential value, make time for the team to get their hands dirty and test the tech— perhaps through spikes, proof of concepts, or even internal hackathons.

7. Kaizen! Drive Continuous Process Improvement

“I love the freedom we have to always improve our techniques, process, and technology whenever we need to” – Elder @ Stormpath

Have a process, any process. Make it strong and clear. Heavy or light, iterate on it so that it fits your strategy and your team. It’ll ensure that your team has clear direction on what to do and how to do it. That’s just good engineering management, but to build a great engineering culture, the process should be owned and managed by the engineering team itself, not the management team.

The engineers are the ones working with the process day in and day out. They know, better than anyone, where it’s working and where it’s not. If your culture already fosters open debate and has clear goals, this ownership can work wonders.

Every two weeks or so have everyone meet with their ideas on how to improve your process. No idea is a bad idea. No matter how crazy, give it a shot for two weeks and reassess. You process will ebb and flow but always towards stronger alignment with what matters most to your company. This style of management is ultimately the backbone of Toyota manufacturing and has worked well for us at Stormpath too. If you’d like to read more on it you can check out our post on Agile Kanban process.

8. Respect Their Time

“I feel like you respect my time as a professional” – Pablo @ Stormpath

People want to be respected. If you give them that respect, you’ll be rewarded with respect, as well as loyalty and low friction in the office. Respecting your engineers is easy: respect their expertise and, more importantly, respect their time.

You can institutionalize respect incredibly fast in two ways. Start with these two and you’ll see respect spread quickly.

  1. Force your daily stand up meeting to start on-time, every time. Scheduled for 10am? Start at 10:00am and not a minute later, no matter who is late, as a sign of respect for the other people who showed up on time. Even if the manager or chief architect is late, force them to start on time to make it clear that no one is exempt.

  2. On that next big engineering deadline where everyone needs to work crazy hours, ask them, don’t tell them, to stay late and explain why it matters to the company. Set a clear and realistic expectation of what you need so that they can plan their personal lives during the push. Make sure they’re as comfortable as possible. And once its done, do everything in your power to minimize the frequency of those pushes so that you don’t lose their trust.

9. Give and Receive Regular Feedback

“Feedback, the breakfast of champions” – Alex @ Stormpath

The best engineers want to grow by improving their skills and areas where they struggle. To do so, they need clear, honest, and constructive feedback. The more often you provide that feedback the more data points they will have and the quicker they can make changes. In turn, gather feedback from them so you can improve yourself, your management skills, and the company. By building strong two-way feedback channel you’ll get better, stronger engineers and their trust and loyalty.

Setting up for regular feedback takes time and discipline. Once a quarter works well for us — often enough to be actionable and yet not repetitive. For each engineer, dedicate at least an hour of prep time to think through the feedback you think would be valuable and actionable. And ask them to spend as much time prepping to give you feedback, and reflecting on their own performance. Then schedule a one hour meeting to give and receive. Justifying this kind of time investment can be difficult for teams who’ve never done it before, especially when all of engineering feels under-resourced with short deadlines. But it’s an investment thats comes with huge long term payouts to you and your team. Preparation is key if this is new for you (and if not!).

These nine steps are powerful ways to build a great engineering culture, but they’re just the baseline. To build a truly exceptional culture, evaluate your organization’s core strategy and find ways to align your culture to that strategy in a way that’s authentic and actionable by your engineering team. If you invest the time and effort, your culture will blossom eventually help you attract, retain, and guide the best people with a lot less management.

Brand Integrity: A New .NET Backend To Boost Brand Engagement

$
0
0

Every company needs engaged employees who live the brand. These true believers are more satisfied and productive, drive great customer experiences, and help reduce employee stress and turnover. In other words, they directly impact the bottom line.

Brand Integrity is an engagement company who is disrupting business as usual with the new rules of engagement. With their sustainable solutions, they are helping their clients in various industries to synchronize their brand’s values, culture, and reputation to create a reputable and compelling brand that employees, customers, partners, and the market understand and trust.

That boost starts with an advanced web application platform, backed by Stormpath’s API for authentication and User management.

Brand Integrity Potential Point Diagram

A Web Platform for Employee Engagement

“Clients use our web platform as an ecosystem where employees can recognize each other for going above and beyond” explained Suraj Bhagavan, a software developer at Brand Integrity. “There’s an activity feed similar to what you would see in Facebook or LinkedIn that captures and shares successes and allows employees to engage socially and learn from best practices.”

Brand Integrity’s web platform, the Brand Integrity Platform allows companies to teach and reinforce positive behaviors with three key applications: employee assessments, employee recognition, and customer assessments. The platform manages, measures and shares employee experience so management – and employees – can decrease turnover, grow sales and revenue, replicate top employees’ behavior, and create lifelong customers.

Authentication and user Management in the Potential Point system is powered by Stormpath. Brand Integrity simply passes user authentication data collected from the user to Stormpath, where the authentication is handled and the credentials are stored securely. Brand Integrity’s development team can focus on their clients’ needs. Stormpath also takes the burden of user data security off of Brand Integrity’s software developers.

Potential Point’s Web Services Architecture

Like all software, the Brand Integrity Platform has evolved over years of iteration and customer feedback, and recently got a new backend architecture based on APIs and web services built in .NET with a Knockout frontend.

“The model that we have now is to consume our own API to build out our site,” explained Bhagavan. “Our product is API-based; we use third-party services to make use of things we’re not expert in, and our own API to get everything else in the data.”

This architectural approach not only allows Brand Integrity to manage their software, it also creates the potential for clients to design an employee engagement platform that is tailored for their business. “Clients can sign up for different packages and get different pieces and components – it’s all plug and play.”

Complex Login… Streamlined

As the Brand Integrity team began rearchitecting, one of the initial challenges was authentication, specifically integrating with external protocols and user stores, like SAML and LDAP.

Brand Integrity’s clients have users who need to login using many different mechanisms. “We have users who come in from wide variety of sources and we needed figure out a way to streamline all that without having to write a whole ton of code ourselves. But just getting into the security code — that is like building a company by itself.”

Brand Integrity was able to offload authentication to Stormpath, freeing up time to improve user experience and application functionality, without getting bogged down in user security and maintenance.

Unlike other access management services, Stormpath handles the entire backend, giving clients peace of mind. “We don’t want to really do all the login and all the user security, because that’s not really where we are experts,” Bhagavan explained. “It’s more of knocking around and hoping that it works. Stormpath was the solution that allowed us to get off that and just focus on our app.”

Although Stormpath does not yet have a .NET SDK, Bhagavan and his team were able to easily connect directly with Stormpath’s REST+JSON API.

Separating User and Application Data for Clarity

The company uses Stormpath’s authentication API to store user accounts in Stormpath, along with user identification information and credentials (username, password, and other pertinent information pertaining to login). Other information related to the user’s interaction with the product is stored elsewhere.

This separation of account information from usage information ensures clarity in data, and prevents the development team from having to maintain user data security. “We’re not storing any of the user information that we don’t want to store.” More and more development teams like Brand Integrity use this separation approach to limit liability and make it easier to comply with customer requirements. The model also lends itself to connections with user stores controlled by the customer, like an on-premise Active Directory server.

Stormpath has saved Brand Integrity not only many hours in setting up a user management backend, but also the hassle of building and securing authentication and authorization features.

In the future, the company plans to integrate SAML into their API. “A lot of these clients that we deal with have their own internal HR systems and internal login from their internet and right now we’ve set up a custom build,” explained Bhagavan. “We use SAML libraries and we custom build around it.” Stormpath is working to bring SAML to Brand Integrity in the near future.

Stormpath Helps Couples to Say ‘I Do’

$
0
0

A true Renaissance man, Pedro Baumann wears a number of professional hats: Web designer, Linux SysAdmin, practicing Psychotherapist. But in his free time, the full stack developer plays in Flask.

“As a Flask developer, I’m always testing new technologies,” Pedro explained. “When I found out about Stormpath, I thought it was a great idea. In my personal projects, I had used OpenID login services, Facebook services, and sometimes built the user:passwords database myself, but I did not like it! I am not a security expert, nor a database guru, so Stormpath is the solution to offering a reliable user management system to our customers.“

Pedro tested Stormpath for a webapp to manage patients in his practice, and was impressed with the results. “I even skipped using a database at all and just added all the info I needed to the customData functionality Stormpath offers,” he said.

Getting Hitched in the 21st Century

Wedding App Login

First comes love, then comes a custom wedding app.

Pedro and his bride wanted guests to be able to log into a private, richly featured wedding app with Facebook, or just create an account. The app cannot be authorized to login with Google, since Stormpath only handles one redirect URI for added security. “I used Stormpath social login to make my job programming the Facebook logins easier, allowing users to create a new account and saving some basic information about the guests,” he said.

Once logged in, guests can read about and RSVP to the wedding, comment on and discuss subjects opened by the bride and groom, and suggest songs they want to hear at the reception. Guests can even leave a nice message on a special wall that will then be printed as a poster for the newlyweds.

Wedding App Login

The bride, groom, and “admins” can edit the comments, see what songs their guests are suggesting (ordered for them by genre), and open new discussion subjects. Pedro said that the app is fully responsive and will change its display and layout according to the date and how close it is to the wedding, always showing the most relevant sections first.

The app was built with a fairly lightweight stack:

Linode with Ubuntu 12.04

Nginx as a reverse proxy for uWSGI

Circus as a service manager for my Flask uWSGI apps

Flask app with standard libraries + Flask-Stormpath and Pony ORM

All and all, Pedro reports that Stormpath has saved him stress and made the app more secure for the most important people in his life.

Wedding App Login

“It lets me focus on spending my time building new functionalities for the app, while not worrying at all about how secure my friends and family credentials are!”

While Pedro has a lot on his plate, he plans to extend the app to allow other brides and grooms to manage their own guest user management. Stormpath’s multi-tenant architecture makes it easy to extend an app into a service. The wedding service will be available in 2015.

If you’re building a Flask app and need to complete user management and secure authentication in minutes, not hours, check out our Flask resources: + Flask-Stormpath Integration and Docs + Sample App

Please join us in wishing Pedro and Lucia – who were married in December and just returned from their honeymoon – Felicidades! And check out more of the charming design mocks for their wedding app:

Wedding App Login

Wedding App Login

Updates to Stormpath Python Support

$
0
0

Stormpath Python Support

At Stormpath, we really love our Python users. Over the past year we’ve made:

In short, we’ve been working hard to not only improve our Python user experience, but also improve the overall quality and feel of our libraries and integrations.

Many the suggestions for improvements and bug fixes – as well as solutions – come from our community.

Recent Stormpath-Python Changes

In the past several Python / Flask / Django releases we’ve tremendously improved the speed at which our libraries work, reduced the number of lurking bugs, and improved error handling in a number of ways:

  • Improving stability (handling API edge cases and unexpected behaviors).
  • Fixing bugs (huge shout out to our awesome users who filed issues on our Github repos — you are the greatest)!
  • Improving performance (refactoring caching, and fixing funky cache invalidation issues).
  • And even improving extensibility — adding more options for developers, exposing more functionality, and adding lots of convenience methods to help you write your code faster.

If you aren’t using the latest versions of our Python libraries, now would be a good time to upgrade!

If you’d like to see our specific improvements, you can check out our:

And if you have any suggestions, be sure to create an issue on the relevant Github repo!

Python Plans for This Year

In terms of what you can expect in the near future, here’s what you’ll be seeing soon:

  • Integration with more than just Google and Facebook. We’re adding LinkedIn and Twitter support as well.
  • Greatly improved API Authentication support. You’ll be able to work with multiple types of OAuth2 grants, handle custom scopes, and easily work with single-page apps!
  • Lots more speed and caching improvements.
  • Better support for single sign on and hosted login, courtesy of our ID site service.
  • Improved authorization assertions. Expect to see a fully featured assertion framework.

Looking forward to helping you build more apps faster, and more securely this year.

If you’re not already using Stormpath to secure your user data, now would be a great time to get started!

Exploring Microservices Architectures with Stormpath

$
0
0

One of the biggest development trends over the last few years is a move towards architectures based on API services. While it’s increasingly common for new applications to start fresh with a services-friendly framework and functionality offloaded to API services, it’s much less common to rebuild traditional applications in a service-oriented architecture. It’s harder, there’s much more risk, as well as legacy mayhem to contend with. We applaud people who do it, and particularly the audacious people who do it for the love of Java development.

Tony Wolski has been exploring the movement from monolithic Java web applications to microservices-based architectures and documenting his odyssey and lessons learned on his (fascinating) blog.

One system he’s working on was built in a traditional structure: JSF on the frontend and Hibernate and MySQL on the backend, running on Tomcat, and deployed to Jelastic. Bit by bit, Wolski has been re-architecting an application, following Rich Manalang’s Four Principles Of Modern Web Development. Central to his efforts has been the extrapolation of services into API’s, following the third principle of “Create and use your own REST API.”

Transitioning to API Services

Replacing functionality with REST-JSON-based APIs gives him a lot more deployment flexibility and allows for more agile development. “I can make changes to the microservice without having to package up and deploy the whole thing again,” Wolski explained. His aspiration is to deploy all the backend services separately, with executable JARs that are able to connect with any UI.

Initially, Wolski had built a custom user management system but it was the first functionality he decoupled to a standalone API, using Stormpath. “With the old user management I would actually have to write the reset passwords link. With Stormpath I just hook into the API and it’s really straightforward. It takes that all away.”

“I was pretty impressed with the way that Stormpath took all of that custom-built stuff out of my hands,” he said, adding that it “takes a way a bit of the application that really has nothing to do with the application. It lets me focus on the actual business logic.”

Instead of building his own API service for user management, Wolski saved several weeks of time in actual development, as well as time in research and design of user features. “I use it because it saves me time to not think about it, design something and wonder whether I’m actually doing it right or if there’s a better way to get it out there.”

DropWizard, Dart, and Apache Shiro

With user infrastructure out of the way, Wolski turned his attention to the first of his planned microservices; a client management REST API selected for its limited scope. Critical to that effort was DropWizard.

DropWizard is a Java framework built specifically for developing RESTful web services, and it comes with tools many web services need: configuration, application metrics, logging, and operational tools. The redesign also gave him a chance to dig into Groovy and experiment with new technologies, like Dart and Angular.js.

To add a security layer, he implemented the Apache Shiro plugin for Stormpath. Apache Shiro is a fast growing Java security framework that plugs directly into Stormpath with an official integration. You can see how Wolski configured Shiro’s Authentication filter to work with Dart/Chromium on his blog.

The new client management API proved to be so effective at increasing productivity and maintainability that he plans to follow the same model to redesign his entire monolithic app.

Wolski had such a positive experience with his initial integration to Dropwizard, he spun out his work into a standalone sample. Today, that DropWizard API secured with Shiro+Stormpath is available on GitHub, so be sure to check out his GitHub repo.

The Future

Eventually, Wolski hopes to expand the project into a multi-tenant SaaS. To do so, he’ll turn his attention to redesigning the core quoting and conveyance functionality of his application as a REST service. Stormpath will facilitate this with its support for multitenant user models.

Stay on the lookout for the full product once it is launched!


Where to Store your JWTs - Cookies vs HTML5 Web Storage

$
0
0

Stormpath has recently worked on token authentication features using JSON Web Tokens (JWT), and we have had many conversations about the security of these tokens and where to store them.

If you are curious about your options, this post is for you. We will cover the basics of JSON Web Tokens (JWT), cookies, HTML5 web storage (localStorage/sessionStorage), and basic information about cross-site scripting (XSS) and cross site request forgery (CSRF).

Let’s get started…

JSON Web Tokens (JWT): A Crash Course

The most implemented solutions for API authentication and authorization are the OAuth 2.0 and JWT specifications, which are fairly dense. Cliff’s Notes Time! Here’s what you need to know:

  • JWTs are a great authentication mechanism. They give you a structured and stateless way to declare a user and what they can access. They can be cryptographically signed and encrypted to prevent tampering on the client side.
  • JWTs are a great way to declare information about the token and authentication. You have a ton of freedom to decide what makes sense for your application because you are working with JSON.
  • The concept behind scopes is powerful yet incredibly simple: you have the freedom to design your own access control language because, again, you are working with JSON.

If you encounter a token in the wild, it looks like this:

"dBjftJeZ4CVP.mB92K27uhbUJU1p1r.wW1gFWFOEjXk..."

This is a Base64 encoded string. If you break it apart you’ll actually find three separate sections:

eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9
.
eyJpc3MiOiJodHRwOi8vZ2FsYXhpZXMuY29tIiwiZXhwIjoxMzAwODE5MzgwLCJzY29wZXMiOlsiZXhwbG9yZXIiLCJzb2xhci1oYXJ2ZXN0ZXIiXSwic3ViIjoic3RhbmxleUBhbmRyb21lZGEuY29tIn0
.
edK9cpfKKlGtT6BqaVy4bHnk5QUsbnbYCWjBEE7wcuY

The first section is a header that describes the token. The second section is a payload which contains the juicy bits, and the third section is a signature hash that can be used to verify the integrity of the token (if you have the secret key that was used to sign it).

When we magically decode the second section, the payload, we get this nice JSON object:

{
  "iss": "http://galaxies.com",
  "exp": 1300819380,
  "scopes": ["explorer", "solar-harvester", "seller"],
  "sub": "tom@andromeda.com"
}

This is the payload of your token. It allows you to know the following:

  • Who this person is (sub, short for subject)
  • What this person can access with this token (scope)
  • When the token expires (exp)
  • Who issued the token (iss, short for issuer)

These declarations are called ‘claims’ because the token creator claims a set of assertions that can be used to ‘know’ things about the subject. Because the token is signed with a secret key, you can verify its signature and implicitly trust what is claimed.

Tokens are given to your users after they present some credentials, typically a username and password, but they can also provide API keys, or even tokens from another service. This is important because it is better to pass a token (that can expire, and have limited scope) to your API than a username and password. If the username and password are compromised in a man-in-the-middle attack, it is like giving an attacker keys to the castle.

Stormpath’s API Key Authentication Feature is an example of this. The idea is that you present your hard credentials once, and then get a token to use in place of the hard credentials.

The JSON Web Token (JWT) specification is quickly gaining traction. Recommended highly by Stormpath, it provides structure and security, but with the flexibility to modify it for your application. Here is a longer article on it: Use JWT the Right Way!

Where to Store Your JWTs

So now that you have a good understanding of what a JWT is, the next step is to figure out how to store them. If you are building a web application, you have a couple options:

  • HTML5 Web Storage (localStorage/sessionStorage)
  • Cookies

To compare these two, let’s say we have a fictitious AngularJS or single page app (SPA) called galaxies.com with a login route (/token) to authenticate users to return a JWT. To access the other APIs endpoints that serve your SPA, the client needs to pass an valid JWT.

The request that the single page app makes would resemble:

HTTP/1.1

POST /token
Host: galaxies.com
Content-Type: application/x-www-form-urlencoded

username=tom@galaxies.com&password=andromedaisheadingstraightforusomg&grant_type=password

Your server’s response will vary based on whether you are using cookies or Web Storage. For comparison, let’s take a look at how you would do both.

Web Storage

Exchanging a username and password for a JWT to store it in browser storage (sessionStorage or localStorage) is rather simple. The response body would contain the JWT as an access token:

HTTP/1.1 200 OK

  {
  "access_token": "eyJhbGciOiJIUzI1NiIsI.eyJpc3MiOiJodHRwczotcGxlL.mFrs3Zo8eaSNcxiNfvRh9dqKP4F1cB",
       "expires_in":3600
   }

On the client side, you would store the token in HTML5 Web Storage (assuming that we have a success callback):

function tokenSuccess(err, response) {
    if(err){
        throw err;
    }
    $window.sessionStorage.accessToken = response.body.access_token;
}

To pass the access token back to your protected APIs, you would use the HTTP Authorization Header and the Bearer scheme. The request that your SPA would make would resemble:

HTTP/1.1

GET /stars/pollux
Host: galaxies.com
Authorization: Bearer eyJhbGciOiJIUzI1NiIsI.eyJpc3MiOiJodHRwczotcGxlL.mFrs3Zo8eaSNcxiNfvRh9dqKP4F1cB

Cookies

Exchanging a username and password for a JWT to store it in a cookie is simple as well. The response would use the Set-Cookie HTTP header:

HTTP/1.1 200 OK

Set-Cookie: access_token=eyJhbGciOiJIUzI1NiIsI.eyJpc3MiOiJodHRwczotcGxlL.mFrs3Zo8eaSNcxiNfvRh9dqKP4F1cB; Secure; HttpOnly;

To pass the access token back to your protected APIs on the same domain, the browser would automatically include the cookie value. The request to your protected API would resemble:

GET /stars/pollux
Host: galaxies.com

Cookie: access_token=eyJhbGciOiJIUzI1NiIsI.eyJpc3MiOiJodHRwczotcGxlL.mFrs3Zo8eaSNcxiNfvRh9dqKP4F1cB;

So, What’s the difference?

If you compare these approaches, both receive a JWT down to the browser. Both are stateless because all the information your API needs is in the JWT. Both are simple to pass back up to your protected APIs. The difference is in the medium.

Web Storage

Web Storage (localStorage/sessionStorage) is accessible through JavaScript on the same domain. This means that any JavaScript running on your site will have access to web storage, and because of this can be vulnerable to cross-site scripting (XSS) attacks. XSS in a nutshell is a type of vulnerability where an attacker can inject JavaScript that will run on your page. Basic XSS attacks attempt to inject JavaScript through form inputs, where the attacker puts <script>alert('You are Hacked');</script> into a form to see if it is run by the browser and can be viewed by other users.

To prevent XSS, the common response is to escape and encode all untrusted data. But this is far from the full story. In 2015, modern web apps use JavaScript hosted on CDNs or outside infrastructure. Modern web apps include 3rd party JavaScript libraries for A/B testing, funnel/market analysis, and ads. We use package managers like Bower to import other peoples’ code into our apps.

What if only one of the scripts you use is compromised? Malicious JavaScript can be embedded on the page, and Web Storage is compromised. These types of XSS attacks can get everyone’s Web Storage that visits your site, without their knowledge. This is probably why a bunch of organizations advise not to store anything of value or trust any information in web storage. This includes session identifiers and tokens.

As a storage mechanism, Web Storage does not enforce any secure standards during transfer. Whoever reads Web Storage and uses it must do their due diligence to ensure they always send the JWT over HTTPS and never HTTP.

Cookies

Cookies, when used with the HttpOnly cookie flag, are not accessible through JavaScript, and are immune to XSS. You can also set the Secure cookie flag to guarantee the cookie is only sent over HTTPS. This is one of the main reasons that cookies have been leveraged in the past to store tokens or session data. Modern developers are hesitant to use cookies because they traditionally required state to be stored on the server, thus breaking RESTful best practices. Cookies as a storage mechanism do not require state to be stored on the server if you are storing a JWT in the cookie. This is because the JWT encapsulates everything the server needs to serve the request.

However, cookies are vulnerable to a different type of attack: cross-site request forgery (CSRF). A CSRF attack is a type of attack that occurs when a malicious web site, email, or blog causes a user’s web browser to perform an unwanted action on a trusted site on which the user is currently authenticated. This is an exploit of how the browser handles cookies. A cookie can only be sent to the domains in which it is allowed. By default, this is the domain that originally set the cookie. The cookie will be sent for a request regardless of whether you are on galaxies.com or hahagonnahackyou.com.

CSRF works by attempting to lure you to hahagonnahackyou.com. That site will have either an img tag or JavaScript to emulate a form post to galaxies.com and attempt to hijack your session, if it is still valid, and modify your account.

For example:

<body>

  <!-- CSRF with an img tag -->

  <img href="http://galaxies.com/stars/pollux?transferTo=tom@stealingstars.com" />

  <!-- or with a hidden form post -->

  <script type="text/javascript">
  $(document).ready(function() {
    window.document.forms[0].submit();
  });
  </script>

  <div style="display:none;">
    <form action="http://galaxies.com/stars/pollux" method="POST">
      <input name="transferTo" value="tom@stealingstars.com" />
    <form>
  </div>
</body>

Both would send the cookie for galaxies.com and could potentially cause an unauthorized state change. CSRF can be prevented by using synchronized token patterns. This sounds complicated, but all modern web frameworks have support for this.

For example, AngularJS has a solution to validate that the cookie is accessible by only your domain. Straight from AngularJS docs:

When performing XHR requests, the $http service reads a token from a cookie (by default, XSRF-TOKEN) and sets it as an HTTP header (X-XSRF-TOKEN). Since only JavaScript that runs on your domain can read the cookie, your server can be assured that the XHR came from JavaScript running on your domain.

You can make this CSRF protection stateless by including a xsrfToken JWT claim:

{
  "iss": "http://galaxies.com",
  "exp": 1300819380,
  "scopes": ["explorer", "solar-harvester", "seller"],
  "sub": "tom@andromeda.com",
  "xsrfToken": "d9b9714c-7ac0-42e0-8696-2dae95dbc33e"
}

If you are using the Stormpath SDK for AngularJS, you get stateless CSRF protection with no development effort.

Leveraging your web app framework’s CSRF protection makes cookies rock solid for storing a JWT. CSRF can also be partially prevented by checking the HTTP Referer and Origin header from your API. CSRF attacks will have Referer and Origin headers that are unrelated to your application.

Even though they are more secure to store your JWT, cookies can cause some developer headaches, depending on if your applications require cross-domain access to work. Just be aware that cookies have additional properties (Domain/Path) that can be modified to allow you to specify where the cookie is allowed to be sent. Using AJAX, your server side can also notify browsers whether credentials (including Cookies) should be sent with requests with CORS.

Conclusion

JWTs are a awesome authentication mechanism. They give you a structured way to declare users and what they can access. They can be encrypted and signed for to prevent tampering on the client side, but the devil is in the details and where you store them. Stormpath recommends that you store your JWT in cookies for web applications, because of the additional security they provide, and the simplicity of protecting against CSRF with modern web frameworks. HTML5 Web Storage is vulnerable to XSS, has a larger attack surface area, and can impact all application users on a successful attack.

Questions or comments? We would love to hear them! Let me know if you have any questions in the discussion below or at tom@stormpath.com / @omgitstom.

How to build an app with AngularJS, Node.js and Stormpath in 15 minutes

$
0
0

AngularJS is a framework for building front-end (browser) applications, also known as “Single Page Apps” (SPAs), and we think it’s superb!

AngularJS makes it very easy to build a complex, responsive application, particularly to put a SPA on top of your API service. And once you have an app up, you want your users to be able to log in.

In this tutorial we will:

  • Scaffold a basic AngularJS app With Yeoman, Bower and Grunt
  • Create a simple API backend using Node.js for a “Fullstack” project (meaning it has both a front-end and back-end, paired together).
  • Use Stormpath, a user management API, to manage authentication and other user management features in a new AngularJS project. Throughout this tutorial we reference the [Stormpath AngularJS SDK Docs][] and the complete Stormpath AngularJS Guide. Those resources will help you move beyond this tutorial and explore all the possibilities of our AngularJS SDK.
  • Set up common user routes and views for registration, login, and user profile data.

Here is a preview of what it will look like:

Registration Form

Login Form

User Profile View

Let’s get started!

Generate a Project With Yeoman, Bower and Grunt

If this is your first time using Yeoman, Bower and Grunt, you’re in for a treat! They make it very easy to “scaffold” or “generate” the boilerplate code for a fullstack AngularJS + Node.js project.

We’re going to use a specific Yeoman generator to generate the boilerplate for our fullstack project. The generated project will use Bower to manage the front-end dependencies, and Grunt for performing tasks like rebuilding your code as you edit it.

Assuming you already have Node.js on your system, you can install these tools with these commands:

$ npm install -g grunt-cli
$ npm install -g yo
$ npm install -g bower
$ npm install -g generator-angular-fullstack

Once that’s done you need to create a project directory and change directories into it:

$ mkdir my-angular-project && cd $_

Now for the fun part: running the generator. Kick it off with this command:

$ yo angular-fullstack dashboard-app

We are calling our app “dashboard-app”, because it’s going to be a dashboard for users who visit our website. The generator will ask you several questions, such as which templating engine to use. We’re sticking to vanilla HTML/CSS/JS for this guide, the only opinionated choice we are making is to the the 3rd-party UI Router instead of Angular’s default $route service. Here are the choices that we made:

# Client

? What would you like to write scripts with? JavaScript
? What would you like to write markup with? HTML
? What would you like to write stylesheets with? CSS
? What Angular router would you like to use? uiRouter
? Would you like to include Bootstrap? Yes
? Would you like to include UI Bootstrap? No

# Server

? Would you like to use mongoDB with Mongoose for data modeling? No

Assuming everything installs OK you should now have the default project in place. Use this Grunt command to start the development server and see the application:

$ grunt serve

It should automatically open this page in your browser:

Sweet! We’re got an AngularJS application, we are ready to add the user components to it. Now would be a good time to start using Git with your project, you can stop the server by pressing Ctrl+C – then use these git commands:

$ git init
$ git add .
$ git commit -m "Begin dashboard app project"

Sign Up With Stormpath

If you don’t have a Stormpath account, head over to https://api.stormpath.com/register and sign up for one – it’s really easy and our Developer plan is always free. We’ll send you an email verification message, click on the link and then login to the Admin Console at https://api.stormpath.com/login

Stormpath – once installed in your app – will automate a lot of the user functionality, interactions and views so you don’t have to build it.

Create an API Key Pair

Once you’ve logged into the Stormpath Admin Console, click the “Manage API Keys” button on the homepage. This will generate a new API key pair and prompt you to download it as a file. Keep this file safe and secure, we will need it in the next section.

Get Your Application HREF

Stormpath allows you to provision any number of “Applications”. An “Application” is just Stormpath’s term for a project. One is created for you automatically when you sign up. You can find this in the “Applications” section of the Admin Console, and if you click into it you will see it’s HREF – you will need this in the next section.

The general rule is that you should create one Application per website (or project). Since we’re just starting you can use the default application that was created for you, called “My Application”.

Add Stormpath to your API Server

The generator created an Express.js server for us, it serves a list of things at /api/things (you saw this when you ran grunt serve for the first time, they were listed on the home page of the application). We will use Stormpath to secure this simple API.

We need to give your Stormpath information to Express. Locate the file server/config/local.env.js and add these properties to the export block, but using your information:

module.exports = {
  DOMAIN: 'http://localhost:9000',
  SESSION_SECRET: "dashboard-secret",
  // Control debug level for modules using visionmedia/debug
  DEBUG: '',
  STORMPATH_API_KEY_ID: 'YOUR_KEY_ID',
  STORMPATH_API_KEY_SECRET: 'YOUR_KEY_SECRET',
  STORMPATH_APP_HREF: 'YOUR_APP_HREF'
};

Upgrade Express.js

Run this command to make sure that you have the latest version of Express.js:

$ npm i --save express@latest

Configure the Middleware

Now we can configure the Stormpath Express SDK and use it to secure the API. Find the file server/routes.js, we’re going to make some modifications to it. This is the main file used by Express to configure the endpoints that are available in our API.

To begin you need to require the Stormpath Express SDK, add this line to the top of the file:

var stormpathExpressSdk = require('stormpath-sdk-express');

Now you can create an instance of the Stormpath middleware, add this line before the module.exports statement:

var spMiddleware = stormpathExpressSdk.createMiddleware();

We want to attach the Stormpath middleware to the Express application. Add this line inside the module.exports block, before any other app statements:

spMiddleware.attachDefaults(app);

This will attach a handful of necessary endpoints, such as the endpoint that will accept POST requests from the login form. This is all handled under the hood by the SDK, nothing more for you to do here!

Last but most importantly: we want to protect the things API. Modify that line to use the Stormpath authenticate middleware:

app.use('/api/things', spMiddleware.authenticate, require('./api/thing'));

Add Stormpath To The AngularJS Application

Since we are using Bower to manage dependencies for our AngularJS application, run this command in your project folder to install the Stormpath AngularJS SDK:

$ bower install --save stormpath-sdk-angularjs

When you use third-party modules in AngularJS you need to declare them as dependencies of your main application module. We need to declare the Stormpath Angular SDK as a dependency of our application.

Open the file client/app/app.js and modify the module list to look like so:

angular.module('dashboardAppApp', [
  'ngCookies',
  'ngResource',
  'ngSanitize',
  'ui.router',
  'stormpath',
  'stormpath.templates'
])

Note that that we also included the Stormpath templates module, this module provides the default templates that we will be using in this tutorial. Want to write your own templates? No problem! All of the Stormpath directives can take an optional template. See the Stormpath AngularJS SDK API Documentation for more information.

Configure the UI Router Integration

While AngularJS does provide a routing system, via the $route service, we’ve decided to use the UI Router module for this application. It’s very well featured and the norm for complex AngularJS applications.

In the same app.js file you want to add this run block, place it below the .config block (make sure you move the semicolon from the config block to the run block):

.run(function($stormpath){
  $stormpath.uiRouter({
    loginState: 'login',
    defaultPostLoginState: 'main'
  });
});

This tells the SDK to do the following:

  • Redirect users to the login view if they try to access a restricted view. After login they’ll be send back to the view that they requested.
  • Send users to the main view after login, if they have visited the login page directly (they did not try to access a restricted view first)

This completes our initial configuration of the SDK, in the next section we will add some links to the menu so that we can access the new views we will be creating.

Customize the Menu

In the next few sections we will create views for a login form, a user registration form, and a user profile page. We’ll need some clickable links that we can use to get to those pages, so we’ll create those links first.

Open the file client/components/navbar/navbar.html and replace the <ul> section with this markup:

<ul class="nav navbar-nav">
  <li ng-repeat="item in menu" ng-class="{active: isActive(item.link)}">
      <a ng-href="{{item.link}}">{{item.title}}</a>
  </li>
  <li if-user ng-class="{active: isActive('/profile')}">
      <a ng-href="/profile">Profile</a>
  </li>
  <li if-not-user ng-class="{active: isActive('/register')}">
      <a ui-sref="register">Register</a>
  </li>
  <li if-not-user ng-class="{active: isActive('/login')}">
      <a ui-sref="login">Login</a>
  </li>
  <li if-user ng-class="{active: isActive('/logout')}">
      <a ui-sref="main" logout>Logout</a>
  </li>
</ul>

We’ve retained the piece that iterates over the default links, but we also added the new links that we want. We are using the ifUser and ifNotUser directives to control the visibility of the links.

You can reload the app to see these changes, but the links won’t work until we complete the next few sections.

Create the Registration Form

We want users to register for accounts on our site. The Stormpath AngularJS SDK provides a built-in registration form that we can just drop in. When it’s used, Stormpath will create a new account in the Stormpath Directory that is associated with the Stormpath Application that you are using.

Generate the /register Route

When you want to create a new route and view in an Angular application, there are a handful of files that you have to make. Thankfully the generator is going to help us with this.

Stop the server and run this command in your project folder:

$ yo angular-fullstack:route register

It will ask you some questions, just hit enter to choose the defaults for all of them. Now start the server and click the link to the Register page, you will see the default view that was created:

This is the default template that was created by the generator. In the next section we will edit that template and use the default registration form that Stormpath provides.

Use the Registration Form Directive

AngularJS has a component called a “directive”. They can look like custom HTML elements, or they can look like attributes that you add to existing elements. In either case you are “mixing in” some functionality that another module provides.

The Stormpath AngularJS SDK provides a directive which inserts the default registration page into the given element. Open the file client/app/register/register.html and then replace it’s contents with this (notice where the directive is):

<div ng-include="'components/navbar/navbar.html'"></div>

<div class="container">
  <div class="row">
    <div class="col-xs-12">
      <h3>Registration</h3>
      <hr>
    </div>
  </div>
  <div sp-registration-form post-login-state="main"></div>
</div>

This is a small bit of HTML markup which does the following:

  • Includes the common menu bar for the application (we modified this in the last section)
  • Sets up some [Bootstrap][] classes so that the page flows nicely
  • Inserts the default registration form, via the sp-registration-form directive
  • Declares (as an option to the directive) that we want to send the user to the main view after they register

Save that file and the browser should auto reload, you should now see the registration route like this:

You can now register for your application, git it a try! After you register you will be prompted to login, but the link won’t work yet – we’re going to build the Login form in the next section.

Stormpath also provides email verification features: we can send a link that the user must click on before their account is activated. We discuss this in detail in the Stormpath AngularJS Guide, see the Email Verification Directive section.

Create the Login Form

Just like the registration form, Stormpath also provides a default login form that you can easily include in your application. Like we did with the Registration page, we will use the generator to create the login route and view.

Stop the server and run this command in your project folder, pressing enter to choose all the default options when it asks:

$ yo angular-fullstack:route login

Use the Login Form Directive

Open the file client/app/login/login.html and then replace it’s contents with this:

<div ng-include="'components/navbar/navbar.html'"></div>

<div class="container">
  <div class="row">
    <div class="col-xs-12">
      <h3>Login</h3>
      <hr>
    </div>
  </div>
  <div sp-login-form></div>
</div>

This is a small bit of HTML markup which does the following:

  • Includes the common menu bar for the application
  • Sets up some Bootstrap classes so that the page flows nicely
  • Inserts the default login form, via the spLoginForm directive

Save that file and the browser should auto reload, you should now see the login route like this:

At this point you should be able to login to your application! It will simply redirect you back to the main view, which isn’t very exciting. In the next section we’ll build a bare-bones user profile view that will show you the details about your user object.

You will also notice that the Login form has a link to a password reset flow. If you would like to implement this, please see the Password Reset Flow section of the Stormpath AngularJS Guide

Creating a User Profile View

Most user-centric applications have a “Profile” view, a place where the user can view and modify their basic profile information. We’ll end this tutorial with a very basic profile view: a simple display of the JSON object that is the Stormpath user object.

Generate the /profile Route

Alright, one more time! We’re going to use the generator to scaffold the files for us:

$ yo angular-fullstack:route profile

Force Authentication

The user must be logged in if they want to see their profile, otherwise there is nothing to show! We want to prevent users from accessing this page if they are not logged in. We do that by defining the SpStateConfig on the UI state for this route.

Open the file client/app/profile/profile.js and modify the state configuration to include the Stormpath state configuration:

.state('profile', {
  url: '/profile',
  templateUrl: 'app/profile/profile.html',
  controller: 'ProfileCtrl',
  sp: {
    authenticate: true
  }
});

Build the View

We declared authentication for this state, this guarantees that the user will always be logged in by the time that this view loads (they are redirected to the login page otherwise).

With that assumption we can build our template without annoying switches or waits. The Stormpath AngularJS SDK will automatically assign the current user object to user on the Root Scope, so it will always be available in your templates.

Open the file client/app/profile/profile.html and then replace it’s contents with this:

<div ng-include="'components/navbar/navbar.html'"></div>

<div class="container">
  <div class="row">
    <div class="col-xs-12">
      <h3>My Profile</h3>
      <hr>
    </div>
  </div>

  <div class="row">
    <div class="col-xs-12">
      <pre ng-bind="user | json"></pre>
    </div>
  </div>
</div>

Just like the other pages, we’ve included our common menu and setup some basic Bootstrap classes. The <pre> block will leverage Angular’s built-in JSON filter to show the user object.

Try it out! Make sure you’re logged in, then click the Profile link. You should now see your user data:

Conclusion.. But Wait, There’s More!

This tutorial leaves you with a new AngularJS application, with a registration and login form for your users. If you want to add email verification or password reset, please refer to the complete Stormpath AngularJS Guide.

We are developing our AngularJS SDK very quickly, and new features are being added all the time! We suggest that you subscribe to the Stormpath AngularJS SDK on Github, and follow the complete guide for updates.

Here is a short list of upcoming features:

  • A detailed walkthrough of creating custom templates
  • More API security examples (like group-based access control)
  • Adding custom fields to the registration form
  • Allowing the user to edit their profile
  • Social login!

With that.. I hope that you’ll check back soon, and happy coding!

-Robert

The Ultimate Guide to Mobile API Security

$
0
0

Mobile API consumption is a topic that comes up frequently on both Stack Overflow and the Stormpath support channel. It’s a problem that has already been solved, but requires a lot of prerequisite knowledge and sufficient understanding in order to implement properly.

This post will walk you through everything you need to know to properly secure a REST API for consumption on mobile devices, whether you’re building a mobile app that needs to access a REST API, or writing a REST API and planning to have developers write mobile apps that work with your API service.

My goal is to not only explain how to properly secure your REST API for mobile developers, but to also explain how the entire exchange of credentials works from start to finish, how to recover from security breaches, and much more.

The Problem with Mobile API Security

Before we dive into how to properly secure your REST API for mobile developers — let’s first discuss what makes mobile authentication different from traditional API authentication in the first place!

The most basic form of API authentication is typically known as HTTP Basic Authentication.

The way it works is pretty simple for both the people writing API services, and the developers that consume them:

  • A developer is given an API key (typically an ID and Secret). This API key usually looks something like this: 3bb743bbd45d4eb8ae31e16b9f83c9ba:ffb7d6369eb84580ad2e52ca3fc06c9d.

  • A developer is responsible for storing this API key in a secure place on their server, in a place that nobody else can access it.

  • The developer makes API requests to the API service by putting the API key he was given into the HTTP Authorization header along with the word Basic (which is used by the API server to properly decode the authorization credentials). Here’s how a developer might specify his API key when authenticating to an API service via the command line tool cURL:

      $ curl --user 3bb743bbd45d4eb8ae31e16b9f83c9ba:ffb7d6369eb84580ad2e52ca3fc06c9d https://api.example.com/v1/test
    

    The cURL tool will take the API credentials, base64 encode them, and create an HTTP Authorization header that looks like this: Basic M2JiNzQzYmJkNDVkNGViOGFlMzFlMTZiOWY4M2M5YmE6ZmZiN2Q2MzY5ZWI4NDU4MGFkMmU1MmNhM2ZjMDZjOWQ=.

    The API server will then reverse this process. When it finds the HTTP Authorization header, it will base64 decode the result, grab the API key ID and Secret, then validate these tokens before allowing the request to continue being processed.

HTTP Basic Authentication is great because it’s simple. A developer can request an API key, and easily authenticate to the API service using this key.

What makes HTTP Basic Authentication a bad option for mobile apps is that you need to actually store the API key securely in order for things to work. In addition to this, HTTP Basic Authentication requires that your raw API keys be sent over the wire for every request, thereby increasing the chance of exploitation in the long run (the less you use your credentials, the better).

In most cases, this is impractical as there’s no way to safely embed your API keys into a mobile app that is distributed to many users.

For instance, if you build a mobile app with your API keys embedded inside of it, a savvy user could reverse engineer your app, exposing this API key, and abusing your service.

This is why HTTP Basic Authentication is not optimal in untrusted environments, like web browsers and mobile applications.

NOTE: Like all authentication protocols, HTTP Basic Authentication must be used over SSL at all times.

Which brings us to our next section…

Introducing OAuth2 for Mobile API Security

You’ve probably heard of OAuth before, and the debate about what it is and is not good for. Let’s be clear: OAuth2 is an excellent protocol for securing API services from untrusted devices, and it provides a nice way to authenticate mobile users via what is called token authentication.

Here’s how OAuth2 token authentication works from a user perspective (OAuth2 calls this the password grant flow):

  1. A user opens up your mobile app and is prompted for their username or email and password.
  2. You send a POST request from your mobile app to your API service with the user’s username or email and password data included (OVER SSL!).
  3. You validate the user credentials, and create an access token for the user that expires after a certain amount of time.
  4. You store this access token on the mobile device, treating it like an API key which lets you access your API service.
  5. Once the access token expires and no longer works, you re-prompt the user for their username or email and password.

What makes OAuth2 great for securing APIs is that it doesn’t require you to store API keys in an unsafe environment. Instead, it will generate access tokens that can be stored in an untrusted environment temporarily.

This is great because even if an attacker somehow manages to get a hold of your temporary access token, it will expire! This reduces damage potential (we’ll cover this in more depth in our next article).

Now, when your API service generates an Oauth2 access token that your mobile app needs, of course you’ll need to store this in your mobile app somewhere.

BUT WHERE?!

Well, there are different places this token should be stored depending on what platform you’re developing against. If you’re writing an Android app, for instance, you’ll want to store all access tokens in SharedPreferences (here’s the API docs you need to make it work). If you’re an iOS developer, you will want to store your access tokens in the Keychain.

If you still have questions, the following two StackOverflow posts will be very useful — they explain not only how you should store access tokens a specific way, but why as well:

It’s all starting to come together now, right? Great!

You should now have a high level of understanding in regards to how OAuth2 can help you, why you should use it, and roughly how it works.

Which brings us to the next section…

Access Tokens

Let’s talk about access tokens for a little bit. What the heck are they, anyway? Are they randomly generated numbers? Are they uuids? Are they something else? AND WHY?!

Great questions!

Here’s the short answer: an access token can technically be anything you want:

  • A random number.
  • A random string.
  • A UUID.
  • etc.

As long as you can:

  • Issue it to a client,
  • Verify that it was created by you (using a strong signature),
  • And assign it an expiration time…

You’re golden!

BUT… With that said, there are some conventions you’ll probably want to follow.

Instead of handling all this stuff yourself, you can instead create an access token that’s a JWT (JSON Web Token). It’s a relatively new specification that allows you to generate access tokens that:

  • Can be issues to clients.
  • Can be verified as being created by you (more on this later).
  • Can expire automatically at a specific time.
  • Can hold variable JSON information.
  • Can reduce the amount of API calls to your service by allowing users to validate / verify their API credentials LOCALLY, without querying your service!

JWTs also look like a randomly generated string: so you can always store them as strings when using them. This makes them really convenient to use in place of a traditional access token as they’re basically the same thing, except with way more benefits.

JWTs are almost always cryptographically signed. The way they work is like so:

  • You store a secure random string somewhere on your API server. This should ideally just be a long random string (40 characters or so is fine).
  • When you create a new JWT, you’ll pass this random string into your JWT library to sign the token, along with any JSON data you want to store: a user account ID, an email address, what permissions this user has, etc.
  • This token will be generated, and it’ll look something like this: header.claims.signature — where header, claims, and signature are just long base64 encoded strings. This isn’t really important to know though.
  • You give this token to your user: likely an API client (eg: your mobile app).

Now, from the mobile client, you can view whatever is stored in the JWT. So if I have a JWT, I can easily check to see what JSON data is inside it. Usually it’ll be something like:

{
  "user_id": "e3457285-b604-4990-b902-960bcadb0693",
  "scope": "can-read can-write"
}

Now, this is a 100% fictional example, of course, but you get the idea: if I have a copy of this JWT token, I can see the JSON data above, yey!

But I can also verify that it is still valid, because the JWT spec supports expiring tokens automatically. So when you’re using your JWT library in whatever language you’re writing, you’ll be able to verify that the JWT you have is valid and hasn’t yet expired (cool).

This means that if you use a JWT to access an API service, you’ll be able to tell whether or not your API call will work by simply validating the JWT! No API call required!

Now, once you’ve got a valid JWT, you can also do cool stuff with it on the server-side.

Let’s say you’ve given out a JWT to a mobile app that contains the following data:

{
  "user_id": "e3457285-b604-4990-b902-960bcadb0693",
  "scope": "can-read can-write"
}

But let’s say some malicious program on the mobile app is able to modify your JWT so that it says:

{
  "user_id": "e3457285-b604-4990-b902-960bcadb0693",
  "scope": "can-read can-write can-delete"
}

See how I added in the can-delete permission there? What will happen if this modified token is sent to our API server? Will it work? Will our server accept this modified JWT?

NOPE!!

When your API service receives this JWT and validates it, it’ll do a few things:

  • It’ll check the token to make sure it wasn’t tampered with. It does this by using the secret randomly generated string that only the server knows. If the JWT was modified at all, this check will fail, and you’ll know someone is trying to do something nasty.
  • It’ll also check the expires time of this JWT to make sure it’s actually valid. So if you assigned a JWT a long time ago that has long since expired, you’ll know that your client is trying to use an old token — so you can just reject their API request.

This is nice functionality, as it makes handling verification / expiration / security a lot simpler.

The only thing you need to keep in mind when working with JWTs is this: you should only store stuff you don’t mind exposing publicly.

As long as you follow the rule above, you really can’t go wrong with using JWTs.

The two pieces of information you’ll typically store inside of a JWT are:

  • A user account’s unique ID of some sort. This way you can look this user up from your user database when you receive this JWT for authentication.
  • A user’s permissions: what they can and can’t do. If you’re building a simple API service where all users are the same, this may not be necessary. But this way, users won’t need to hit your API to figure out what they can do all the time: instead, they can just look at their JWT.

So, that just about sums up JWTs. Hopefully you now know why you should be using them as your OAuth access tokens — they provide:

  • A nice way to validate tokens.
  • A nice way to pass publicly-viewable information to a client.
  • A simple interface for developers to work with.
  • Built-in expiration.

Now, moving on — let’s talk about how this all works together…

How it All Works

In this section we’re going to get into the nitty gritty and cover the entire flow from start to finish, with all the low-level technical details you need to build a secure API service that can be securely consumed from a mobile device.

Ready? Let’s do this.

First off, here’s how things will look when we’re done. You’ll notice each image has a little picture next to it. That’s because I’m going to explain each step in detail below.

OAuth2 Flow

So, take a look at that image above, and then follow along.

1. User Opens App

The user opens the app! Next!

2. App Asks for Credentials

Since we’re going to be using the OAuth2 password grant type scheme to authenticate users against our API service, your app needs to ask the user for their username or email and password.

Almost all mobile apps ask for this nowadays, so users are used to typing their information in.

3. User Enters their Credentials

Next, the user enters their credentials into your app. Bam. Done. Next!

4. App Sends POST Requests to API Service

This is where the initial OAuth2 flow begins. What you’ll be doing is essentially making a simple HTTP POST request from your mobile app to your API service.

Here’s a command line POST request example using cURL:

$ curl --form 'grant_type=password&username=USERNAMEOREMAIL&password=PASSWORD' https://api.example.com/v1/oauth

What we’re doing here is POST’ing the username or email and password to our API service using the OAuth2 password grant type: (there are several grant types, but this is the one we’ll be talking about here as it’s the only relevant one when discussing building your own mobile-accessible API).

NOTE: See how we’re sending the body of our POST request as form content? That is, application/www-x-form-urlencoded? This is what the OAuth2 spec wants =)

5. API Server Authenticates the User

What happens next is that your API service retrieves the incoming username or email and password data and validates the user’s credentials.

This step is very platform specific, but typically works like so:

  1. You retrieve the user account from your database by username or email.
  2. You compare the password hash from your database to the password received from the incoming API request. NOTE: Hopefully you store your passwords with bcrypt!
  3. If the credentials are valid (the user exists, and the password matches), then you can move onto the next step. If not, you’ll return an error response to the app, letting it know that either the username or email and password are invalid.

6. API Server Generates a JWT that the App Stores

Now that you’ve authenticated the app’s OAuth2 request, you need to generate an access token for the app. To do this, you’ll use a JWT library to generate a useful access token, then return it to the app.

Here’s how you’ll do it:

  1. Using whatever JWT library is available for your language, you’ll create a JWT that includes JSON data which holds the user ID (from your database, typically), all user permissions (if you have any), and any other data you need the app to immediately access.

  2. Once you’ve generated a JWT, you’ll return a JSON response to the app that looks something like this:

     {
       "access_token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJEUExSSTVUTEVNMjFTQzNER0xHUjBJOFpYIiwiaXNzIjoiaHR0cHM6Ly9hcGkuc3Rvcm1wYXRoLmNvbS92MS9hcHBsaWNhdGlvbnMvNWpvQVVKdFZONHNkT3dUVVJEc0VDNSIsImlhdCI6MTQwNjY1OTkxMCwiZXhwIjoxNDA2NjYzNTEwLCJzY29wZSI6IiJ9.ypDMDMMCRCtDhWPMMc9l_Q-O-rj5LATalHYa3droYkY",
       "token_type": "bearer",
       "expires_in": 3600
     }
    

    As you can see above, our JSON response contains 3 fields. The first field access_token, is the actual OAuth2 access token that the mobile app will be using from this point forward in order to make authenticated API requests.

    The second field, token_type, simply tells the mobile app what type of access token we’re providing — in this case, we’re providing an OAuth2 Bearer token. I’ll talk about this more later on.

    Lastly, the third field provided is the expires_in field. This is basically the number of seconds for which the supplied access token is valid.

    In the example above, what we’re saying is that we’re giving this mobile app an access token which can be used to access our private API for up to 1 hour — no more. After 1 hour (3600 seconds) this access token will expire, and any future API calls we make using that access token will fail.

  3. On the mobile app side of things, you’ll retrieve this JSON response, parse out the access token that was provided by the API server, and then store it locally in a secure location. On Android, this means SharedPreferences, on iOS, this means Keychain.

Now that you’ve got an access token securely stored on the mobile device, you can use it for making all subsequent API requests to your API server.

Not bad, right?

7. App Makes Authenticated Requests to API Server

All that’s left to do now is to make secure API requests from your mobile app to your API service. The way you do this is simple.

In the last step, your mobile app was given an OAuth2 access token, which it then stored locally on the device.

In order to successfully make API requests using this token, you’ll need to create an HTTP Authorization header that uses this token to identify your user.

To do this, what you’ll do is insert your access token along with the word Bearer into the HTTP Authorization header. Here’s how this might look using cURL:

$ curl -H "Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJEUExSSTVUTEVNMjFTQzNER0xHUjBJOFpYIiwiaXNzIjoiaHR0cHM6Ly9hcGkuc3Rvcm1wYXRoLmNvbS92MS9hcHBsaWNhdGlvbnMvNWpvQVVKdFZONHNkT3dUVVJEc0VDNSIsImlhdCI6MTQwNjY1OTkxMCwiZXhwIjoxNDA2NjYzNTEwLCJzY29wZSI6IiJ9.ypDMDMMCRCtDhWPMMc9l_Q-O-rj5LATalHYa3droYkY" https://api.example.com/v1/test

In the end, your Authorization header will look like this: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJEUExSSTVUTEVNMjFTQzNER0xHUjBJOFpYIiwiaXNzIjoiaHR0cHM6Ly9hcGkuc3Rvcm1wYXRoLmNvbS92MS9hcHBsaWNhdGlvbnMvNWpvQVVKdFZONHNkT3dUVVJEc0VDNSIsImlhdCI6MTQwNjY1OTkxMCwiZXhwIjoxNDA2NjYzNTEwLCJzY29wZSI6IiJ9.ypDMDMMCRCtDhWPMMc9l_Q-O-rj5LATalHYa3droYkY.

When your API service receives the HTTP request, what it will do is this:

  1. Inspect the HTTP Authorization header value, and see that it starts with the word Bearer.

  2. Next, it’ll grab the following string value, referring to this as the access token.

  3. It’ll then validate this access token (JWT) using a JWT library. This step ensures the token is valid, untampered with, and not yet expired.

  4. It’ll then retrieve the user’s ID and permissions out of the token (permissions are optional, of course).

  5. It’ll then retrieve the user account from the user database.

  6. Lastly, it will ensure that what the user is trying to do is allowed, eg: the user must be allowed to do what they’re trying to do. After this is done, the API server will simply process the API request and return the result normally.

Nothing anything familiar about this flow? You should! It’s almost the exact same way HTTP Basic Authentication works, with one main difference in execution: the HTTP Authorization header is slightly different (Bearer vs Basic).

This is the end of the “How it All Works” section. In the next article, we’ll talk about all the other things you need to know about managing API authentication on mobile devices.

Simpler Solutions

As this is a high level article meant to illustrate how to properly write an API service that can be consumed from mobile devices, I’m not going to get into language specific implementation details here — however, I do want to cover something I consider to be very important.

If you’re planning on writing your own API service like the ones discussed in this article, you’ll want to write as little of the actual security code as possible. While I’ve done my best to summarize exactly what needs to be done in each step in the process, actual implementation details can be quite a bit more complex.

It’s usually a good idea to find a popular OAuth2 library for your favorite programming language or framework, and use that to help offload some of the burden of writing this sort of thing yourself.

Lastly, if you really want to simplify things, you might want to sign up for our service: Stormpath. Stormpath is an API service that stores your user accounts securely, manages API keys, handles OAuth2 flows, and also provides tons of convenience methods / functions for working with user data, doing social login, and a variety of other things.

Stormpath is also totally, 100% free to use. You can start using it RIGHT NOW in your applications, and BAM, things will just work. We only charge you for real projects — feel free to deploy as many side projects as you’d like on our platform for no cost =)

Hopefully this article has helped you figure out the best way to handle API authentication for your mobile devices. If you have any questions (this stuff can be confusing), feel free to email us directly!

-Randall

How to Manage API Authentication Lifecycle on Mobile Devices

$
0
0

If you didn’t catch it, in the last article I explained how to know to build and deploy a real mobile app that uses OAuth2 authentication for your private API service.

In this article, I’m going to cover a tightly related topic: how to properly manage your OAuth2 API token lifecycle.

Because things like token expiration and revocation are so paramount to API security, I figured they deserved their own discussion here.

Token Expiration

One of the most common questions we get here at Stormpath, when talking about token authentication for mobile devices, is about token expiration.

Developers typically ask us this:

“This OAuth2 stuff with JSON Web Tokens sounds good, but how long should I allow my access tokens to exist before expiring them? I don’t want to force my users to re-authenticate every hour. That would suck.”

This is an excellent question. The answer is a bit tricky though. Here are some general rules:

If you’re dealing with any form of sensitive data (money, banking data, etc.), don’t bother storing access tokens on the mobile device at all. When you authenticate the user and get an access token, just keep it in memory. When a users closes your app, your memory will be cleaned up, and the token will be gone. This will force users to log into your app every time they open it, but that’s a good thing.

For extra security, make sure your tokens themselves expire after a short period of time (eg: 1 hour) — this way, even if an attacker somehow compromises your access token, it’ll still expire fairly quickly.

If you’re building an app that holds sensitive data, that’s not related to money, you’re probably fine forcing tokens to expire somewhere around the range of every month. For instance, if I was building a mobile app that allowed users to take fitness progress photos of themselves to review at a later time, I’d use a 1 month setting.

The above setting is a good idea as it doesn’t annoy users, requiring them to re-input their credentials every time the open the app, but also doesn’t expose them to unnecessary risk. In the worst case scenario above, if a user’s access token is compromised, an attacker might be able to view this person’s progress photos for up to one month.

If you’re building a massive consumer application, like a game or social application, you should probably use a much more liberal expiration time: anywhere from 6 months to 1 year.

For these sorts of applications, there is very little risk storing an access token for a long period of time, as the service contains only low-value content that can’t really hurt a user much if leaked. If a token is compromised, it’s not the end of the world.

This strategy also has the benefit of not annoying users by prompting them to re-authenticate very frequently. For many mass consumer applications, signing in is considered a big pain, so you don’t want to do anything to break down your user experience.

Token Revocation

Let’s now talk about token revocation. What do you do if an access token is compromised?

Firstly, let’s discuss the odds of this happening. In general: they are very low. Using the recommended data stores for Android and iOS will greatly reduce the risk of your tokens being compromised, as the operating system provides a lot of built-in protections for storing sensitive data like access tokens.

But, let’s assume for this exercise that a user using your mobile app lost their phone, a saavy hacker grabbed it, broke through the OS-level protections, and was able to extract your API service’s access token.

What do you do?

This is where token revocation comes into play.

It is, in general, a good idea to support token revocation for your API service. What this means is that you should have a way to strategically invalidate tokens after issuing them.

NOTE: Many API services do not support token revocation, and as such, simply rely on token expiration times to handle abuse issues.

Supporting token revocation means you’ll have to go through an extra few steps when building this stuff out:

  1. You’ll need to store all access tokens (JWTs) that you generate for clients in a database. This way, you can see what tokens you’ve previously assigned, and which ones are valid.

  2. You’ll need to write an API endpoint which accepts an access token (or user credentials) and removes either the specific access token or all access tokens from a user’s account.

For those of you wondering how this works, the official OAuth2 Revocation Spec actually talks about it in very simple terms. The gist of it is that you write an endpoint like /revoke that accepts POST requests, with the token or credentials in the body of the request.

The idea is basically this though: once you know that a given access token, or user account has been compromised, you’ll issue the appropriate revocation API request to your private API service. You’ll either revoke:

  • The single access token, or
  • All access tokens for a given user account.

Make sense? Great!

Simpler Solutions

If you’re planning on writing your own API service like the ones discussed in this article, you’ll want to write as little of the actual security code as possible. Actual implementation details can be quite a bit more complex, depending on your framework and programming langugage.

Stormpath is an API service that stores your user accounts securely, manages API keys, handles OAuth2 flows, and also provides tons of convenience methods / functions for working with user data, doing social login, and a variety of other things.

If you have any questions (this stuff can be confusing), feel free to email us directly — we really don’t mind answering questions! You can, of course, also just leave a comment below. Either way works!

-Randall

Why HTTP is Sometimes Better than HTTPS

$
0
0

Gas Mask Sketch

UPDATED April 2, 2015: This was an April Fools Joke. Read. Laugh. Learn. If you’re building web services, you should most definitely be using HTTPS.

As a security company, we frequently get questions here at Stormpath from developers regarding security best practices. One of the most common questions we get is:

Should I run my site over HTTPS?

Unfortunately, regardless of where you go on the internet, you’ll mostly ready the same advice: encrypt everything!, use SSL for all sites!, etc. The reality, of course, is that this is not usually good advice.

There are many circumstances where HTTP is better than HTTPS. HTTP is, in fact, a much better and more useful protocol than HTTPS, which is why we often recommend it to our customers. Here’s why…

The Problems with HTTPS

HTTPS as a protocol is riddled with problems. Numerous, well-known issues with the protocol and popular implementations make it unsuitable for a wide variety of web services.

HTTPS is Painfully Slow

Sloth Sketch

One of the primary blockers for HTTPS adoption is the fact that the HTTPS protocol is painfully slow.

By its very nature, HTTPS is meant to securely encrypt communications between two parties. This requires both parties continuously spend valuable CPU cycles:

  • Initially saying “hello” and determining what sorts of encryption to use (cypher suites).
  • Validating SSL certificates.
  • Running crypto code for each request to validate / verify the request / response.

While this doesn’t sound like much, crypto code is very CPU intensive. It makes heavy usage of the floating point CPU registers, which taxes your CPU and slows down request processing.

Here’s a very informative ServerFault thread showing just how big of a slowdown you can expect using a simple Ubuntu sever with Apache2: http://serverfault.com/questions/43692/how-much-of-a-performance-hit-for-https-vs-http-for-apache

Here are the results:

HTTPS is Slow

Even in a very simple example like the one shown above, HTTPS can reduce the speed of your web server by more than 40 times! That’s a HUGE drag to web performance.

In environments today, where it’s common to build your application as a composition of REST APIs — using HTTPS is a sure way to slow down your site, reduce your application’s performance, unnecessarily hammer your server CPUs, and generally annoy your users.

For many speed sensitive applications it’s often much better to just use plain HTTP.

HTTPS Isn’t a One-Size-Fits All Safeguard

Darth Vader Sketch

A lot of people are under the impression that HTTPS will make their site secure. This isn’t true.

HTTPS only encrypts traffic between you and a server — once the HTTPS information transit has terminated, everything is fair game.

This means that if your computer is already infected with malware, or you’ve been tricked into running some malicious software — all the HTTPS in the world won’t do anything for you.

Furthermore, if any exploits exist on the HTTPS server, an attacker can simply wait until the HTTPS transaction has finished, then grab whatever data necessary at another layer (the web service layer, for example).

SSL certificates themselves are also frequently abused. The way they work in web browsers, for instance, is quite error prone:

  • Each browser vendor (Mozilla, Google, etc.) independently audits and approves root certificate providers to ensure they are securely handling SSL certs.
  • Once approved, these root SSL certs are put into the browser’s “trusted” cert list, which means that any SSL certs signed by these providers is implicitly trusted.
  • These providers are then free to screw things up and cause all sorts of security issues — like what happened with DigiNotar in 2011.

In the above case, a popular certificate authority mistakenly signed numerous fake and fraudulent certificates, directly compromising the security of (millions?) of Mozilla users.

While HTTP doesn’t offer encryption of any type, at least you know what you’re dealing with.

HTTPS Traffic Can be Intercepted Easily

If you’re building a web service that is meant to be consumed through insecure devices (like mobile apps), you might be under the impression that since your service is running over HTTPS, users are unable to intercept and read your private messages.

If that’s what you thought, you’d be wrong.

Users can easily setup a proxy on their computer to intercept and inspect all HTTPS traffic, thereby bypassing your very own SSL certificate checks, and allowing your private information to be directly leaked.

This blog post walks you through intercepting and reading private HTTPS messages on mobile devices.

Think you’re doing it right? Don’t count on it! Even large companies like Uber have had their mobile apps reverse engineered, despite their HTTPS usage. If you’re in the mood, I can’t recommend reading this article enough.

It’s time to accept the fact that no matter what you do, attackers will be able to read your traffic in one way or another. Instead of wasting engineering time trying to fix and patch common SSL issues, spend your time working on your core product or service and just use HTTP wisely.

HTTPS Exploits Exist

It’s well known that HTTPS isn’t invulnerable. There have been numerous HTTPS exploits over the years:

It’s inevitable that there will be more attacks in the future. If you pair this with the fact that the NSA is spending insane amounts of money to capture and store SSL traffic for future decryption — it seems pointless to use HTTPS considering that your private traffic will almost certainly be made public at some point in the future.

HTTPS is Expensive

The last main point I want to cover is that HTTPS is expensive. To purchase a certificate that browsers and web clients will recognize, you have to purchase an SSL certificate from a root certificate authority.

This isn’t cheap.

SSL Certificates can range from a few dollars per year to thousands — and if you’re building a distributed application that relies on multiple microservices, you’ll need more than just one.

This can quickly add up to a lot of money, which is particularly expensive for people building smaller projects, or looking to launch a new service on a tight budget.

Why HTTP is a Good Choice

On the flip side, let’s stop being negative for a moment, and instead focus on the positive: what makes HTTP great. Most developers don’t appreciate its’ benefits.

Secure in the Right Conditions

While HTTP itself doesn’t offer any security whatsoever, by properly setting up your infrastructure and network, you can avoid almost all security issues.

Firstly, for all internal HTTP services you might be using, ensure that your network is private and can’t be publicly sniffed for packets. This means you’ll probably want to deploy your HTTP services inside of a very secure network like Amazon’s EC2.

By deploying public cloud servers on EC2, you’re guaranteed to have top-notch network security, to prevent any other AWS customers from sniffing your network traffic.

Use HTTP’s Insecurity for Scaling

Something not many people think about, when obsessing over HTTP’s lack of security and encryption is how well it scales.

Most modern web applications scale via queueing.

You have a web server which accepts incoming requests, then farms individual jobs out to a cluster of servers on the same network which perform more CPU and memory intensive tasks.

To handle queueing, people typically use a system like RabbitMQ or Redis. Both are excellent choices — but what if you could get all the benefits of queueing without using any infrastructure except your network?

With HTTP, you can!

Here’s how it works:

  • Setup a network where both your web server and all worker servers share a subnet.
  • Make your worker servers listen for ALL packets on the network, and passively sniff network traffic.
  • When you receive incoming HTTP traffic to your web server, your worker servers can simply read those incoming requests (in plain text, since HTTP isn’t encrypted), and start the processing work IMMEDIATELY!

The above system works exactly like a distributed queue, is fast, efficient, and simple.

Using HTTPS, the above scenario would be impossible, but, by using HTTP, you can dramatically speed up your applications while removing your need for infrastructure services — a big win.

Insecure and Proud

The last point I’d like to mention in favor of using HTTP instead of HTTPS for your next project is: insecurity.

Yes, HTTP provides no security for your users — but is security even really necessary?

Not only do most ISPs monitor network traffic, but it’s become quite apparent over the past couple of years that the government has been storing and decrypting network traffic for a long time.

Worrying about using HTTPS is like putting a padlock on a fence that is 1 foot high: it’s basically impossible to secure your applications — so why bother?

By developing services that rely on HTTP alone, you’re not giving your users a false sense of security, tricking them into thinking they are secure when, in fact, they most likely aren’t.

By building your apps on HTTP, you’re simplifying your life, and increasing transparency with your users. Consider it!

JUST KIDDING!! >:)

Happy April Fools’ Day!

I hope you didn’t really think I would recommend against using HTTPS! I want to be perfectly clear: if you’re building any sort of web application, use HTTPS!

It doesn’t matter what sort of application or service you’re building, if it’s not using HTTPS, you are doing it wrong.

Now, let’s talk about why HTTPS is awesome.

HTTPS is Secure

Bouncer Sketch

HTTPS is a great protocol with an excellent track record. While there have been several exploits over the years, they’ve all been relatively minor, and furthermore, they’ve been patched quickly.

And yes, while the NSA is most certainly storing SSL traffic somewhere, the odds that they’re able to decrypt even a small amount of SSL traffic is infinitely small — this would require fast, fully functional quantum computers and would cost an insane amount of money. Odds are, nothing like this exists, so you can sleep easily at night knowing that the SSL on your site is actually protecting user data in transit.

HTTPS is Fast

I mentioned above that “painfully slow” HTTPS was, but the truth is almost completely the opposite.

While HTTPS certainly requires more CPU for terminating SSL connections — this processing power is negligible at best on modern computers. The odds that you’ll ever hit an SSL bottleneck are effectively 0.

You’re far more likely to have a bottleneck with your application or web server performance.

HTTPS is an Important Safeguard

While HTTPS isn’t a one-size-fits-all solution to web security, without it you’re guaranteed to be insecure.

All web security relies on you having HTTPS. If you don’t have it, then no matter how strongly you hash your passwords or how much data encryption you do, an attacker can simply monitor a client’s network connection, read their credentials — then BAM — game over.

So — while you can’t rely on HTTPS to solve all of your security problems, you absolutely, 100% need to use it for all services you build — otherwise there’s absolutely no way to secure your application.

Furthermore, while certificate signing is most definitely not a perfect practice, each browser vendor has pretty strict and rigorous rules for certificate authorities. It’s VERY hard to become a trusted certificate authority, and keeping yourself in good standing is equally tough.

Mozilla (and the other vendors) do an excellent job of pruning bad root authorities, and are generally awesome stewards of internet security.

HTTPS Traffic Interception Is Avoidable

Earlier, I mentioned that it’s quite easy to man-in-the-middle SSL traffic by creating your own SSL certificates, trusting them, and then intercepting traffic.

While this is most definitely possible, it’s fairly easy to prevent via SSL Certificate Pinning.

Essentially, by following the guidelines in the article linked to above, you can force your clients to trust only a true and valid SSL certificate, effectively preventing all sorts of SSL MITM attacks before they can even start =)

If you’re deploying an SSL service to an untrusted location (like a mobile or desktop app), you should most definitely look into using SSL Certificate Pinning.

HTTPS Isn’t Expensive (anymore)

While it’s true that historically, HTTPS has been expensive — this is no longer the case. You can currently purchase very cheap SSL certificates from a number of web hosts.

Furthermore, the EFF (Electronic Frontier Foundation) is just about to launch a completely free SSL certificate provider: https://letsencrypt.org/

It’s launching in 2015, and will invariably change the game for all web developers. Once Let’s Encrypt goes live, you’ll be able to encrypt 100% of your sites and services for no cost at all.

Be sure to check out their site and subscribe for updates!

HTTP Isn’t Secure on Private Networks

Earlier, when I talked about how HTTP security doesn’t matter, especially if your network is locked down — I was lying to you.

While network security matters, so does transit encryption!

If an attacker is able to gain access to any of your internal services all HTTP traffic will be intercepted and read, regardless of how ‘secure’ your network may be. This is a very bad thing.

This is why HTTPS is critically important on both public AND private networks.

BONUS: If you’re deploying services on AWS, DON’T COUNT ON YOUR NETWORK TRAFFIC BEING PRIVATE! AWS networks are PUBLIC, meaning that other AWS customers can potentially sniff your private network traffic — be very careful.

HTTP and Queueing

When I mentioned earlier how you could replace queuing infrastructure with HTTP — I wasn’t really wrong, but OH MAN. What a horrible idea!

Relying on poor security practices to “scale” your service is a bad, horrible, awful, VERY BAD idea.

Please don’t do it (unless it’s a proof-of-concept, in which case it’d make for a very cool demo to say the least)!

Summary

If you’re building web services, you should most definitely be using HTTPS.

It’s easy, cheap and builds user trust, so there’s no excuse not to. As developers, it’s our job to help protect user security — and one of the best ways to do that is to force HTTPS side-wide.

I hope you enjoyed this article, and got a good laugh or two.

If you liked this article, you might also like last year’s Apil Fools’ post as well: Why You Might Want to Store Your Passwords in Plain Text.

How to Create and verify JWTs in Java

$
0
0

Java support for JWT (JSON Web Tokens) is in its infancy – the prevalent libraries can require customization around unresolved dependencies and pages of code to assemble a simple JWT.

We recently released an open-source library for JWTs in Java. JJWT aims to be the easiest to use and understand library for creating and verifying JSON Web Tokens (JWTs) on the JVM.

JJWT is a ‘clean room’ implementation based solely on the JWT, JWS, JWE and JWA RFC draft specifications. According to one user on stack overflow, its “Simple, easy and clean, and worked immediately.” This post will show you how to use it, so any java app can generate, encrypt and decrypt JWTs without much hassle.

What Are JWTs?

JWTs are an encoded representation of a JSON object. The JSON object consists of zero or more name/value pairs, where the names are strings and the values are arbitrary JSON values. JWT is useful to send such information in the clear (for example in an URL) while it can still be trusted to be unreadable (i.e. encrypted), unmodifiable (i.e. signed) and url-safe (i.e. Base64 encoded).

Want to learn more? You can check one of our previous posts and the JWT spec.

JWTs can have different usages: authentication mechanism, url-safe encoding, securely sharing private data, interoperability, data expiration, etc. Regardless of how you will use your JWT, the mechanisms to construct and verify it are the same. So, let’s see how we can very easily achieve that with the JSON Web Token for Java project

Generate Tokens

java
import javax.crypto.spec.SecretKeySpec;
import javax.xml.bind.DatatypeConverter;
import java.security.Key;
import io.jsonwebtoken.*;
import java.util.Date;

//Sample method to construct a JWT

private String createJWT(String id, String issuer, String subject, long ttlMillis) {

//The JWT signature algorithm we will be using to sign the token
SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;

long nowMillis = System.currentTimeMillis();
Date now = new Date(nowMillis);

//We will sign our JWT with our ApiKey secret
byte[] apiKeySecretBytes = DatatypeConverter.parseBase64Binary(apiKey.getSecret());
Key signingKey = new SecretKeySpec(apiKeySecretBytes, signatureAlgorithm.getJcaName());

  //Let's set the JWT Claims
JwtBuilder builder = Jwts.builder().setId(id)
                                .setIssuedAt(now)
                                .setSubject(subject)
                                .setIssuer(issuer)
                                .signWith(signatureAlgorithm, signingKey);

 //if it has been specified, let's add the expiration
if (ttlMillis >= 0) {
    long expMillis = nowMillis + ttlMillis;
    Date exp = new Date(expMillis);
    builder.setExpiration(exp);
}

 //Builds the JWT and serializes it to a compact, URL-safe string
return builder.compact();
}

Decode and Verify Tokens

java
import javax.xml.bind.DatatypeConverter;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.Claims;

//Sample method to validate and read the JWT
private void parseJWT(String jwt) {
//This line will throw an exception if it is not a signed JWS (as expected)
Claims claims = Jwts.parser()
   .setSigningKey(DatatypeConverter.parseBase64Binary(apiKey.getSecret()))
   .parseClaimsJws(jwt).getBody();
System.out.println("ID: " + claims.getId());
System.out.println("Subject: " + claims.getSubject());
System.out.println("Issuer: " + claims.getIssuer());
System.out.println("Expiration: " + claims.getExpiration());
}

To sum it up…

We tried to make it very easy to both construct and verify JWTs using JSON Web Token for Java. You only need to specify the data you want to encode and sign it with a key. Later, with that same key you can verify the authenticity of the token and decode it. The benefits of using JWT greatly exceed the time and effort of implementing them. Give it a try and you will have a hassle-free and more secure application.

Last but not least, do not forget to use SSL when communicating with remote peers since the token will be travelling over the wire on every request.

Please leave your comments below and check out our new Spring Boot Support and Java Servlet Support. We’re investing heavily in making authentication, user management, and single sign-on across Java applications easy, free and secure. You can read more about Stormpath user management for the JVM.

New Node.js Release: User Management & Authentication for Loopback

$
0
0

Loopback Authentication

If you’ve been building Node.js applications for a while, you’ve likely heard of Loopback — it’s a very popular Node.js framework for building API services.

I’m a huge fan of Loopback, as I’ve found it a really quick and convenient way to build REST APIs quickly in the past.

With our brand new loopback-stormpath library, you can now use all of Stormpath’s amazing user management tools to secure your user data, easily manage your users via our clean web interface, and scale your Loopback APIs to infinityyyyy and beyond!

Loopback it has tons of really nice integrations:

  • It auto-generates Swagger 2.0 compliant API services from your data models. This means you can build an API REALLY fast with very little work.
  • Javascript client libraries for consuming the API, especially with Angular JS.
  • Excellent mobile SDKs so you can build nice Android and iOS apps that use your REST API as the backend.
  • Nice command line tools for generating data models quickly using a number of popular databases.
  • It has built-in monitoring and deployment tools to speed deployment.
  • And much more =)

The goal for loopback-stormpath is to extend Loopback with Stormpath’s user and API authentication and other features, so all Loopback developers can have robust authentication and user functionality in only a few minutes. This release is the first step.

How The Loopback-Stormpath User Model Works

While Loopback provides a built-in user model that you can use to create / store / manage users in your own user database, our new loopback-stormpath library offloads your user store to Stormpath, which gives you a number of additional user management features and benefits:

  • All of your users are stored in a central, easy-to-access user store, regardless of what language you’re using. This makes it easy to connect multiple applications to a common user database, and also standardizes the user functionality across your apps – so you don’t have to reinvent the user wheel with each new product.
  • Support for more complex user models: create administrators, manage users, manage groups and permissions, and build complex user hierarchies not normally possible.
  • Built in data security and maintenance in the Stormpath system.
  • API authentication support, as well as all the other features of our Node.js library.

Getting Started with Loopback-Stormpath

Using the new loopback-stormpath library is quite simple. Here’s what you need to do after creating a new Loopback project.

Firstly, install the library via npm:

$ npm install loopback-stormpath --save

Secondly, modify your server/server.js file, and add the following import at the top:

var stormpath = require('loopback-stormpath');

Next, in your server/server.js file, directly before the boot(app, __dirname); line, add the following:

// Initialize Stormpath.
stormpath.init(app);

This will initialize Stormpath’s middleware properly.

After that, you need to modify your server/model-config.json file and do the following:

  • Remove the built in User object completely.
  • Add the following StormpathUser definition:

    “StormpathUser”: { “dataSource”: “stormpath” }

Lastly, open up server/datasources.json and add the following:

"stormpath": {
  "name: "stormpath",
  "connector": "stormpath",
  "apiKeyId": "xxx",
  "apiKeySecret": "xxx",
  "applicationHref": "xxx"
}

You’ll need to fill in the three bottom values with your Stormpath credentials. If you don’t already have a Stormpath account, go make one! https://api.stormpath.com/register

That’s it! You’ve now got Stormpath installed and configured properly, so you can manage your users as you would with any other Stormpath-backed application.

Upcoming Features for loopback-stormpath

Right now, this is an early alpha release. This means that it’s brand new, and might contain bugs!

If you find any bugs or issues, please file them on the Github repo! We love bug reports as well as feature requests.

Over the next few months, we will improve the integration so it supports all ORM features, as well as build out new library documentation, and include first-class front-end support.

There’s a LOT more to come in the future, so please go check it out now and let me know what you think so far!

Also! I just wanted to give a huge shout out to everyone at Strongloop who helped me with this along the way. Big props to the entire Strongloop team — everyone there was amazingly helpful =)

Happy Hacking,

-Randall


How to Write Middleware for Express.js Apps

$
0
0

Express.js is a lightweight HTTP framework for node.js that allows you to create a variety of applications, from a standard website to a REST API. It gets out of your way with a minimal API that you fill in with your custom needs.

The structure of ExpressJS is this: everything is “middleware”. If you’ve built an Express app, you’ve probably seen code like this:

app.use(bodyParser())
app.use(cookieParser())

This code wires middleware to your application. So what is Middleware?

What is Middleware?

Middleware is a function that receives the request and response objects of an HTTP request/response cycle. It may modify (transform) these objects before passing them to the next middleware function in the chain. It may decide to write to the response; it may also end the response without continuing the chain.

In other frameworks “middleware” is called “filters”, but the concept is the same: a request, response, and some transformation functions.

A very simple middleware function looks like this:

function logger(req,res,next){
  console.log(new Date(), req.method, req.url);
  next();
}

This is middleware at its simplest: a function with a signature of (req, res, next). In this particular example, a simple logger prints some information about these requests to the server console, and then continues the chain by calling next().

The job of Express is to manage your chain of middleware functions. All middleware should achieve three things:

  • It should be a function that does something awesome
  • It’s well-documented
  • It can be easily mixed into your existing Express application

The “Hello, World!” of Middleware

As you write your own middleware you will run into some pitfalls, but fear not! I will cover them in this article, so you know if you’ve fallen into one. :)

In our example application, we want two simple things to happen:

  • Say “hello” and “goodbye” on all the responses.
  • Log all the requests.

Let’s get started! Here is a basic shell of an Express application:

var express = require('express');

var app = express();

var server = app.listen(3000);

This Express application doesn’t do anything by itself; you need to add some middleware! We’ll add our logger (the one you saw in the introduction):

app.use(logger);

Good to go, right? When we run our server and make a request of it (using Curl in the terminal), we should see a log statement printed in the server console. But if you try, you’ll see this from your request:

$ curl http://localhost:3000/
Cannot GET /
$

And this from your server:

Mon Mar 23 2015 11:05:04 GMT-0700 (PDT) 'GET' '/'

We saw the server logging, but Curl gets a ‘Not Found’ error. What happened?

Pitfall #1 – “Not Found” means “Nothing else to do”

While we did the good thing of calling next(), no other middleware has been registered and there is nothing else for Express to do!

Because we have not ended the response, and there are no other middleware functions to run, Express kicks in with a default “404 Not Found” response.

The Solution: end your responses via res.end(). We’ll cover that in a later section.

Saying Hello

We’re going to write a new middleware function, named hello, and add this to our app. First, the function:

function hello(req,res,next){
  res.write('Hello \n');
  next();
}

Then add it to your middleware chain:

app.use(logger);
app.get('/hello',hello);

Notice the difference between use and get? These mean different things in Express.js:

  • use means “Run this on ALL requests”
  • get means “Run this on a GET request, for the given URL”

So what happens when we make a request for /hello? Here’s what Curl would do:

$ curl http://localhost:3000/hello
Hello

And what the server logs:

Mon Mar 23 2015 11:23:59 GMT-0700 (PDT) 'GET' '/hello'

Looks okay, right? But if you actually try this, you’ll notice that your Curl command never exits. Why? Read on…

Pitfall #2 – Not Ending The Response

Our hello middleware is doing the right thing and writing “Hello” to the response, but it never ends the response. As such, Express will think that someone else is going to do that, and will sit around waiting.

The solution: You need to end the response by calling res.end().

We wanted to say “Bye” as well, so let’s create some middleware for that. In that middleware we will end the response. Here’s what the bye middleware looks like:

function bye(req,res,next){
  res.write('Bye \n');
  res.end();
}

And now we’ll add it to the chain:

app.use(logger);
app.get('/hello',hello,bye);

Now everything will work the way we want! Here is what Curl gives us:

$ curl http://localhost:3000/hello
Hello
Bye
$

And the server will log our requests as well:

Mon Mar 23 2015 11:23:59 GMT-0700 (PDT) 'GET' '/hello'

Middleware: Mix and Match

When you create simple middleware functions with single concerns, you can build up an application from these smaller pieces.

Here’s a hypothetical situation: let’s say we’ve setup an easter-egg route on our server, named /wasssaaa (rather than hello). Of course, we want to know how many people hit this route, because that’s really quite interesting. But we don’t want to know if someone is hitting the hello route, because that’s not very interesting.

Besides, our marketing team can tell us that information from their analytics system (but they don’t know about our easter egg! Ha!)

We would re-write our midddleware wiring to look like this:

app.get('/hello',hello,bye);

app.get('/wasssaaa',logger,hello,bye);

This removed the global app.use(logger) statement, and added it to just the /wasssaaa route. Brilliant!

Express,js Routers

Express.js has a feature called Routers – mini Express applications that nest within each other. This pattern is a great way of breaking up the major components of your application.

A typical situation is this: you have a single Express server, but it does two things:

  • It serves a few basic pages, such as a home page and user registration system
  • It serves an API that your customers use to access their information, perhaps from mobile applications, an Angular application, or some other service

The code and dependencies for the web pages are drastically different from the API service, and you typically divide up that code. You can also divide them into separate Express routers!

Hello World, with Routers

Following the situation above, let’s build a simple server that says Hello! to everyone on our website AND our API, but only logs requests for the API service. That simple app might look like this:

var app = express();

var apiRouter = express.Router();

apiRouter.use(logger);

app.use(hello,bye);

app.use('/api',apiRouter);

We’ve separated our API service by defining it as an Express router, and then attaching that router to the /api URL of our main Express application.

What happens when we run this? Here’s what Curl reports:

$ curl http://localhost:3000/
Hello
Bye

$ curl http://localhost:3000/api/hello
Hello
Bye
$

Looking good, right? But what does the server have to say?

...

Hmm.. it doesn’t say anything! What happened??

Pitfall #3: Ordering of Middleware is Important

Express.js views middleware as a chain, and it just keeps going down the chain until a response is ended or it decides there is nothing left to do. For this reason, the order in which you register the middleware is very important.

In the last example we registered the bye middleware before we attached the apiRouter. Because of this, the bye middleware will be invoked first. Our bye middleware ends the response (without calling next), so our chain ends and the router is never reached!

The Solution: Re-order your middleware. In this situation, we simply need to register the apiRouter first:

app.use('/api',apiRouter);

app.use(hello,bye)

With this, we now get what we expect. Curl reports the same as before:

$ curl http://localhost:3000/
Hello
Bye
$ curl http://localhost:3000/api/hello
Hello
Bye
$

But now our server logs the API request:

Mon Mar 23 2015 14:48:59 GMT-0700 (PDT) 'GET' '/hello'

But notice something curious here: even though we have requested /api/hello, the logger reports /hello. Hmm…

Pitfall #4: URLs Are Relative to a Router

A router doesn’t really know that it’s being attached to another application. If you really need to know the exact URL, you should use req.originalUrl. Or if you’re curious about where this route has been attached, use req.baseUrl (which would be /api in this example).

Debugging Middleware

In this article I’ve shown you some of the common pitfalls with Express.js middleware. This certainly will help you as you write your own middleware, but what about all that third party middleware that you put into your Express application?

If you’re using 3rd party middleware and it’s not working as expected, you’re going to have to stop and debug.

First, look at the source code of the module. Scan it for places where it accepts (res,res,next) and look for places where it calls next() or res.end(). This will give you a general idea of what the flow control looks like, and might help you figure out the issue.

Otherwise, check out Node Inspector and go down the step-by-step debugging path.

So Much Middleware, So Little Time!

I’ll wrap this article with this advice: there’s a lot of middleware out there! Start browsing NPM for great node.js middleware! If you want some inspiration, here are some we love:

  • Morgan is a fully-featured logger for Express.js. It does much more than our trivial example!

  • Helmet is a collection of smaller modules, culminating in a one-stop-shop for securing your web application. You should install this one right now.

And of course (we’re a little biased), but we think Stormpath Express will be a great addition to your Express.js application. It handles all the authentication and user management for your application, so you don’t need to build out user infrastructure from scratch. It takes about 15 minutes to get a full authentication system for Express with this tutorial – including all the login screens.

With that.. happy coding! Feel free to leave comments and questions below. :)

   

What the Heck is OAuth?

$
0
0

Stormpath spends a lot of time building authentication services and libraries, we’re frequently asked by developers (new and experienced alike): “What the heck is OAuth?”.

There’s a lot of confusion around what OAuth actually is.

Some people consider OAuth a login flow (like when you sign into an application with Google Login), and some people think of OAuth as a “security thing”, and don’t really know much more than that.

I’m going to walk you through what OAuth is, explain how Oauth works, and hopefully leave you with a sense of how and where Oauth can benefit your application.

What Is OAuth?

To begin at a high level, OAuth is not an API or a service: it is an open standard for authorization and any developer can implement it.

OAuth is a standard that applications (and the developers who love them) can use to provide client applications with a ‘secure delegated access’. OAuth works over HTTP and authorizes Devices, APIs, Servers and Applications with access tokens rather than credentials, which we will go over in depth below.

There are two versions of OAuth: OAuth 1.0a and OAuth2. These specifications are completely different from one another, and cannot be used together: there is no backwards compatibility between them.

Which one is more popular? Great question! Nowadays (at this time of writing), OAuth2 is no doubt the most widely used form of OAuth. So from now on, whenever I write just “OAuth”, I’m actually talking about OAuth2 — as it is most likely what you’ll be using.

Now — onto the learning!

What Does OAuth Do?

OAuth is basically a protocol that supports authorization workflows. What this means is that it gives you a way to ensure that a specific user has permissions to do something.

That’s it.

OAuth isn’t meant to do stuff like validate a user’s identity — that’s taken care of by an Authentication service. Authentication is when you validate a user’s identity (like asking for a username / password to log in), whereas authorization is when check to see what permissions an existing user already has.

Just remember that OAuth is a protocol for authorization.

How OAuth Works

There are 4 separate modes of OAuth, which are called grant types. Each mode serves a different purpose, and is used in a different way. Depending on what type of service you are building, you might need to use one or more of these grant types to make stuff work.

Let’s go over each one separately.

The Authorization Code Grant Type

The authorization code OAuth grant type is meant to be used on web servers. You’ll want to use the authorization code grant type if you are building a web application with server-side code that is NOT public. If want to implement an OAuth flow in a server-side web framework like Express.js, Flask, Django, Ruby on Rails, an Authorization Code is the way to go.

Here’s how it works:

  • An anonymous user visits your website.
  • They want to log into your site using a Third-Party Identity, stored somewhere else: Google, Facebook, your own OAuth service that you created, etc.
  • They click a “Log In” button on your site and are redirected to their identify provider’s website (eg: Google, Facebook, etc.), and are prompted to accept certain permissions.
  • If they accept these permissions, the identity provider will redirect the user BACK to your web application along with an authorization code.
  • Your web server will then make a request to the identity provider’s API with the authorization code you were just given, and you’ll then be given an access token you can use to actually retrieve this user’s information.

Here’s how it typically looks:

Facebook Login

How to Use Authorization Code Grant Types

You’ll basically create a login button on your login page with a link that looks something like this:

https://login.blah.com/oauth?response_type=code&client_id=xxx&redirect_uri=xxx&scope=email

When the user clicks this button they’ll visit login.blah.com where they’ll be prompted for whatever permissions you’ve requested.

After accepting the permissions, the user will be redirected to back to your site, at whichever URL you specified in the redirect_uri parameter, along with an authorization code. Here’s how it might look:

https://yoursite.com/oauth/callback?code=xxx

You’ll then read in the code querystring value, and exchange that for an access token using the provider’s API:

POST https://api.blah.com/oauth/token?grant_type=authorization_code&code=xxx&redirect_uri=xxx&client_id=xxx&client_secret=xxx

NOTE: The client_id and client_secret stuff you see in the above examples are provided by the identity provider. When you create a Facebook or Google app, for instance, they’ll give you these values.

Once that POST request has successfully completed, you’ll then receive an access token which you can use to make real API calls to retrieve the user’s information from the identity provider.

The Implicit Grant Type

The implicit grant type is meant to be used for client-side web applications (like React.js or Angular.js) that don’t have a server-side component — or any sort of mobile application that can use a mobile web browser.

Implicit grants ideal for client-side web applications and mobile apps because this grant type doesn’t require you to store any secret key information at all — this means you can log someone into your site / app WITHOUT knowing what your application’s client_secret is.

Here’s how it works:

  • An anonymous user visits your website or opens your mobile app.
  • They want to log into your site using a Third-Party Identity, stored somewhere else: Google, Facebook, your own OAuth service that you created, etc.
  • They click a “Log In” button on your site / app and are redirected to theiridentify provider’s website (eg: Google, Facebook, etc.), and are prompted to accept certain permissions.
  • If they accept these permissions, the identity provider will redirect the user BACK to your web application along with an access token.
  • You can these use this access token to actually retrieve this user’s information.

Here’s how it typically looks:

Facebook Login

How to Use the Implicit Grant Type

You’ll basically create a login button on your login page that contains a link that looks something like this:

https://login.blah.com/oauth?response_type=token&client_id=xxx&redirect_uri=xxx&scope=email

When the user clicks this button they’ll visit login.blah.com where they’ll be prompted for whatever permissions you’ve requested.

After accepting the permissions, the user will be redirected to back to your site, at whichever URL you specified in the redirect_uri parameter, along with an access token. Here’s how it might look:

https://yoursite.com/oauth/callback?token=xxx

You’ll then read in the token querystring value which you can use to make real API calls to retrieve the user’s information from the identity provider.

NOTE: The client_id stuff you see in the above examples are provided by the identity provider. When you create a Facebook or Google app, for instance, they’ll give you these values.

The Password Credentials Grant Type

The password credentials grant type is meant to be used for first class web applications OR mobile applications. This is ideal for official web and mobile apps for your project because you can simplify the authorization workflow by ONLY asking a user for their username and password, as opposed to redirecting them to your site, etc.

What this means is that if you have built your own OAuth service (login.yoursite.com), and then created your own OAuth client application, you could use this grant type to authenticate users for your native Android, iPhone, and web apps.

But here’s the catch: ONLY YOUR native web / mobile applications can use this method! Let’s say you are Google. It would be OK for you to use this method to authenticate users in the official Google Android and iPhone apps, but NOT OK for some other site that uses Google login to authenticate people.

The reason here is this: by using the password credentials grant type, you’ll essentially be collecting a username and password from your user directly. If you allow a third-party vendor to do this, you run the risk that they’ll store this information and use it for bad purposes (nasty!).

Here’s how it works:

  • An anonymous user visits your website or opens your mobile app.
  • They want to log into your site / app using their identity (stored in the OAuth service that you created).
  • They input their username and password into your site / app, and you then validate this information via an API call and receive an access token.
  • You can these use this access token to actually retrieve this user’s information.

Here’s how it looks:

Facebook App Login

How to Use the Password Credentials Grant Type

You’ll basically create an HTML form of some sort on your login page that accepts the user’s credentials — typically username and password.

You’ll then accept the user’s credentials, and POST them to your identity service using the following request format:

POST https://login.blah.com/oauth/token?grant_type=password&username=xxx&password=xxx&client_id=xxx

You’ll then receive an access token in the response which you can use to make real API calls to retrieve the user’s information from your OAuth service.

The Client Credentials Grant Type

The client credentials grant type is meant to be used for application code.

You’ll want to use the client credentials grant type if you are building an application that needs to perform non-user related tasks. For instance, you might want to update your application’s metadata — read in application metrics (how many users have logged into your service?) — etc.

What this means is that if you’re building an application (like a background process that doesn’t interact with a user in a web browser), this is the grant type for you!

Here’s how it works:

  • Your application makes a request to the identity provider’s API service using it’s application credentials.
  • It receives an access token back, which can be used to make API requests.

How to Use The Client Credentials Grant Type

You’ll fire off a single API request to the identity provider that looks something like this:

POST https://login.blah.com/oauth/token?grant_type=client_credentials&client_id=xxx&client_secret=xxx

You’ll then receive an access token in the response which you can use to make real API calls to retrieve information from the identity provider’s API service.

NOTE: The client_id and client_secret stuff you see in the above examples are provided by the identity provider. When you create a Facebook or Google app, for instance, they’ll give you these values.

Is OAuth2 Secure?

Let’s talk about OAuth security real quick: “Is OAuth2 secure?”

The answer is, unquestionably, NO! OAuth2 is NOT (inherently) SECURE. Numerous, well-known security issues with the protocol that have yet to be addressed.

If you’d like to quickly get the low down on all of the OAuth2 security issues, I’d recommend this article, written by the famed security researcher Egor Homakov.

So, should you use it anyway? That’s a huge topic we have covered briefly in our post Secure Your API The Right Way. If you need to secure an API, this post will help you choose the right protocol.

Key Takeaways

Hopefully this article has provided you with some basic OAuth knowledge. I realize there’s a lot to it, but here are some key things to remember:

Know What Grant Type to Use

If you’re building an application that integrates with another provider’s login stuff (Google, Facebook, etc.) — be sure to use the correct grant type for your situation.

If you’re building….

  • A server-side web app: use authorization code.
  • A client-side web app (or mobile app): use implicit.
  • An integration with an OAuth service you built yourself, use password credentials.
  • An application that doesn’t interact with user data: use client credentials.

Don’t Use OAuth2 for Sensitive Data

If you’re building an application that holds sensitive data (like social security numbers, etc.) — consider using OAuth 1.0a instead of OAuth2 — it’s much more secure.

Use OAuth if You Need It

You should only use OAuth if you actually need it. If you are building a service where you need to use a user’s private data that is stored on another system — use OAuth. If not — you might want to rethink your approach!

There are other forms of authentication for both websites and API services that don’t require as much complexity, and can offer similar levels of protection in certain cases.

Namely: HTTP Basic Authentication and HTTP Digest Authentication.

Use Stormpath for OAuth

Our service, Stormpath, offers the password and client credential workflows as a service that you can add to your application quickly, easily, and securely. Read how to:

If you’ve got any questions, we can be reached easily by email.

And… That’s all! I hope you enjoyed yourself =)

Five Practical Tips for Building Your Java API

$
0
0

Increasingly, Java developers are building APIs for their own apps to consume as part of a micro-services oriented architecture, or for consumption by external services. At Stormpath we do both, and we’re expert in the “complications” this can create for a development team. Many teams find it difficult to manage authentication and access control to their APIs, so we want to share a few architectural principles and tips to make it easier to manage access to your Java API.

For a bit of context: Stormpath at its core, is a Java-based REST+JSON API, built on the Spring Framework using Apache Shiro as an application security layer. We store user credentials and data on behalf of other companies, so for us security is paramount. Thus, my first requirement for these tips is that they help manage access to your Java API securely.

We also evaluated tips based on whether they work well in a services-based architecture like ours, whether they benefit both internal and public APIs, and whether they offer developers increased speed and security.

On to the fun part!

Secure Authentication Requests with TLS

I like to think of an API as a super-highway of access to your application. Allowing basic authentication requests without TLS support is like allowing people to barrel down your highway… drunk… in a hydrogen powered tank… When that requests lands, it has the potential to wreak havoc in your application.

We have written extensively on how to secure your API and why you shouldn’t use password-based authentication in an API. When in doubt, at a bare minimum, use Basic Authentication with TLS.

How you implement TLS/SSL is heavily dependent on your environment – both Spring Security and Apache Shiro support it readily. But I think devs frequently omit this step because it seems like a lot of work. Here is a code snippet that shows how a servlet retrieves certificate information:

public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
..........
X509Certificate[] certs = (X509Certificate[]) req.getAttribute("javax.servlet.request.X509Certificate");
.........

Not a lot of work. I’ve posted some links to different tutorials at the bottom if you’re new to TLS or want to ensure you’re doing it right. Pro tip: Basic Auth with TLS is built into Stormpath SDKs.

Build Your Java Web Service with Spring Boot

Spring Boot is a fantastic way to get a Java API into production without a lot of setup. As one blogger wrote, “It frees us from the slavery of complex configuration files, and helps us to create standalone Spring applications that don’t need an external servlet container.” Love. It.

There are a ton of tutorials (see below) on building Restful Web services with Spring Boot, and the great thing about taking this approach is that much of the security is pre-built, either through a sample application or a plugin. SSL in Spring Boot, for instance, is configured by adding a few lines to your application.properties file:

server.port = 8443 server.ssl.key-store = classpath:keystore.jks server.ssl.key-store-password = secret server.ssl.key-password = another-secret

Stormpath also offers Spring Boot Support, so you can easily use Stormpath’s awesome API authentication and security features in your Spring Boot App.

Use a Java API to Visualize Data…About your Java API

So meta. Because APIs are (potentially, hopefully!) managing lots of data, and the availability of that data is critical to downstream connections. For APIs in production, analytics and monitoring are critical. Most users won’t warn you before they start load testing, and good usage insight helps you plan your infrastructure as your service grows.

Like other tech companies (Coursera, Indeed, BazaarVoice), we use DataDog to visualize our metrics and events. They have strong community support for Java APIs, plus spiffy dashboards.

Also, we project our dashboards on a wall in the office. This certainly doesn’t replace pager alerts on your service, but it helps make performance transparent to the whole team. At Stormpath, this has been a great way to increase and inform discussion about our service delivery and infrastructure – across the team.

Encourage Your Users To Secure Their API Keys Properly

The most terrifying thing that happens to me at work is when someone emails me their Stormpath API key. It happens with shocking frequency, so we went on a fact-finding mission and discovered a scary truth: even awesome devs use their email to store their API key and/or password… and occassionally accidentally hit send. When these land in my inbox, a little part of me dies.

Some ideas: – Make your API key button red. I’m not above scaring people with a red button. – At Stormpath we encourage storing the API key/secret in a file only readable by the owner. You can instruct your users to do this via the terminal, regardless of what language they are working in. Our instructions look like this (for an api key named apiKey.properties):

Save this file in a secure location, such as your home directory, in a hidden .stormpath directory. For example:

$ mkdir ~/.stormpath

$ mv ~/Downloads/apiKey.properties ~/.stormpath/

Change the file permissions to ensure only you can read this file. For example:

$ chmod go-rwx ~/.stormpath/apiKey.properties

Stormpath Makes API Authentication, Tokens and Scopes Easy

Finally, a shameless plug: Stormpath automates a lot of functionality for Java WebApps. Our API security features generate your API keys, manage authentication to your API, allow you to control what users with keys have access to via groups and custom permissions, and manage scopes and tokens.

We lock down access with awesome Java security infrastructure. Stormapth for API Security and Authentication and our API Authentication Guide. These features work with all our Java SDKs for Servlets, Spring Boot, Apache Shiro and Spring Security and will save you tons of time.

As ever, feel free to comment if we missed anything or you have additional suggestions. If you want help with your Stormpath setup, email support@stormpath.com and a technical human will get back to you quickly.

Resources

TLS Tutorials & Sample Apps

Spring Boot your REST API service

REST VS SOAP: When Is REST Better?

$
0
0

While the SOAP (Simple Object Access Protocol) has been the dominant approach to web service interfaces for a long time, REST (Representational State Transfer) is quickly winning out and now represents over 70% of public APIs.

REST is simpler to interact with, particularly for public APIs, but SOAP is still used and loved for specific use cases. REST and SOAP have important, frequently overlooked differences, so when building a new web service, do you know which approach is right for your use case?

Spoiler Alert: USE REST+JSON. Here’s Why…

SOAP: The Granddaddy of Web Services Interfaces

SOAP is a mature protocol with a complete spec, and is designed to expose individual operations – or pieces of operations – as web services. One of the most important characteristics of SOAP is that it uses XML rather than HTTP to define the content of the message.

The Argument For SOAP

SOAP is still offered by some very prominent tech companies for their APIs (Salesforce, Paypal, Docusign). One of the main reasons: legacy system support. If you built a connector between your application and Salesforce back in the day, there’s a decent probability that connection was built in SOAP.

There are a few additional situations:

  • SOAP is good for applications that require formal contracts between the API and consumer, since it can enforce the use of formal contracts by using WSDL (Web Services Description Language).
  • Additionally, SOAP has built in WS-Reliable messaging to increase security in asynchronous execution and processing.
  • Finally, SOAP has built-in stateful operations. REST is naturally stateless, but SOAP is designed support conversational state management.

Some would argue that because of these features, as well as support for WS_AtomicTransaction and WS_Security, SOAP can benefit developers when there is a high need for transactional reliability.

REST: The Easy Way to Expose Web Services

And yet, most new APIs are built in REST+JSON. Why?

First, REST is easy to understand: it uses HTTP and basic CRUD operations, so it is simple to write and document. This ease of use also makes it easy for other developers to understand and write services against.

REST also makes efficient use of bandwidth, as it’s much less verbose than SOAP. Unlike SOAP, REST is designed to be stateless and REST reads can be cached for better performance and scalability.

REST supports many data formats, but the predominant use of JSON means better support for browser clients. JSON sets a standardized method for consuming API payloads, so you can take advantage of its connection with JavaScript and the browser. Read our best practices on REST+JSON API Design Here.

Case 1: Developing a Public API

REST focuses on resource-based (or data-based) operations, and inherits its operations (GET, PUT, POST, DELETE) from HTTP. This makes it easy for both developers and web-browsers to consume it, which is beneficial for public APIs where you don’t have control over what’s going on with the consumer. Simplicity is one of the strongest reasons that major companies like Amazon and Google are moving their APIs from SOAP to REST.

Case 2: Extensive Back-and-Forth Object Information

APIs used by apps that require a lot of back-and-forth messaging should always use REST. For example, mobile applications. If a user attempts to upload something to a mobile app (say, an image to Instagram) and loses reception, REST allows the process to be retried without major interruption, once the user regains cell service.

However, with SOAP, the same type of service would require more initialization and state code. Because REST is stateless, the client context is not stored on the server between requests, giving REST services the ability to be retried independently of one another.

Case 3: Your API Requires Quick Developer Response

REST allows easy, quick calls to a URL for fast return responses. The difference between SOAP and REST in this case is complexity—-SOAP services require maintaining an open stateful connection with a complex client. REST, in contrast, enables requests that are completely independent from each other. The result is that testing with REST is much simpler.

Helpfully, REST services are now well-supported by tooling. The available tools and browser extensions make testing REST services continually easier and faster.

Developer Resources for REST+JSON API Development

Stormpath is an REST+JSON API-based authentication and user management system for your web and mobile services and APIs. We <3 REST+JSON.

If you want learn more about how to build, design, and secure REST+JSON APIs, here are some developer tutorials and explainer blogposts on REST+JSON API Development:

Easy Unified Identity

$
0
0

Stormpath + OAuth Opengraph

Unified Identity is the holy grail of website authentication. Allowing your users to log into your website through any mechanism they want, while always having the same account details, provides a really smooth and convenient user experience.

Unfortunately, unified identity can be tricky to implement properly! How many times have you logged into a website with Google Login, for instance, then come back to the site later and created an account with email / password only to discover you now have two separate accounts! This happens to me all the time and is really frustrating.

In a perfect world, a user should be able to log into your website with:

  • Google
  • Facebook
  • Twitter
  • Email or Username and Password
  • Any other OAuth provider

And always have the same account / account data — regardless of how they choose to log in at any particular point in time.

Unified Identity Management

Over the past few months we’ve been collaborating with our good friends over at OAuth.io to build a unified identity management system that combines OAuth.io’s broad support for social login providers with Stormpath’s powerful user management, authorization and data security service.

Here’s how it works:

You’ll use OAuth.io’s service to connect your Google, Facebook, Twitter, or any other social login services.

You’ll then use Stormpath to store your user accounts and link them together to give you a single, unified identity for every user.

It’s really simple to do and works very well!

And because OAuth.io supports over 100 separate OAuth providers, you can allow your website visitors to log in with just about any service imaginable!

User Registration & Unification Demo

To see how it works, I’ve created a small demo app you can check out here: https://unified-identity-demo.herokuapp.com/

Everything is working in plain old Javascript — account registration, unified identity linking, etc.

Go ahead and give it a try! It looks something like this:

Unified Identity Demo

If you’d like to dig into the code yourself, or play around with the demo app on your own, you can visit our project repository on Github here: https://github.com/stormpath/unified-identity-demo

If you’re a Heroku user, you can even deploy it directly to your own account by clicking the button below!

Deploy

Configure Stormpath + OAuth.io Integration

Let’s take a look at how simple it is to add unified identity to your own web apps now.

Firstly, you’ll need to go and create an

Don’t worry — both are totally free to use.

Next, you’ll need to create a Stormpath Application.

Stormpath Create Application

Next, you’ll need to log into your OAuth.io Dashboard, visit the “Users Overview” tab, and enter your Stormpath Application name and credentials.

OAuth.io Stormpath Configuration

Finally, you need to visit the “Integrated APIs” tab in your OAuth.io Dashboard and add in your Google app, Facebook app, and Twitter app credentials. This makes it possible for OAuth.io to easily handle social login for your web app:

OAuth.io Social Configuration

Show Me the Code!

Now that we’ve got the setup stuff all ready to go, let’s take a look at some code.

The first thing you’ll need to do is activate the OAuth.io Javascript library in your HTML pages:

<script src="https://stormpath.com/static/js/oauth.min.js"></script>
<script>
  OAuth.initialize("YOUR_OAUTHIO_PUBLIC_KEY");
</script>

You’ll most likely want to include this at the bottom of the <head> section in your HTML page(s). This will initialize the OAuth.io library.

Next, in order to register a new user via email / password you can use the following HTML / Javascript snippet:

<form onsubmit="return register()">
  <input id="firstName", placeholder="First Name", required>
  <input id="lastName", placeholder="Last Name", required>
  <input id="email", placeholder="Email", required, type="email">
  <input id="password", placeholder="Password", required, type="password">
  <button type="submit"> Register
</form>
<script>
  function register() {
    User.signup({
      firstname: document.getElementById('firstName').value,
      lastname: document.getElementById('lastName').value,
      email: document.getElementById('email').value,
      password: document.getElementById('password').value
    }).done(function(user) {
      // Redirect the user to the dashboard if the registration was
      // successful.
      window.location = '/dashboard';
    }).fail(function(err) {
      alert(err);
    });
    return false;
  }
</script>

This will create a new user account for you, with the user account stored in Stormpath.

Now, in order to log a user in via a social provider (Google, Facebook, Twitter, etc.) — you can do something like this:

<script>
  function link(provider) {
    var user = User.getIdentity();
    OAuth.popup(provider).then(function(p) {
      return user.addProvider(p);
    }).done(function() {
      // User identity has been linked!
    });
  }
</script>
<button type="button" onclick="link('facebook')">Link Facebook</button>
<button type="button" onclick="link('google')">Link Google</button>
<button type="button" onclick="link('twitter')">Link Twitter</button>

If a user clicks any of the three defined buttons above, they’ll be prompted to log into their social account and accept permissions — and once they’ve done this, they’ll then have their social account ‘linked’ to their normal user account that was previously created.

Once a user’s account has been ‘linked’, the user can log into any of their accounts and will always have the same account profile returned.

Nice, right?!

Simple Identity Management

Hopefully this quick guide has shown you how easy it can be to build unified identity into your next web application. With Stormpath and OAuth.io, it can take just minutes to get a robust, secure, user authentication system up and running.

To dive in, check out the demo project on github: https://github.com/stormpath/unified-identity-demo

Happy Hacking!

Viewing all 278 articles
Browse latest View live