OAuth2 Plugin for CloudFoundry UAA

Initial implementation  of a plugin that supports the
CloudFoundry UAA OAuth2 server protocol (see
https://github.com/cloudfoundry/uaa/blob/master/docs/UAA-APIs.rst)

UAA uses so-called JSON web tokens as access tokens,
which already contain the required user id and email
information. This makes an additional request for the
user detail information obsolete. JSON web tokens
have a signature that is verified by the service.
Both HMACSHA256 and SHA256withRSA signatures are
supported.

The plugin has been tested with UAA 2.4.0 but should work
also with older UAA versions.

Change-Id: I3a7c4a885b7dc7491c9092e9a340974b0a37748d
Signed-off-by: Michael Ochmann <michael.ochmann@sap.com>
diff --git a/.buckconfig b/.buckconfig
new file mode 100644
index 0000000..561d6eb
--- /dev/null
+++ b/.buckconfig
@@ -0,0 +1,13 @@
+[alias]
+  cfoauth = //:cfoauth
+  plugin = //:cfoauth
+
+[java]
+  src_roots = java, resources
+
+[project]
+  ignore = .git
+
+[cache]
+  mode = dir
+  dir = buck-out/cache
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..b4277e3
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,10 @@
+/.buckversion
+/.buckd
+/.watchmanconfig
+/buck-out
+/bucklets
+/target
+/.classpath
+/.project
+/.settings/org.maven.ide.eclipse.prefs
+/.settings/org.eclipse.m2e.core.prefs
diff --git a/BUCK b/BUCK
new file mode 100644
index 0000000..f20aa8a
--- /dev/null
+++ b/BUCK
@@ -0,0 +1,54 @@
+include_defs('//bucklets/gerrit_plugin.bucklet')
+include_defs('//bucklets/maven_jar.bucklet')
+define_license('scribe')
+
+gerrit_plugin(
+  name = 'cfoauth',
+  srcs = glob(['src/main/java/**/*.java']),
+  resources = glob(['src/main/**/*']),
+  manifest_entries = [
+    'Gerrit-PluginName: cfoauth',
+    'Gerrit-ApiType: plugin',
+    'Gerrit-ApiVersion: 2.12-SNAPSHOT',
+    'Gerrit-HttpModule: com.googlesource.gerrit.plugins.cfoauth.HttpModule',
+    'Gerrit-InitStep: com.googlesource.gerrit.plugins.cfoauth.InitOAuthConfig',
+    'Implementation-Title: Cloud Foundry UAA OAuth 2.0 Authentication Provider',
+    'Implementation-URL: https://gerrit-review.googlesource.com/#/admin/projects/plugins/cfoauth',
+  ],
+  deps = [
+    ':scribe'
+  ],
+  provided_deps = [
+    '//lib:guava',
+    '//lib:gson',
+    '//lib/commons:codec'
+  ],
+)
+
+# this is required for bucklets/tools/eclipse/project.py to work
+java_library(
+  name = 'classpath',
+  deps = [':cfoauth__plugin'],
+)
+
+java_test(
+  name = 'cfoauth_tests',
+  srcs = glob(['src/test/java/**/*.java']),
+  labels = ['cfoauth'],
+  deps = [
+    ':cfoauth__plugin',
+    ':scribe',
+    '//lib:junit',
+    '//lib:guava',
+    '//lib:gson',
+    '//lib/commons:codec'
+  ],
+)
+
+maven_jar(
+  name = 'scribe',
+  id = 'org.scribe:scribe:1.3.7',
+  sha1 = '583921bed46635d9f529ef5f14f7c9e83367bc6e',
+  license = 'scribe',
+  local_license = True,
+)
diff --git a/LICENSE b/LICENSE
new file mode 100644
index 0000000..11069ed
--- /dev/null
+++ b/LICENSE
@@ -0,0 +1,201 @@
+                              Apache License
+                        Version 2.0, January 2004
+                     http://www.apache.org/licenses/
+
+TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+1. Definitions.
+
+   "License" shall mean the terms and conditions for use, reproduction,
+   and distribution as defined by Sections 1 through 9 of this document.
+
+   "Licensor" shall mean the copyright owner or entity authorized by
+   the copyright owner that is granting the License.
+
+   "Legal Entity" shall mean the union of the acting entity and all
+   other entities that control, are controlled by, or are under common
+   control with that entity. For the purposes of this definition,
+   "control" means (i) the power, direct or indirect, to cause the
+   direction or management of such entity, whether by contract or
+   otherwise, or (ii) ownership of fifty percent (50%) or more of the
+   outstanding shares, or (iii) beneficial ownership of such entity.
+
+   "You" (or "Your") shall mean an individual or Legal Entity
+   exercising permissions granted by this License.
+
+   "Source" form shall mean the preferred form for making modifications,
+   including but not limited to software source code, documentation
+   source, and configuration files.
+
+   "Object" form shall mean any form resulting from mechanical
+   transformation or translation of a Source form, including but
+   not limited to compiled object code, generated documentation,
+   and conversions to other media types.
+
+   "Work" shall mean the work of authorship, whether in Source or
+   Object form, made available under the License, as indicated by a
+   copyright notice that is included in or attached to the work
+   (an example is provided in the Appendix below).
+
+   "Derivative Works" shall mean any work, whether in Source or Object
+   form, that is based on (or derived from) the Work and for which the
+   editorial revisions, annotations, elaborations, or other modifications
+   represent, as a whole, an original work of authorship. For the purposes
+   of this License, Derivative Works shall not include works that remain
+   separable from, or merely link (or bind by name) to the interfaces of,
+   the Work and Derivative Works thereof.
+
+   "Contribution" shall mean any work of authorship, including
+   the original version of the Work and any modifications or additions
+   to that Work or Derivative Works thereof, that is intentionally
+   submitted to Licensor for inclusion in the Work by the copyright owner
+   or by an individual or Legal Entity authorized to submit on behalf of
+   the copyright owner. For the purposes of this definition, "submitted"
+   means any form of electronic, verbal, or written communication sent
+   to the Licensor or its representatives, including but not limited to
+   communication on electronic mailing lists, source code control systems,
+   and issue tracking systems that are managed by, or on behalf of, the
+   Licensor for the purpose of discussing and improving the Work, but
+   excluding communication that is conspicuously marked or otherwise
+   designated in writing by the copyright owner as "Not a Contribution."
+
+   "Contributor" shall mean Licensor and any individual or Legal Entity
+   on behalf of whom a Contribution has been received by Licensor and
+   subsequently incorporated within the Work.
+
+2. Grant of Copyright License. Subject to the terms and conditions of
+   this License, each Contributor hereby grants to You a perpetual,
+   worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+   copyright license to reproduce, prepare Derivative Works of,
+   publicly display, publicly perform, sublicense, and distribute the
+   Work and such Derivative Works in Source or Object form.
+
+3. Grant of Patent License. Subject to the terms and conditions of
+   this License, each Contributor hereby grants to You a perpetual,
+   worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+   (except as stated in this section) patent license to make, have made,
+   use, offer to sell, sell, import, and otherwise transfer the Work,
+   where such license applies only to those patent claims licensable
+   by such Contributor that are necessarily infringed by their
+   Contribution(s) alone or by combination of their Contribution(s)
+   with the Work to which such Contribution(s) was submitted. If You
+   institute patent litigation against any entity (including a
+   cross-claim or counterclaim in a lawsuit) alleging that the Work
+   or a Contribution incorporated within the Work constitutes direct
+   or contributory patent infringement, then any patent licenses
+   granted to You under this License for that Work shall terminate
+   as of the date such litigation is filed.
+
+4. Redistribution. You may reproduce and distribute copies of the
+   Work or Derivative Works thereof in any medium, with or without
+   modifications, and in Source or Object form, provided that You
+   meet the following conditions:
+
+   (a) You must give any other recipients of the Work or
+       Derivative Works a copy of this License; and
+
+   (b) You must cause any modified files to carry prominent notices
+       stating that You changed the files; and
+
+   (c) You must retain, in the Source form of any Derivative Works
+       that You distribute, all copyright, patent, trademark, and
+       attribution notices from the Source form of the Work,
+       excluding those notices that do not pertain to any part of
+       the Derivative Works; and
+
+   (d) If the Work includes a "NOTICE" text file as part of its
+       distribution, then any Derivative Works that You distribute must
+       include a readable copy of the attribution notices contained
+       within such NOTICE file, excluding those notices that do not
+       pertain to any part of the Derivative Works, in at least one
+       of the following places: within a NOTICE text file distributed
+       as part of the Derivative Works; within the Source form or
+       documentation, if provided along with the Derivative Works; or,
+       within a display generated by the Derivative Works, if and
+       wherever such third-party notices normally appear. The contents
+       of the NOTICE file are for informational purposes only and
+       do not modify the License. You may add Your own attribution
+       notices within Derivative Works that You distribute, alongside
+       or as an addendum to the NOTICE text from the Work, provided
+       that such additional attribution notices cannot be construed
+       as modifying the License.
+
+   You may add Your own copyright statement to Your modifications and
+   may provide additional or different license terms and conditions
+   for use, reproduction, or distribution of Your modifications, or
+   for any such Derivative Works as a whole, provided Your use,
+   reproduction, and distribution of the Work otherwise complies with
+   the conditions stated in this License.
+
+5. Submission of Contributions. Unless You explicitly state otherwise,
+   any Contribution intentionally submitted for inclusion in the Work
+   by You to the Licensor shall be under the terms and conditions of
+   this License, without any additional terms or conditions.
+   Notwithstanding the above, nothing herein shall supersede or modify
+   the terms of any separate license agreement you may have executed
+   with Licensor regarding such Contributions.
+
+6. Trademarks. This License does not grant permission to use the trade
+   names, trademarks, service marks, or product names of the Licensor,
+   except as required for reasonable and customary use in describing the
+   origin of the Work and reproducing the content of the NOTICE file.
+
+7. Disclaimer of Warranty. Unless required by applicable law or
+   agreed to in writing, Licensor provides the Work (and each
+   Contributor provides its Contributions) on an "AS IS" BASIS,
+   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+   implied, including, without limitation, any warranties or conditions
+   of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+   PARTICULAR PURPOSE. You are solely responsible for determining the
+   appropriateness of using or redistributing the Work and assume any
+   risks associated with Your exercise of permissions under this License.
+
+8. Limitation of Liability. In no event and under no legal theory,
+   whether in tort (including negligence), contract, or otherwise,
+   unless required by applicable law (such as deliberate and grossly
+   negligent acts) or agreed to in writing, shall any Contributor be
+   liable to You for damages, including any direct, indirect, special,
+   incidental, or consequential damages of any character arising as a
+   result of this License or out of the use or inability to use the
+   Work (including but not limited to damages for loss of goodwill,
+   work stoppage, computer failure or malfunction, or any and all
+   other commercial damages or losses), even if such Contributor
+   has been advised of the possibility of such damages.
+
+9. Accepting Warranty or Additional Liability. While redistributing
+   the Work or Derivative Works thereof, You may choose to offer,
+   and charge a fee for, acceptance of support, warranty, indemnity,
+   or other liability obligations and/or rights consistent with this
+   License. However, in accepting such obligations, You may act only
+   on Your own behalf and on Your sole responsibility, not on behalf
+   of any other Contributor, and only if You agree to indemnify,
+   defend, and hold each Contributor harmless for any liability
+   incurred by, or claims asserted against, such Contributor by reason
+   of your accepting any such warranty or additional liability.
+
+END OF TERMS AND CONDITIONS
+
+APPENDIX: How to apply the Apache License to your work.
+
+   To apply the Apache License to your work, attach the following
+   boilerplate notice, with the fields enclosed by brackets "[]"
+   replaced with your own identifying information. (Don't include
+   the brackets!)  The text should be enclosed in the appropriate
+   comment syntax for the file format. We also recommend that a
+   file or class name and description of purpose be included on the
+   same "printed page" as the copyright notice for easier
+   identification within third-party archives.
+
+Copyright [yyyy] [name of copyright owner]
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+    http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
diff --git a/LICENSE-scribe b/LICENSE-scribe
new file mode 100644
index 0000000..7cea02d
--- /dev/null
+++ b/LICENSE-scribe
@@ -0,0 +1,22 @@
+The MIT License
+
+Copyright (c) 2010 Pablo Fernandez
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+THE SOFTWARE.
+
diff --git a/README.md b/README.md
new file mode 100644
index 0000000..dd37c20
--- /dev/null
+++ b/README.md
@@ -0,0 +1,15 @@
+Cloud Foundry UAA OAuth 2.0 Authentication Provider
+===================================================
+
+With this plugin Gerrit can use OAuth2 protocol to authenticate users
+accessing Gerrit's Web UI with a
+[CloudFoundry User Account and Authentication (UAA)](https://github.com/cloudfoundry/uaa)
+server. The `Sign In` link will redirect the user to the UAA login screen.
+
+For Git-over-HTTP communication users still need to generate and use
+an HTTP password.
+
+License
+-------
+
+Apache License 2.0
diff --git a/VERSION b/VERSION
new file mode 100644
index 0000000..cfb4e97
--- /dev/null
+++ b/VERSION
@@ -0,0 +1,4 @@
+# Used by BUCK to include "Implementation-Version" in plugin Manifest.
+# If this file doesn't exist the output of 'git describe' is used
+# instead.
+PLUGIN_VERSION = '2.12-SNAPSHOT'
diff --git a/lib/BUCK b/lib/BUCK
new file mode 100644
index 0000000..ab803a7
--- /dev/null
+++ b/lib/BUCK
@@ -0,0 +1,15 @@
+include_defs('//bucklets/maven_jar.bucklet')
+
+maven_jar(
+  name = 'gson',
+  id = 'com.google.code.gson:gson:2.3.1',
+  sha1 = 'ecb6e1f8e4b0e84c4b886c2f14a1500caf309757',
+  license = 'Apache2.0',
+)
+
+maven_jar(
+  name = 'guava',
+  id = 'com.google.guava:guava:18.0',
+  sha1 = 'cce0823396aa693798f8882e64213b1772032b09',
+  license = 'Apache2.0',
+)
diff --git a/lib/commons/BUCK b/lib/commons/BUCK
new file mode 100644
index 0000000..7aafa82
--- /dev/null
+++ b/lib/commons/BUCK
@@ -0,0 +1,9 @@
+include_defs('//bucklets/maven_jar.bucklet')
+
+maven_jar(
+  name = 'codec',
+  id = 'commons-codec:commons-codec:1.4',
+  sha1 = '4216af16d38465bbab0f3dff8efa14204f7a399a',
+  license = 'Apache2.0',
+  exclude = ['META-INF/LICENSE.txt', 'META-INF/NOTICE.txt'],
+)
diff --git a/lib/gerrit/BUCK b/lib/gerrit/BUCK
new file mode 100644
index 0000000..85b90a8
--- /dev/null
+++ b/lib/gerrit/BUCK
@@ -0,0 +1,12 @@
+include_defs('//bucklets/maven_jar.bucklet')
+
+VER = '2.12-SNAPSHOT'
+REPO = MAVEN_LOCAL
+
+maven_jar(
+  name = 'plugin-api',
+  id = 'com.google.gerrit:gerrit-plugin-api:' + VER,
+  license = 'Apache2.0',
+  attach_source = False,
+  repository = REPO,
+)
diff --git a/src/main/java/com/googlesource/gerrit/plugins/cfoauth/AccessToken.java b/src/main/java/com/googlesource/gerrit/plugins/cfoauth/AccessToken.java
new file mode 100644
index 0000000..3e9e4f3
--- /dev/null
+++ b/src/main/java/com/googlesource/gerrit/plugins/cfoauth/AccessToken.java
@@ -0,0 +1,124 @@
+// Copyright (C) 2015 The Android Open Source Project
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package com.googlesource.gerrit.plugins.cfoauth;
+
+import com.google.gerrit.reviewdb.client.AccountExternalId;
+
+import java.util.Objects;
+
+class AccessToken {
+
+  private final String value;
+
+  private final String externalId;
+  private final String username;
+  private final String emailAddress;
+  private final long expiresAt;
+
+  /**
+   * Creates an access token.
+   *
+   * @param value the raw value of the access token.
+   * @param username the name of the token owner.
+   * @param emailAddress the email address of the token owner.
+   * @param expiresAt time to expiration of this tokens in seconds
+   * since midnight January, 1st, 1970.
+   */
+  public AccessToken(String value, String username, String emailAddress,
+      long expiresAt) {
+    if (value == null) {
+      throw new IllegalArgumentException("token value must not be null");
+    }
+    if (username == null) {
+      throw new IllegalArgumentException("username must not be null");
+    }
+    if (emailAddress == null) {
+      throw new IllegalArgumentException("emailAddress must not be null");
+    }
+    this.value = value;
+    this.username = username;
+    this.externalId = AccountExternalId.SCHEME_EXTERNAL + username;
+    this.emailAddress = emailAddress;
+    this.expiresAt = expiresAt;
+  }
+
+  /**
+   * Returns the value of the access token.
+   */
+  public String getValue() {
+    return value;
+  }
+
+  /**
+   * Returns the external id of the token owner.
+   */
+  public String getExternalId() {
+    return externalId;
+  }
+
+  /**
+   * Returns the name of the token owner.
+   */
+  public String getUserName() {
+    return username;
+  }
+
+  /**
+   * Returns the email address of the token owner.
+   */
+  public String getEmailAddress() {
+    return emailAddress;
+  }
+
+  /**
+   * Returns the timestamp when this token will expire in seconds
+   * since midnight January, 1st, 1970.
+   */
+  public long getExpiresAt() {
+    return expiresAt;
+  }
+
+  /**
+   * Returns <code>true</code> if this token has already expired.
+   */
+  public boolean isExpired() {
+    return System.currentTimeMillis() > expiresAt * 1000;
+  }
+
+  @Override
+  public String toString() {
+    return "{'value':'" + value
+        + "','externalId':'" + externalId
+        + "','userName':'" + username
+        + "','emailAddress':'" + emailAddress
+        + "','expiresAt':" + expiresAt + "}";
+  }
+
+  @Override
+  public int hashCode() {
+    return value.hashCode();
+  }
+
+  @Override
+  public boolean equals(Object obj) {
+    if (this == obj) {
+        return true;
+    }
+    if (!(obj instanceof AccessToken)) {
+      return false;
+    }
+    return Objects.equals(value, ((AccessToken) obj).value);
+  }
+}
diff --git a/src/main/java/com/googlesource/gerrit/plugins/cfoauth/CFOAuthService.java b/src/main/java/com/googlesource/gerrit/plugins/cfoauth/CFOAuthService.java
new file mode 100644
index 0000000..dbc9e20
--- /dev/null
+++ b/src/main/java/com/googlesource/gerrit/plugins/cfoauth/CFOAuthService.java
@@ -0,0 +1,90 @@
+// Copyright (C) 2015 The Android Open Source Project
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package com.googlesource.gerrit.plugins.cfoauth;
+
+import com.google.common.base.CharMatcher;
+import com.google.gerrit.extensions.annotations.PluginName;
+import com.google.gerrit.extensions.auth.oauth.OAuthServiceProvider;
+import com.google.gerrit.extensions.auth.oauth.OAuthToken;
+import com.google.gerrit.extensions.auth.oauth.OAuthUserInfo;
+import com.google.gerrit.extensions.auth.oauth.OAuthVerifier;
+import com.google.gerrit.server.config.CanonicalWebUrl;
+import com.google.gerrit.server.config.PluginConfig;
+import com.google.gerrit.server.config.PluginConfigFactory;
+import com.google.inject.Inject;
+import com.google.inject.Provider;
+import com.google.inject.Singleton;
+
+import java.io.IOException;
+
+@Singleton
+class CFOAuthService implements OAuthServiceProvider {
+
+  private static final String OAUTH_VERSION = "2.0";
+  private static final String NAME = "Cloud Foundry UAA OAuth2";
+
+  private final UAAClient uaaClient;
+
+  @Inject
+  CFOAuthService(PluginConfigFactory cfgFactory,
+      @PluginName String pluginName,
+      @CanonicalWebUrl Provider<String> urlProvider) {
+    PluginConfig cfg = cfgFactory.getFromGerritConfig(pluginName);
+    String uaaServerUrl = CharMatcher.is('/')
+        .trimTrailingFrom(cfg.getString(InitOAuthConfig.SERVER_URL));
+    String redirectUrl = CharMatcher.is('/')
+        .trimTrailingFrom(urlProvider.get()) + "/oauth";
+    this.uaaClient = new UAAClient(uaaServerUrl,
+        cfg.getString(InitOAuthConfig.CLIENT_ID),
+        cfg.getString(InitOAuthConfig.CLIENT_SECRET),
+        cfg.getBoolean(InitOAuthConfig.VERIFIY_SIGNATURES, true),
+        redirectUrl);
+  }
+
+  @Override
+  public String getAuthorizationUrl() {
+    return uaaClient.getAuthorizationUrl();
+  }
+
+  @Override
+  public OAuthToken getAccessToken(OAuthVerifier rv) {
+    return getAsOAuthToken(uaaClient.getAccessToken(rv.getValue()));
+  }
+
+  @Override
+  public OAuthUserInfo getUserInfo(OAuthToken token) throws IOException {
+    return getAsOAuthUserInfo(uaaClient.toAccessToken(token.getToken()));
+  }
+
+  @Override
+  public String getVersion() {
+    return OAUTH_VERSION;
+  }
+
+  @Override
+  public String getName() {
+    return NAME;
+  }
+
+  private OAuthToken getAsOAuthToken(AccessToken accessToken) {
+    return new OAuthToken(accessToken.getValue(), null, null);
+  }
+
+  private OAuthUserInfo getAsOAuthUserInfo(AccessToken accessToken) {
+    return new OAuthUserInfo(accessToken.getExternalId(),
+        accessToken.getUserName(), accessToken.getEmailAddress(),
+        null, null);
+  }
+}
diff --git a/src/main/java/com/googlesource/gerrit/plugins/cfoauth/HMACSHA256SignatureVerifier.java b/src/main/java/com/googlesource/gerrit/plugins/cfoauth/HMACSHA256SignatureVerifier.java
new file mode 100644
index 0000000..898e782
--- /dev/null
+++ b/src/main/java/com/googlesource/gerrit/plugins/cfoauth/HMACSHA256SignatureVerifier.java
@@ -0,0 +1,65 @@
+// Copyright (C) 2015 The Android Open Source Project
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package com.googlesource.gerrit.plugins.cfoauth;
+
+import static java.nio.charset.StandardCharsets.US_ASCII;
+import static org.apache.commons.codec.binary.Base64.encodeBase64URLSafe;
+
+import java.security.InvalidKeyException;
+import java.security.NoSuchAlgorithmException;
+import java.text.MessageFormat;
+
+import javax.crypto.Mac;
+import javax.crypto.SecretKey;
+import javax.crypto.spec.SecretKeySpec;
+
+class HMACSHA256SignatureVerifier implements SignatureVerifier {
+
+  private static final String HS256 = "HS256";
+  private static final String HMAC_SHA256 = "HMACSHA256";
+
+  private final SecretKey secretKey;
+
+  public HMACSHA256SignatureVerifier(String secret) {
+    secretKey = new SecretKeySpec(secret.getBytes(US_ASCII), HMAC_SHA256);
+  }
+
+  @Override
+  public boolean verify(String content, String signature) {
+    Mac mac = null;
+    try {
+      mac = Mac.getInstance(HMAC_SHA256);
+    } catch (NoSuchAlgorithmException e) {
+      throw new IllegalStateException(
+          "Runtime does not support HMACSHA256 signatures", e);
+    }
+    try {
+      mac.init(secretKey);
+    } catch (InvalidKeyException e) {
+      throw new IllegalArgumentException(MessageFormat.format(
+          "Invalid HMACSHA256 secret: {0}", secretKey), e);
+    }
+    byte[] digest = mac.doFinal(content.getBytes(US_ASCII));
+    String actualSignature = new String(encodeBase64URLSafe(digest), US_ASCII);
+    return signature.equals(actualSignature);
+  }
+
+  @Override
+  public boolean supports(String algorithm) {
+    return HS256.equalsIgnoreCase(algorithm)
+        || HMAC_SHA256.equalsIgnoreCase(algorithm);
+  }
+
+}
diff --git a/src/main/java/com/googlesource/gerrit/plugins/cfoauth/HttpModule.java b/src/main/java/com/googlesource/gerrit/plugins/cfoauth/HttpModule.java
new file mode 100644
index 0000000..a8948dd
--- /dev/null
+++ b/src/main/java/com/googlesource/gerrit/plugins/cfoauth/HttpModule.java
@@ -0,0 +1,46 @@
+// Copyright (C) 2015 The Android Open Source Project
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package com.googlesource.gerrit.plugins.cfoauth;
+
+import com.google.gerrit.extensions.annotations.Exports;
+import com.google.gerrit.extensions.annotations.PluginName;
+import com.google.gerrit.extensions.auth.oauth.OAuthServiceProvider;
+import com.google.gerrit.httpd.plugins.HttpPluginModule;
+import com.google.gerrit.server.config.PluginConfig;
+import com.google.gerrit.server.config.PluginConfigFactory;
+import com.google.inject.Inject;
+
+class HttpModule extends HttpPluginModule {
+
+  private final PluginConfigFactory cfgFactory;
+  private final String pluginName;
+
+  @Inject
+  HttpModule(PluginConfigFactory cfgFactory,
+      @PluginName String pluginName) {
+    this.cfgFactory = cfgFactory;
+    this.pluginName = pluginName;
+  }
+
+  @Override
+  protected void configureServlets() {
+    PluginConfig cfg = cfgFactory.getFromGerritConfig(pluginName);
+    if (cfg.getString(InitOAuthConfig.CLIENT_ID) != null) {
+      bind(OAuthServiceProvider.class)
+       .annotatedWith(Exports.named(pluginName))
+       .to(CFOAuthService.class);
+    }
+  }
+}
diff --git a/src/main/java/com/googlesource/gerrit/plugins/cfoauth/InitOAuthConfig.java b/src/main/java/com/googlesource/gerrit/plugins/cfoauth/InitOAuthConfig.java
new file mode 100644
index 0000000..f0b76fb
--- /dev/null
+++ b/src/main/java/com/googlesource/gerrit/plugins/cfoauth/InitOAuthConfig.java
@@ -0,0 +1,57 @@
+// Copyright (C) 2015 The Android Open Source Project
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package com.googlesource.gerrit.plugins.cfoauth;
+
+import com.google.gerrit.extensions.annotations.PluginName;
+import com.google.gerrit.pgm.init.api.ConsoleUI;
+import com.google.gerrit.pgm.init.api.InitStep;
+import com.google.gerrit.pgm.init.api.Section;
+import com.google.inject.Inject;
+
+class InitOAuthConfig implements InitStep {
+  static final String PLUGIN_SECTION = "plugin";
+  static final String SERVER_URL = "serverUrl";
+  static final String CLIENT_ID = "clientId";
+  static final String CLIENT_SECRET = "clientSecret";
+  static final String VERIFIY_SIGNATURES = "verifySignatures";
+
+  static final String DEFAULT_SERVER_URL = "http://localhost:8080/uaa";
+  static final String DEFAULT_CLIENT_ID = "gerrit";
+
+  private final ConsoleUI ui;
+  private final Section cfg;
+
+  @Inject
+  InitOAuthConfig(ConsoleUI ui,
+      Section.Factory sections,
+      @PluginName String pluginName) {
+    this.ui = ui;
+    this.cfg = sections.get(PLUGIN_SECTION, pluginName);
+  }
+
+  @Override
+  public void run() throws Exception {
+    ui.header("Cloud Foundry UAA OAuth 2.0 Authentication Provider");
+    cfg.string("UAA server URL", SERVER_URL, DEFAULT_SERVER_URL);
+    cfg.string("Client id", CLIENT_ID, DEFAULT_CLIENT_ID);
+    cfg.passwordForKey("Client secret", CLIENT_SECRET);
+    cfg.set(VERIFIY_SIGNATURES, Boolean.toString(
+        ui.yesno(true, "Verify token signatures", VERIFIY_SIGNATURES)));
+  }
+
+  @Override
+  public void postRun() throws Exception {
+  }
+}
diff --git a/src/main/java/com/googlesource/gerrit/plugins/cfoauth/SHA265WithRSASignatureVerifier.java b/src/main/java/com/googlesource/gerrit/plugins/cfoauth/SHA265WithRSASignatureVerifier.java
new file mode 100644
index 0000000..2d175a3
--- /dev/null
+++ b/src/main/java/com/googlesource/gerrit/plugins/cfoauth/SHA265WithRSASignatureVerifier.java
@@ -0,0 +1,91 @@
+// Copyright (C) 2015 The Android Open Source Project
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package com.googlesource.gerrit.plugins.cfoauth;
+
+import static java.nio.charset.StandardCharsets.US_ASCII;
+import static org.apache.commons.codec.binary.Base64.decodeBase64;
+import static org.apache.commons.codec.binary.Base64.decodeInteger;
+
+import java.security.InvalidKeyException;
+import java.security.KeyFactory;
+import java.security.NoSuchAlgorithmException;
+import java.security.Signature;
+import java.security.SignatureException;
+import java.security.interfaces.RSAPublicKey;
+import java.security.spec.InvalidKeySpecException;
+import java.security.spec.RSAPublicKeySpec;
+import java.text.MessageFormat;
+
+class SHA265WithRSASignatureVerifier implements SignatureVerifier {
+
+  private static final String RSA = "RSA";
+  private static final String RS256 = "RS256";
+  private static final String SHA265_WITH_RSA = "SHA256withRSA";
+
+  private final RSAPublicKey publicKey;
+
+  public SHA265WithRSASignatureVerifier(String modulus,
+      String publicExponent) {
+    RSAPublicKeySpec publicKeySpec = new RSAPublicKeySpec(
+        decodeInteger(modulus.getBytes(US_ASCII)),
+        decodeInteger(publicExponent.getBytes(US_ASCII)));
+    KeyFactory keyFactory = null;
+    try {
+      keyFactory = KeyFactory.getInstance(RSA);
+    } catch (NoSuchAlgorithmException e) {
+      throw new IllegalStateException(
+          "Runtime does not support SHA256withRSA signatures", e);
+    }
+    try {
+      this.publicKey = (RSAPublicKey)keyFactory.generatePublic(publicKeySpec);
+    } catch (InvalidKeySpecException e) {
+      throw new IllegalArgumentException(MessageFormat.format(
+          "Invalid RSA public key specification: mod={1}, exp={2}",
+          publicKeySpec.getModulus(),
+          publicKeySpec.getPublicExponent()), e);
+    }
+  }
+
+  @Override
+  public boolean verify(String content, String signature) {
+    Signature rsa = null;
+    try {
+      rsa = Signature.getInstance(SHA265_WITH_RSA);
+    } catch (NoSuchAlgorithmException e) {
+      throw new IllegalStateException(
+          "Runtime does not support SHA256withRSA signatures", e);
+    }
+    try {
+      rsa.initVerify(publicKey);
+    } catch (InvalidKeyException e) {
+      throw new IllegalArgumentException(MessageFormat.format(
+          "Invalid public key: {0}", publicKey), e);
+    }
+    try {
+      rsa.update(content.getBytes(US_ASCII));
+      return rsa.verify(decodeBase64(signature.getBytes(US_ASCII)));
+    } catch (SignatureException e) {
+      throw new IllegalArgumentException(MessageFormat.format(
+          "Invalid signature: {0}", signature), e);
+    }
+  }
+
+  @Override
+  public boolean supports(String algorithm) {
+    return RS256.equalsIgnoreCase(algorithm)
+        || SHA265_WITH_RSA.equalsIgnoreCase(algorithm);
+  }
+
+}
diff --git a/src/main/java/com/googlesource/gerrit/plugins/cfoauth/SignatureVerifier.java b/src/main/java/com/googlesource/gerrit/plugins/cfoauth/SignatureVerifier.java
new file mode 100644
index 0000000..0a49775
--- /dev/null
+++ b/src/main/java/com/googlesource/gerrit/plugins/cfoauth/SignatureVerifier.java
@@ -0,0 +1,22 @@
+// Copyright (C) 2015 The Android Open Source Project
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package com.googlesource.gerrit.plugins.cfoauth;
+
+interface SignatureVerifier {
+
+  boolean supports(String algorithm);
+
+  boolean verify(String content, String signature);
+}
diff --git a/src/main/java/com/googlesource/gerrit/plugins/cfoauth/UAAClient.java b/src/main/java/com/googlesource/gerrit/plugins/cfoauth/UAAClient.java
new file mode 100644
index 0000000..cb9153b
--- /dev/null
+++ b/src/main/java/com/googlesource/gerrit/plugins/cfoauth/UAAClient.java
@@ -0,0 +1,281 @@
+// Copyright (C) 2015 The Android Open Source Project
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package com.googlesource.gerrit.plugins.cfoauth;
+
+import static java.net.HttpURLConnection.HTTP_OK;
+import static java.nio.charset.StandardCharsets.US_ASCII;
+import static java.nio.charset.StandardCharsets.UTF_8;
+import static org.scribe.model.OAuthConstants.CODE;
+import static org.scribe.model.OAuthConstants.REDIRECT_URI;
+import static org.scribe.model.Verb.GET;
+import static org.scribe.model.Verb.POST;
+import static org.scribe.utils.OAuthEncoder.encode;
+
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.base.Strings;
+import com.google.gson.JsonElement;
+import com.google.gson.JsonObject;
+import com.google.gson.JsonParser;
+import com.google.gson.JsonPrimitive;
+
+import org.apache.commons.codec.binary.Base64;
+import org.scribe.model.OAuthRequest;
+import org.scribe.model.Response;
+
+import java.text.MessageFormat;
+
+class UAAClient {
+
+  private static final String OAUTH_ENDPOINT = "%s/oauth/";
+
+  private static final String AUTHORIZE_ENDPOINT = OAUTH_ENDPOINT
+      + "authorize?response_type=code&client_id=%s&redirect_uri=%s";
+  private static final String TOKEN_ENDPOINT = OAUTH_ENDPOINT + "token";
+  private static final String TOKEN_KEY_ENDPOINT = "%s/token_key";
+
+  private static final String GRANT_TYPE = "grant_type";
+  private static final String BY_AUTHORIZATION_CODE = "authorization_code";
+
+  private static final String ALG_ATTRIBUTE = "alg";
+  private static final String VALUE_ATTRIBUTE = "value";
+  private static final String PUBLIC_EXPONENT_ATTRIBUTE = "e";
+  private static final String MODULUS_ATTRIBUTE = "n";
+  private static final String ACCESS_TOKEN_ATTRIBUTE = "access_token";
+  private static final String EXP_ATTRIBUTE = "exp";
+  private static final String USER_NAME_ATTRIBUTE = "user_name";
+  private static final String EMAIL_ATTRIBUTE = "email";
+
+  private static final String AUTHORIZATION_HEADER = "Authorization";
+  private static final String BASIC_AUTHENTICATION = "Basic";
+
+  private final String clientCredentials;
+  private final String redirectUrl;
+
+  private final String authorizationEndpoint;
+  private final String accessTokenEndpoint;
+  private final String tokenKeyEndpoint;
+
+  private final boolean verifySignatures;
+
+  /**
+   * Lazily initialized and may be updated from time to time
+   * when token key is changed in UAA
+   */
+  private SignatureVerifier signatureVerifier;
+
+  public UAAClient(String uaaServerUrl,
+      String clientId,
+      String clientSecret,
+      boolean verifySignatures,
+      String redirectUrl) {
+    this.clientCredentials = BASIC_AUTHENTICATION + " "
+      + encodeBase64(clientId + ":" + clientSecret);
+    this.verifySignatures = verifySignatures;
+    this.redirectUrl = redirectUrl;
+    this.authorizationEndpoint = String.format(AUTHORIZE_ENDPOINT,
+        uaaServerUrl, encode(clientId), encode(redirectUrl));
+    this.accessTokenEndpoint = String.format(TOKEN_ENDPOINT, uaaServerUrl);
+    this.tokenKeyEndpoint = String.format(TOKEN_KEY_ENDPOINT, uaaServerUrl);
+  }
+
+  /**
+   * Returns the authorization grant endpoint of the UAA server.
+   */
+  public String getAuthorizationUrl() {
+    return authorizationEndpoint;
+  }
+
+  /**
+   * Retrieves an access token from the UAA server providing an
+   * authorization code following the "Authorization Code Grant"
+   * scheme of RFC6749 section 4.1.
+   *
+   * @param authorizationCode a previously obtained authorization code.
+   * @return an access token.
+   *
+   * @throws UAAClientException if the UAA request failed.
+   */
+  public AccessToken getAccessToken(String authorizationCode)
+      throws UAAClientException {
+    OAuthRequest request = new OAuthRequest(POST, accessTokenEndpoint);
+    request.addHeader(AUTHORIZATION_HEADER, clientCredentials);
+    request.addBodyParameter(GRANT_TYPE, BY_AUTHORIZATION_CODE);
+    request.addBodyParameter(CODE, authorizationCode);
+    request.addBodyParameter(REDIRECT_URI, redirectUrl);
+    Response response = request.send();
+    if (response.getCode() != HTTP_OK) {
+      throw new UAAClientException(MessageFormat.format(
+          "POST /oauth/token failed with status {0}", response.getCode()));
+    }
+    return parseAccessTokenResponse(response.getBody());
+  }
+
+  /**
+   * Converts an access token given as string represenation
+   * into an {@link AccessToken}.
+   *
+   * @param accessToken the access token to convert.
+   * @return the <code>AccessToken</code> corressponding to the
+   * given access token.
+   *
+   * @throws UAAClientException if the given access token is not
+   * valid or could not be converted into an <code>AccessToken</code>.
+   */
+  public AccessToken toAccessToken(String accessToken)
+      throws UAAClientException {
+    JsonObject jsonWebToken = toJsonWebToken(accessToken);
+    long expiresAt = getLongAttribute(jsonWebToken, EXP_ATTRIBUTE, 0);
+    String username = getAttribute(jsonWebToken, USER_NAME_ATTRIBUTE);
+    if (username == null) {
+      throw new UAAClientException(
+          "Invalid token: missing or invalid 'user_name' attribute");
+    }
+    String emailAddress = getAttribute(jsonWebToken, EMAIL_ATTRIBUTE);
+    if (emailAddress == null) {
+      throw new UAAClientException(
+          "Invalid token: missing or invalid 'email' attribute");
+    }
+    return new AccessToken(accessToken, username, emailAddress, expiresAt);
+  }
+
+  @VisibleForTesting
+  AccessToken parseAccessTokenResponse(String tokenResponse)
+      throws UAAClientException {
+    if (Strings.isNullOrEmpty(tokenResponse)) {
+      throw new UAAClientException(
+          "Can't extract a token from an empty string");
+    }
+    JsonObject json = getAsJsonObject(tokenResponse);
+    String accessToken = getAttribute(json, ACCESS_TOKEN_ATTRIBUTE);
+    if (accessToken == null) {
+      throw new UAAClientException(
+          "Can't extract a token: missing or invalid 'access_token' attribute");
+    }
+    return toAccessToken(accessToken);
+  }
+
+  @VisibleForTesting
+  JsonObject toJsonWebToken(String accessToken)
+      throws UAAClientException {
+    String[] segments = accessToken.split("\\.");
+    if (segments.length != 3) {
+      throw new UAAClientException(
+          "Invalid token: must be of the form 'header.token.signature'");
+    }
+    String claims = decodeBase64(segments[1]);
+    if (verifySignatures) {
+      String header = decodeBase64(segments[0]);
+      String alg = getAttribute(getAsJsonObject(header), ALG_ATTRIBUTE);
+      if (Strings.isNullOrEmpty(alg)) {
+        throw new UAAClientException("Invalid token: missing \"alg\" attribute");
+      }
+      String signature = segments[2];
+      String signedContent = segments[0] + "." + segments[1];
+      verifySignature(signedContent, signature, alg);
+    }
+    return getAsJsonObject(claims);
+  }
+
+  @VisibleForTesting
+  void verifySignature(String signedContent, String signature,
+      String alg) throws UAAClientException {
+    SignatureVerifier verifier = getSignatureVerifier(alg, false);
+    if (!verifier.verify(signedContent, signature)) {
+      // If the signature is invalid, maybe the secret has changed
+      // in the UAA? Obtain a fresh signature verifier and try again
+      verifier = getSignatureVerifier(alg, true);
+      if (!verifier.verify(signedContent, signature)) {
+        throw new UAAClientException(MessageFormat.format(
+            "Invalid token signature ''{0}''", signature));
+      }
+    }
+  }
+
+  @VisibleForTesting
+  synchronized SignatureVerifier getSignatureVerifier(String alg,
+      boolean refresh) throws UAAClientException {
+    if (signatureVerifier == null || refresh) {
+      signatureVerifier = createSignatureVerifier();
+    }
+    if (!signatureVerifier.supports(alg)) {
+      throw new UAAClientException(MessageFormat.format(
+          "Invalid token: unexpected signature algorithm ''{0}''", alg));
+    }
+    return signatureVerifier;
+  }
+
+  private SignatureVerifier createSignatureVerifier()
+      throws UAAClientException {
+    OAuthRequest request = new OAuthRequest(GET, tokenKeyEndpoint);
+    request.addHeader(AUTHORIZATION_HEADER, clientCredentials);
+    Response response = request.send();
+    if (response.getCode() != HTTP_OK) {
+      throw new UAAClientException(MessageFormat.format(
+          "GET /token_key failed with status {0}", response.getCode()));
+    }
+    JsonObject content = getAsJsonObject(response.getBody());
+    String alg = getAttribute(content, ALG_ATTRIBUTE);
+    if (Strings.isNullOrEmpty(alg)) {
+      throw new UAAClientException(
+          "GET /uaa/token_key failed: missing \"alg\" attribute");
+    }
+    if ("HMACSHA256".equals(alg)) {
+      return new HMACSHA256SignatureVerifier(
+          getAttribute(content, VALUE_ATTRIBUTE));
+    } else if ("SHA256withRSA".equals(alg)) {
+      return new SHA265WithRSASignatureVerifier(
+          getAttribute(content, MODULUS_ATTRIBUTE),
+          getAttribute(content, PUBLIC_EXPONENT_ATTRIBUTE));
+    }
+    throw new UAAClientException(MessageFormat.format(
+        "Unsupported signature algorithm ''{0}''", alg));
+  }
+
+  @VisibleForTesting
+  String getAttribute(JsonObject json, String name) {
+    JsonPrimitive prim = getAsJsonPrimitive(json, name);
+    return prim != null && prim.isString() ? prim.getAsString() : null;
+  }
+
+  @VisibleForTesting
+  long getLongAttribute(JsonObject json, String name, long defaultValue) {
+    JsonPrimitive prim = getAsJsonPrimitive(json, name);
+    return prim != null && prim.isNumber() ? prim.getAsLong() : defaultValue;
+  }
+
+  private JsonPrimitive getAsJsonPrimitive(JsonObject json, String name) {
+    JsonElement attr = json.get(name);
+    if (attr == null || !attr.isJsonPrimitive()) {
+      return null;
+    }
+    return attr.getAsJsonPrimitive();
+  }
+
+  private JsonObject getAsJsonObject(String s) {
+    JsonElement json = new JsonParser().parse(s);
+    if (!json.isJsonObject()) {
+      return new JsonObject();
+    }
+    return json.getAsJsonObject();
+  }
+
+  private String decodeBase64(String s) {
+    return new String(Base64.decodeBase64(s), UTF_8);
+  }
+
+  private String encodeBase64(String s) {
+    return new String(Base64.encodeBase64(s.getBytes(UTF_8)), US_ASCII);
+  }
+}
diff --git a/src/main/java/com/googlesource/gerrit/plugins/cfoauth/UAAClientException.java b/src/main/java/com/googlesource/gerrit/plugins/cfoauth/UAAClientException.java
new file mode 100644
index 0000000..e6f5304
--- /dev/null
+++ b/src/main/java/com/googlesource/gerrit/plugins/cfoauth/UAAClientException.java
@@ -0,0 +1,28 @@
+// Copyright (C) 2015 The Android Open Source Project
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package com.googlesource.gerrit.plugins.cfoauth;
+
+class UAAClientException extends RuntimeException {
+
+  private static final long serialVersionUID = 1L;
+
+  public UAAClientException(String message) {
+    super(message);
+  }
+
+  public UAAClientException(String message, Throwable cause) {
+    super(message, cause);
+  }
+}
diff --git a/src/main/resources/Documentation/build.md b/src/main/resources/Documentation/build.md
new file mode 100644
index 0000000..dd62be3
--- /dev/null
+++ b/src/main/resources/Documentation/build.md
@@ -0,0 +1,69 @@
+Build
+=====
+This plugin can be built with Buck.
+
+Buck
+----
+Two build modes are supported: Standalone and in Gerrit tree.
+The standalone build mode is recommended, as this mode doesn't require
+the Gerrit tree to exist locally.
+
+### Build standalone
+
+Clone bucklets library:
+
+```
+  git clone https://gerrit.googlesource.com/bucklets
+```
+
+and link it to @PLUGIN@ plugin directory:
+
+```
+  cd @PLUGIN@ && ln -s ../bucklets .
+```
+
+Add link to the .buckversion file:
+
+```
+  cd @PLUGIN@ && ln -s bucklets/buckversion .buckversion
+```
+
+Add link to the .watchmanconfig file:
+
+```
+  cd @PLUGIN@ && ln -s bucklets/watchmanconfig .watchmanconfig
+```
+
+To build the plugin, issue the following command:
+
+```
+  buck build plugin
+```
+
+The output is created in
+
+```
+  buck-out/gen/@PLUGIN@.jar
+```
+
+### Build in Gerrit tree
+
+Clone or link this plugin to the plugins directory of Gerrit's source
+tree, and issue the command:
+
+```
+  buck build plugins/@PLUGIN@
+```
+
+The output is created in
+
+```
+  buck-out/gen/plugins/@PLUGIN@/@PLUGIN@.jar
+```
+
+This project can be imported into the Eclipse IDE:
+
+```
+  ./tools/eclipse/project.py
+```
+
diff --git a/src/main/resources/Documentation/config.md b/src/main/resources/Documentation/config.md
new file mode 100644
index 0000000..75fc683
--- /dev/null
+++ b/src/main/resources/Documentation/config.md
@@ -0,0 +1,75 @@
+Configuration
+=============
+
+## Registering a Client for Gerrit
+
+Gerrit must be registered as client with the [CloudFoundry User Account and
+Authentication (UAA) Server](https://github.com/cloudfoundry/uaa) that acts
+as OAuth2 authentication and authorization backend.
+
+The following sequence assumes that the UAA client application (`uaac`) is
+installed. It will create a client with name `gerrit`.
+
+```
+  uaac target <URL of the UAA server>
+
+  uaac token client get admin
+
+  uaac client add gerrit
+    --authorities uaa.resource
+    --authorized_grant_type authorization_code,refresh_token,password
+    --scope openid
+    --autoapprove openid
+    --access_token_validity <time in seconds>
+    --redirect_uri <URL of the Gerrit server>/oauth
+    --secret <client secret>
+```
+
+Make sure to choose a strong password for `secret`. Gerrit uses
+this password to obtain access tokens on behalf of its users.
+
+## Configuring the @PLUGIN@ Plugin
+
+The configuration of the @PLUGIN@ plugin is done in the `gerrit.config`
+file. Note that `auth.type` must be set to `OAUTH`.
+
+```
+[auth]
+  type = OAUTH
+
+[plugin "@PLUGIN@"]
+  serverUrl = <URL of the UAA server>
+  clientId = "<client id>"
+  clientSecret = "<client secret>"
+  verifySignatures = true
+```
+
+The parameters `clientId` and `clientSecret` must match the name and
+password of the Gerrit client as registered with the UAA server above.
+The `serverUrl` must point to the UAA server and include the context path,
+e.g `http(s)://example.org/uaa`.
+
+Alternatively, re-run `init` to configure the @PLUGIN@ plugin:
+
+```
+  java -jar gerrit.war init -d <site>
+  [...]
+
+  *** Cloud Foundry UAA OAuth 2.0 Authentication Provider
+  ***
+
+  UAA server URL    [http://localhost:8080/uaa]: <URL of the UAA server>
+  Client id         [gerrit]: <client id>
+  Client secret             : <client secret>
+           confirm password : <client secret>
+  Verify token signatures [Y/n]?
+```
+
+UAA issues so-called [JSON Web Tokens](http://tools.ietf.org/html/rfc7519]),
+which include a signature. By default, the @PLUGIN@ plugin will verify
+signatures of access tokens it received from UAA. Both HMACSHA256 and
+SHA256withRSA signatures are supported given that the underlying Java runtime
+provides the necessary ciphers. If that is not the case you might switch off
+the verification by setting the parameter `verifySignatures` to `false`.
+Note that this is strongly discouraged for security reasons.
+
diff --git a/src/test/java/com/googlesource/gerrit/plugins/cfoauth/UAAClientTest.java b/src/test/java/com/googlesource/gerrit/plugins/cfoauth/UAAClientTest.java
new file mode 100644
index 0000000..160b8ea
--- /dev/null
+++ b/src/test/java/com/googlesource/gerrit/plugins/cfoauth/UAAClientTest.java
@@ -0,0 +1,181 @@
+// Copyright (C) 2015 The Android Open Source Project
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package com.googlesource.gerrit.plugins.cfoauth;
+
+import static org.junit.Assert.*;
+
+import com.google.gson.JsonObject;
+
+import com.googlesource.gerrit.plugins.cfoauth.AccessToken;
+import com.googlesource.gerrit.plugins.cfoauth.HMACSHA256SignatureVerifier;
+import com.googlesource.gerrit.plugins.cfoauth.SignatureVerifier;
+import com.googlesource.gerrit.plugins.cfoauth.UAAClient;
+import com.googlesource.gerrit.plugins.cfoauth.UAAClientException;
+
+import org.junit.Before;
+import org.junit.Test;
+
+public class UAAClientTest {
+
+  private static final String HS256_TEST_TOKEN =
+      "eyJhbGciOiJIUzI1NiJ9.eyJqdGkiOiI4MWI4M2RhNy0yZmI2LTQ4OTUtYTM5ZS0zZ"
+      + "TFjZWEzNzQ2ZDkiLCJzdWIiOiJmNmM1YTgxMi0yNWM2LTQ5ZjItOTJiMS0yYjQ5N"
+      + "mRjOTAyNTUiLCJzY29wZSI6WyJvcGVuaWQiXSwiY2xpZW50X2lkIjoiZ2Vycml0L"
+      + "WlkIiwiY2lkIjoiZ2Vycml0LWlkIiwiYXpwIjoiZ2Vycml0LWlkIiwiZ3JhbnRfd"
+      + "HlwZSI6ImF1dGhvcml6YXRpb25fY29kZSIsInVzZXJfaWQiOiJmNmM1YTgxMi0yN"
+      + "WM2LTQ5ZjItOTJiMS0yYjQ5NmRjOTAyNTUiLCJ1c2VyX25hbWUiOiJtYXJpc3NhI"
+      + "iwiZW1haWwiOiJtYXJpc3NhQHRlc3Qub3JnIiwicmV2X3NpZyI6IjkwZGQzNTNlI"
+      + "iwiaWF0IjoxNDM2MTg5NzMyLCJleHAiOjE0MzYyMzI5MzIsImlzcyI6Imh0dHA6L"
+      + "y9sb2NhbGhvc3Q6ODA4MC91YWEvb2F1dGgvdG9rZW4iLCJ6aWQiOiJ1YWEiLCJhd"
+      + "WQiOlsiZ2Vycml0LWlkIiwib3BlbmlkIl19.ynnx6J9CO-jnKETDn4DSEdvWMZkC"
+      + "2mTynnhgYL-TyaU";
+
+  private static final String[] HS256_TOKEN_PARTS =
+      HS256_TEST_TOKEN.split("\\.");
+
+  private static final String HS256_SIGNED_CONTENT =
+      HS256_TOKEN_PARTS[0] + "." + HS256_TOKEN_PARTS[1];
+  private static final String HS256_SIGNATURE =
+      HS256_TOKEN_PARTS[2];
+  private static final String HS256_INVALID_SIGNATURE =
+      ".dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk";
+
+
+  private static final String HS256_TOKEN_INVALID_HEADER = ""
+      + "foo" + HS256_TOKEN_PARTS[1] + "." + HS256_TOKEN_PARTS[2];
+  private static final String HS256_TOKEN_INVLID_CLAIMS =
+      HS256_TOKEN_PARTS[0] + ".foo." + HS256_TOKEN_PARTS[2];
+  private static final String HS256_TOKEN_INVALID_SIGNATURE =
+      HS256_TOKEN_PARTS[0] + "." + HS256_TOKEN_PARTS[1]
+          + HS256_INVALID_SIGNATURE;
+
+  private static final String HS256_ACCESS_TOKEN_RESPONSE = "{"
+      + "\"access_token\":\"" + HS256_TEST_TOKEN + "\","
+      + "\"token_type\":\"bearer\","
+      + "\"expires_in\":3600}";
+
+  private static final String MISSING_ACCESS_TOKEN_ATTRIBUTE= "{"
+      + "\"access_token1\":\"" + HS256_TEST_TOKEN + "\"}";
+
+  private static final String INVALID_TOKEN_ATTRIBUTE= "{"
+      + "\"access_token\":\"" + HS256_TOKEN_INVALID_SIGNATURE + "\"}";
+
+  private static final String UAA_SERVER_URL = "http://uaa.example.org/uaa";
+  private static final String CLIENT_ID = "gerrit";
+  private static final String CLIENT_SECRET = "gerritsecret";
+  private static final String REDIRECT_URL = "http://gerrit.example.org/oauth";
+
+  private static final String TOKEN_KEY = "tokenkey";
+
+  private static class UAATestClient extends UAAClient {
+
+    public UAATestClient() {
+      super(UAA_SERVER_URL, CLIENT_ID, CLIENT_SECRET, true, REDIRECT_URL);
+    }
+
+    @Override
+    SignatureVerifier getSignatureVerifier(String alg, boolean refresh)
+        throws UAAClientException {
+      return new HMACSHA256SignatureVerifier(TOKEN_KEY);
+    }
+  }
+
+  private UAAClient client;
+
+  @Before
+  public void setup() throws Exception {
+    client = new UAATestClient();
+  }
+
+  @Test
+  public void testGetAuthorizationUrl() throws Exception {
+    assertEquals("http://uaa.example.org/uaa/oauth/authorize?"
+        + "response_type=code&client_id=gerrit&redirect_uri="
+        + "http%3A%2F%2Fgerrit.example.org%2Foauth",
+        client.getAuthorizationUrl());
+  }
+
+  @Test
+  public void testToJsonWebToken() throws Exception {
+    JsonObject jsonWebToken = client.toJsonWebToken(HS256_TEST_TOKEN);
+    assertEquals("marissa", client.getAttribute(jsonWebToken, "user_name"));
+    assertEquals("marissa@test.org", client.getAttribute(jsonWebToken, "email"));
+    assertEquals(1436232932L, client.getLongAttribute(jsonWebToken, "exp", 0));
+  }
+
+  @Test(expected = UAAClientException.class)
+  public void testToJsonWebTokenInvalidToken() throws Exception {
+    client.toJsonWebToken("foobar");
+  }
+
+  @Test(expected = UAAClientException.class)
+  public void testToJsonWebTokenInvalidPrefix() throws Exception {
+    client.toJsonWebToken(HS256_TOKEN_INVALID_HEADER);
+  }
+
+  @Test(expected = UAAClientException.class)
+  public void testToJsonWebTokenInvalidClaims() throws Exception {
+    client.toJsonWebToken(HS256_TOKEN_INVLID_CLAIMS);
+  }
+
+  @Test(expected = UAAClientException.class)
+  public void testToJsonWebTokenInvalidSignature() throws Exception {
+    client.toJsonWebToken(HS256_TOKEN_INVALID_SIGNATURE);
+  }
+
+  @Test
+  public void testGetAsAccessToken() throws Exception {
+    AccessToken accessToken = client.toAccessToken(HS256_TEST_TOKEN);
+    assertHS266AccessToken(accessToken);
+  }
+
+  @Test
+  public void testVerifySignature() throws Exception {
+    client.verifySignature(HS256_SIGNED_CONTENT, HS256_SIGNATURE, "HS256");
+  }
+
+  @Test(expected = UAAClientException.class)
+  public void testVerifyInvalidSignature() throws Exception {
+    client.verifySignature(HS256_SIGNED_CONTENT, HS256_INVALID_SIGNATURE,
+        "HS256");
+  }
+
+  @Test
+  public void testParseAccessTokenResponse() throws Exception {
+    AccessToken accessToken = client.parseAccessTokenResponse(
+        HS256_ACCESS_TOKEN_RESPONSE);
+    assertHS266AccessToken(accessToken);
+  }
+
+  @Test(expected = UAAClientException.class)
+  public void testParseAccessTokenResponseMissingAccessTokenAttribute()
+      throws Exception {
+    client.parseAccessTokenResponse(MISSING_ACCESS_TOKEN_ATTRIBUTE);
+  }
+
+  @Test(expected = UAAClientException.class)
+  public void testParseAccessTokenResponseInvalidTokenAttribute()
+      throws Exception {
+    client.parseAccessTokenResponse(INVALID_TOKEN_ATTRIBUTE);
+  }
+
+  private void assertHS266AccessToken(AccessToken accessToken) {
+    assertEquals(HS256_TEST_TOKEN, accessToken.getValue());
+    assertEquals(1436232932L, accessToken.getExpiresAt());
+    assertEquals("external:marissa", accessToken.getExternalId());
+    assertEquals("marissa", accessToken.getUserName());
+    assertEquals("marissa@test.org", accessToken.getEmailAddress());
+  }
+}