app/gerrit: import OAuth provider and add SSO support

This change:

 - imports gerrit-oauth-provider from upstream
 - adds sso.hackerspae.pl support to it

Change-Id: I92e7053614a9297bf1ced3aac044c0002acd836a
diff --git a/WORKSPACE b/WORKSPACE
index 66cdf62..d2d7cf6 100644
--- a/WORKSPACE
+++ b/WORKSPACE
@@ -110,6 +110,36 @@
 
 gazelle_dependencies()
 
+# For app/gerrit/gerrit-oauth-provider
+
+git_repository(
+    name = "com_googlesource_gerrit_bazlets",
+    remote = "https://gerrit.googlesource.com/bazlets",
+    commit = "8528a0df69dadf6311d8d3f81c1b693afda8bcf1",
+)
+
+load(
+    "@com_googlesource_gerrit_bazlets//:gerrit_api.bzl",
+    "gerrit_api",
+)
+
+gerrit_api()
+
+load("@com_googlesource_gerrit_bazlets//tools:maven_jar.bzl", "maven_jar")
+
+maven_jar(
+    name = "scribe",
+    artifact = "org.scribe:scribe:1.3.7",
+    sha1 = "583921bed46635d9f529ef5f14f7c9e83367bc6e",
+)
+
+maven_jar(
+    name = "commons-codec",
+    artifact = "commons-codec:commons-codec:1.4",
+    sha1 = "4216af16d38465bbab0f3dff8efa14204f7a399a",
+)
+
+
 # Go repositories
 
 go_repository(
diff --git a/app/gerrit/gerrit-oauth-provider/.gitignore b/app/gerrit/gerrit-oauth-provider/.gitignore
new file mode 100644
index 0000000..445b95a
--- /dev/null
+++ b/app/gerrit/gerrit-oauth-provider/.gitignore
@@ -0,0 +1,11 @@
+/.classpath
+/.project
+/.settings
+/bazel-bin
+/bazel-genfiles
+/bazel-gerrit-oauth-provider
+/bazel-out
+/bazel-testlogs
+/eclipse-out
+/.idea
+*.swp
diff --git a/app/gerrit/gerrit-oauth-provider/BUILD b/app/gerrit/gerrit-oauth-provider/BUILD
new file mode 100644
index 0000000..bb266e4
--- /dev/null
+++ b/app/gerrit/gerrit-oauth-provider/BUILD
@@ -0,0 +1,43 @@
+load("//app/gerrit/gerrit-oauth-provider/tools/bzl:junit.bzl", "junit_tests")
+load(
+    "//app/gerrit/gerrit-oauth-provider/tools/bzl:plugin.bzl",
+    "PLUGIN_DEPS",
+    "PLUGIN_TEST_DEPS",
+    "gerrit_plugin",
+)
+
+gerrit_plugin(
+    name = "gerrit-oauth-provider",
+    srcs = glob(["src/main/java/**/*.java"]),
+    manifest_entries = [
+        "Gerrit-PluginName: gerrit-oauth-provider",
+        "Gerrit-HttpModule: com.googlesource.gerrit.plugins.oauth.HttpModule",
+        "Gerrit-InitStep: com.googlesource.gerrit.plugins.oauth.InitOAuth",
+        "Implementation-Title: Gerrit OAuth authentication provider",
+        "Implementation-URL: https://github.com/davido/gerrit-oauth-provider",
+    ],
+    resources = glob(["src/main/resources/**/*"]),
+    deps = [
+        "@commons-codec//jar:neverlink",
+        "@scribe//jar",
+    ],
+)
+
+junit_tests(
+    name = "gerrit-oauth-provider_tests",
+    srcs = glob(["src/test/java/**/*.java"]),
+    tags = ["oauth"],
+    deps = [
+        ":gerrit-oauth-provider__plugin_test_deps",
+    ],
+)
+
+java_library(
+    name = "gerrit-oauth-provider__plugin_test_deps",
+    testonly = 1,
+    visibility = ["//visibility:public"],
+    exports = PLUGIN_DEPS + PLUGIN_TEST_DEPS + [
+        ":gerrit-oauth-provider__plugin",
+        "@scribe//jar",
+    ],
+)
diff --git a/app/gerrit/gerrit-oauth-provider/LICENSE-Apache2.0 b/app/gerrit/gerrit-oauth-provider/LICENSE-Apache2.0
new file mode 100644
index 0000000..11069ed
--- /dev/null
+++ b/app/gerrit/gerrit-oauth-provider/LICENSE-Apache2.0
@@ -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/app/gerrit/gerrit-oauth-provider/LICENSE-scribe b/app/gerrit/gerrit-oauth-provider/LICENSE-scribe
new file mode 100644
index 0000000..7cea02d
--- /dev/null
+++ b/app/gerrit/gerrit-oauth-provider/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/app/gerrit/gerrit-oauth-provider/README.md b/app/gerrit/gerrit-oauth-provider/README.md
new file mode 100644
index 0000000..414eef6
--- /dev/null
+++ b/app/gerrit/gerrit-oauth-provider/README.md
@@ -0,0 +1,68 @@
+Gerrit OAuth2 authentication provider
+=====================================
+
+[![Build Status](https://travis-ci.org/davido/gerrit-oauth-provider.svg?branch=master)](https://travis-ci.org/davido/gerrit-oauth-provider)
+
+
+With this plugin Gerrit can use OAuth2 protocol for authentication. 
+Supported OAuth providers:
+
+* [AirVantage](https://doc.airvantage.net/av/reference/cloud/API/#API-GeneralInformation-Authentication)
+* [Bitbucket](https://confluence.atlassian.com/bitbucket/oauth-on-bitbucket-cloud-238027431.html)
+* [CAS](https://www.apereo.org/projects/cas)
+* [CoreOS Dex](https://github.com/coreos/dex)
+* [Facebook](https://developers.facebook.com/docs/facebook-login)
+* [GitHub](https://developer.github.com/v3/oauth/)
+* [GitLab](https://about.gitlab.com/)
+* [Google](https://developers.google.com/identity/protocols/OAuth2)
+* [Keycloak](http://www.keycloak.org/)
+* [Office365](https://docs.microsoft.com/en-us/azure/active-directory/develop/active-directory-v2-protocols)
+
+See the [Wiki](https://github.com/davido/gerrit-oauth-provider/wiki) what it can do for you.
+
+Prebuilt artifacts 
+------------------
+
+Prebuilt binary artifacts are available on [release page](https://github.com/davido/gerrit-oauth-provider/releases). Make sure to pick the right JAR for your Gerrit version.
+
+Build
+-----
+
+To build the plugin with Bazel, install
+[Bazel](https://bazel.build/versions/master/docs/install.html) and run the
+following:
+
+```
+  git clone https://gerrit.googlesource.com/plugins/oauth gerrit-oauth-provider
+  cd gerrit-oauth-provider && bazel build gerrit-oauth-provider
+```
+
+Install
+-------
+
+Copy the `bazel-genfiles/oauth.jar` to
+`$gerrit_site/plugins` and re-run init to configure it:
+
+```
+  java -jar gerrit.war init -d <site>
+  [...]
+  *** OAuth Authentication Provider
+  ***
+  Use Bitbucket OAuth provider for Gerrit login ? [Y/n]? n
+  Use Google OAuth provider for Gerrit login ? [Y/n]?
+  Application client id          : <client-id>
+  Application client secret      : 
+                confirm password : 
+  Link to OpenID accounts? [true]: 
+  Use GitHub OAuth provider for Gerrit login ? [Y/n]? n
+```
+
+Reporting bugs
+--------------
+
+Make sure to read the [FAQ](https://github.com/davido/gerrit-oauth-provider/wiki/FAQ) before reporting issues.
+
+License
+-------
+
+Apache License 2.0
diff --git a/app/gerrit/gerrit-oauth-provider/bazlets.bzl b/app/gerrit/gerrit-oauth-provider/bazlets.bzl
new file mode 100644
index 0000000..f089af4
--- /dev/null
+++ b/app/gerrit/gerrit-oauth-provider/bazlets.bzl
@@ -0,0 +1,18 @@
+load("@bazel_tools//tools/build_defs/repo:git.bzl", "git_repository")
+
+NAME = "com_googlesource_gerrit_bazlets"
+
+def load_bazlets(
+        commit,
+        local_path = None):
+    if not local_path:
+        git_repository(
+            name = NAME,
+            remote = "https://gerrit.googlesource.com/bazlets",
+            commit = commit,
+        )
+    else:
+        native.local_repository(
+            name = NAME,
+            path = local_path,
+        )
diff --git a/app/gerrit/gerrit-oauth-provider/external_plugin_deps.bzl b/app/gerrit/gerrit-oauth-provider/external_plugin_deps.bzl
new file mode 100644
index 0000000..e560344
--- /dev/null
+++ b/app/gerrit/gerrit-oauth-provider/external_plugin_deps.bzl
@@ -0,0 +1,14 @@
+load("//tools/bzl:maven_jar.bzl", "maven_jar")
+
+def external_plugin_deps(omit_commons_codec = True):
+    maven_jar(
+        name = "scribe",
+        artifact = "org.scribe:scribe:1.3.7",
+        sha1 = "583921bed46635d9f529ef5f14f7c9e83367bc6e",
+    )
+    if not omit_commons_codec:
+        maven_jar(
+            name = "commons-codec",
+            artifact = "commons-codec:commons-codec:1.4",
+            sha1 = "4216af16d38465bbab0f3dff8efa14204f7a399a",
+        )
diff --git a/app/gerrit/gerrit-oauth-provider/src/main/java/com/googlesource/gerrit/plugins/oauth/AirVantageApi.java b/app/gerrit/gerrit-oauth-provider/src/main/java/com/googlesource/gerrit/plugins/oauth/AirVantageApi.java
new file mode 100644
index 0000000..02f4bd5
--- /dev/null
+++ b/app/gerrit/gerrit-oauth-provider/src/main/java/com/googlesource/gerrit/plugins/oauth/AirVantageApi.java
@@ -0,0 +1,56 @@
+// Copyright (C) 2018 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.oauth;
+
+import static java.lang.String.format;
+
+import org.scribe.builder.api.DefaultApi20;
+import org.scribe.extractors.AccessTokenExtractor;
+import org.scribe.extractors.JsonTokenExtractor;
+import org.scribe.model.OAuthConfig;
+import org.scribe.model.Verb;
+import org.scribe.oauth.OAuthService;
+
+public class AirVantageApi extends DefaultApi20 {
+
+  private static final String AUTHORIZE_URL =
+      "https://eu.airvantage.net/api/oauth/authorize?client_id=%s&response_type=code";
+  private static final String ACCESS_TOKEN_ENDPOINT = "https://eu.airvantage.net/api/oauth/token";
+
+  @Override
+  public String getAuthorizationUrl(OAuthConfig config) {
+    return format(AUTHORIZE_URL, config.getApiKey());
+  }
+
+  @Override
+  public String getAccessTokenEndpoint() {
+    return ACCESS_TOKEN_ENDPOINT;
+  }
+
+  @Override
+  public Verb getAccessTokenVerb() {
+    return Verb.POST;
+  }
+
+  @Override
+  public AccessTokenExtractor getAccessTokenExtractor() {
+    return new JsonTokenExtractor();
+  }
+
+  @Override
+  public OAuthService createService(OAuthConfig config) {
+    return new OAuth20ServiceImpl(this, config);
+  }
+}
diff --git a/app/gerrit/gerrit-oauth-provider/src/main/java/com/googlesource/gerrit/plugins/oauth/AirVantageOAuthService.java b/app/gerrit/gerrit-oauth-provider/src/main/java/com/googlesource/gerrit/plugins/oauth/AirVantageOAuthService.java
new file mode 100644
index 0000000..a1ec591
--- /dev/null
+++ b/app/gerrit/gerrit-oauth-provider/src/main/java/com/googlesource/gerrit/plugins/oauth/AirVantageOAuthService.java
@@ -0,0 +1,127 @@
+// Copyright (C) 2018 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.oauth;
+
+import static com.google.gerrit.json.OutputFormat.JSON;
+import static javax.servlet.http.HttpServletResponse.SC_OK;
+import static org.slf4j.LoggerFactory.getLogger;
+
+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.gson.JsonElement;
+import com.google.gson.JsonObject;
+import com.google.inject.Inject;
+import com.google.inject.Provider;
+import com.google.inject.Singleton;
+import java.io.IOException;
+import org.scribe.builder.ServiceBuilder;
+import org.scribe.model.OAuthRequest;
+import org.scribe.model.Response;
+import org.scribe.model.Token;
+import org.scribe.model.Verb;
+import org.scribe.model.Verifier;
+import org.scribe.oauth.OAuthService;
+import org.slf4j.Logger;
+
+@Singleton
+public class AirVantageOAuthService implements OAuthServiceProvider {
+  private static final Logger log = getLogger(AirVantageOAuthService.class);
+  static final String CONFIG_SUFFIX = "-airvantage-oauth";
+  private static final String AV_PROVIDER_PREFIX = "airvantage-oauth:";
+  private static final String PROTECTED_RESOURCE_URL =
+      "https://eu.airvantage.net/api/v1/users/current";
+  private final OAuthService service;
+
+  @Inject
+  AirVantageOAuthService(
+      PluginConfigFactory cfgFactory,
+      @PluginName String pluginName,
+      @CanonicalWebUrl Provider<String> urlProvider) {
+    PluginConfig cfg = cfgFactory.getFromGerritConfig(pluginName + CONFIG_SUFFIX);
+    String canonicalWebUrl = CharMatcher.is('/').trimTrailingFrom(urlProvider.get()) + "/";
+
+    service =
+        new ServiceBuilder()
+            .provider(AirVantageApi.class)
+            .apiKey(cfg.getString(InitOAuth.CLIENT_ID))
+            .apiSecret(cfg.getString(InitOAuth.CLIENT_SECRET))
+            .callback(canonicalWebUrl + "oauth")
+            .build();
+  }
+
+  @Override
+  public OAuthUserInfo getUserInfo(OAuthToken token) throws IOException {
+    OAuthRequest request = new OAuthRequest(Verb.GET, PROTECTED_RESOURCE_URL);
+    Token t = new Token(token.getToken(), token.getSecret(), token.getRaw());
+    service.signRequest(t, request);
+    Response response = request.send();
+    if (response.getCode() != SC_OK) {
+      throw new IOException(
+          String.format(
+              "Status %s (%s) for request %s",
+              response.getCode(), response.getBody(), request.getUrl()));
+    }
+    JsonElement userJson = JSON.newGson().fromJson(response.getBody(), JsonElement.class);
+    if (log.isDebugEnabled()) {
+      log.debug("User info response: {}", response.getBody());
+    }
+    if (userJson.isJsonObject()) {
+      JsonObject jsonObject = userJson.getAsJsonObject();
+      JsonElement id = jsonObject.get("uid");
+      if (id == null || id.isJsonNull()) {
+        throw new IOException("Response doesn't contain uid field");
+      }
+      JsonElement email = jsonObject.get("email");
+      JsonElement name = jsonObject.get("name");
+      return new OAuthUserInfo(
+          AV_PROVIDER_PREFIX + id.getAsString(),
+          null,
+          email.getAsString(),
+          name.getAsString(),
+          id.getAsString());
+    }
+
+    throw new IOException(String.format("Invalid JSON '%s': not a JSON Object", userJson));
+  }
+
+  @Override
+  public OAuthToken getAccessToken(OAuthVerifier rv) {
+    Verifier vi = new Verifier(rv.getValue());
+    Token to = service.getAccessToken(null, vi);
+    return new OAuthToken(to.getToken(), to.getSecret(), to.getRawResponse());
+  }
+
+  @Override
+  public String getAuthorizationUrl() {
+    return service.getAuthorizationUrl(null);
+  }
+
+  @Override
+  public String getVersion() {
+    return service.getVersion();
+  }
+
+  @Override
+  public String getName() {
+    return "AirVantage OAuth2";
+  }
+}
diff --git a/app/gerrit/gerrit-oauth-provider/src/main/java/com/googlesource/gerrit/plugins/oauth/BitbucketApi.java b/app/gerrit/gerrit-oauth-provider/src/main/java/com/googlesource/gerrit/plugins/oauth/BitbucketApi.java
new file mode 100644
index 0000000..de0f5ea
--- /dev/null
+++ b/app/gerrit/gerrit-oauth-provider/src/main/java/com/googlesource/gerrit/plugins/oauth/BitbucketApi.java
@@ -0,0 +1,150 @@
+// 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.oauth;
+
+import static com.google.gerrit.json.OutputFormat.JSON;
+import static java.lang.String.format;
+import static javax.servlet.http.HttpServletResponse.SC_OK;
+import static org.scribe.model.OAuthConstants.ACCESS_TOKEN;
+import static org.scribe.model.OAuthConstants.CODE;
+
+import com.google.common.io.BaseEncoding;
+import com.google.gson.JsonElement;
+import com.google.gson.JsonObject;
+import org.scribe.builder.api.DefaultApi20;
+import org.scribe.exceptions.OAuthException;
+import org.scribe.extractors.AccessTokenExtractor;
+import org.scribe.model.OAuthConfig;
+import org.scribe.model.OAuthRequest;
+import org.scribe.model.Response;
+import org.scribe.model.Token;
+import org.scribe.model.Verb;
+import org.scribe.model.Verifier;
+import org.scribe.oauth.OAuthService;
+
+public class BitbucketApi extends DefaultApi20 {
+
+  private static final String AUTHORIZE_URL =
+      "https://bitbucket.org/site/oauth2/authorize?client_id=%s&response_type=code";
+  private static final String ACCESS_TOKEN_ENDPOINT =
+      "https://bitbucket.org/site/oauth2/access_token";
+
+  public BitbucketApi() {}
+
+  @Override
+  public String getAuthorizationUrl(OAuthConfig config) {
+    return format(AUTHORIZE_URL, config.getApiKey());
+  }
+
+  @Override
+  public String getAccessTokenEndpoint() {
+    return ACCESS_TOKEN_ENDPOINT;
+  }
+
+  @Override
+  public Verb getAccessTokenVerb() {
+    return Verb.POST;
+  }
+
+  @Override
+  public OAuthService createService(OAuthConfig config) {
+    return new BitbucketOAuthService(this, config);
+  }
+
+  @Override
+  public AccessTokenExtractor getAccessTokenExtractor() {
+    return new BitbucketTokenExtractor();
+  }
+
+  private static final class BitbucketOAuthService implements OAuthService {
+    private static final String VERSION = "2.0";
+
+    private static final String GRANT_TYPE = "grant_type";
+    private static final String GRANT_TYPE_VALUE = "authorization_code";
+
+    private final DefaultApi20 api;
+    private final OAuthConfig config;
+
+    private BitbucketOAuthService(DefaultApi20 api, OAuthConfig config) {
+      this.config = config;
+      this.api = api;
+    }
+
+    @Override
+    public Token getAccessToken(Token token, Verifier verifier) {
+      OAuthRequest request =
+          new OAuthRequest(api.getAccessTokenVerb(), api.getAccessTokenEndpoint());
+      request.addHeader("Authorization", prepareAuthorizationHeaderValue());
+      request.addBodyParameter(GRANT_TYPE, GRANT_TYPE_VALUE);
+      request.addBodyParameter(CODE, verifier.getValue());
+      Response response = request.send();
+      if (response.getCode() == SC_OK) {
+        Token t = api.getAccessTokenExtractor().extract(response.getBody());
+        return new Token(t.getToken(), config.getApiSecret());
+      }
+
+      throw new OAuthException(
+          String.format(
+              "Error response received: %s, HTTP status: %s",
+              response.getBody(), response.getCode()));
+    }
+
+    private String prepareAuthorizationHeaderValue() {
+      String value = String.format("%s:%s", config.getApiKey(), config.getApiSecret());
+      String valueBase64 = BaseEncoding.base64().encode(value.getBytes());
+      return String.format("Basic %s", valueBase64);
+    }
+
+    @Override
+    public Token getRequestToken() {
+      throw new UnsupportedOperationException(
+          "Unsupported operation, please use 'getAuthorizationUrl' and redirect your users there");
+    }
+
+    @Override
+    public String getVersion() {
+      return VERSION;
+    }
+
+    @Override
+    public void signRequest(Token token, OAuthRequest request) {
+      request.addQuerystringParameter(ACCESS_TOKEN, token.getToken());
+    }
+
+    @Override
+    public String getAuthorizationUrl(Token token) {
+      return api.getAuthorizationUrl(config);
+    }
+  }
+
+  private static final class BitbucketTokenExtractor implements AccessTokenExtractor {
+
+    @Override
+    public Token extract(String response) {
+      JsonElement json = JSON.newGson().fromJson(response, JsonElement.class);
+      if (json.isJsonObject()) {
+        JsonObject jsonObject = json.getAsJsonObject();
+        JsonElement id = jsonObject.get(ACCESS_TOKEN);
+        if (id == null || id.isJsonNull()) {
+          throw new OAuthException("Response doesn't contain 'access_token' field");
+        }
+        JsonElement accessToken = jsonObject.get(ACCESS_TOKEN);
+        return new Token(accessToken.getAsString(), "");
+      }
+
+      throw new OAuthException(String.format("Invalid JSON '%s': not a JSON Object", json));
+    }
+  }
+}
diff --git a/app/gerrit/gerrit-oauth-provider/src/main/java/com/googlesource/gerrit/plugins/oauth/BitbucketOAuthService.java b/app/gerrit/gerrit-oauth-provider/src/main/java/com/googlesource/gerrit/plugins/oauth/BitbucketOAuthService.java
new file mode 100644
index 0000000..c1524e9
--- /dev/null
+++ b/app/gerrit/gerrit-oauth-provider/src/main/java/com/googlesource/gerrit/plugins/oauth/BitbucketOAuthService.java
@@ -0,0 +1,130 @@
+// 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.oauth;
+
+import static com.google.gerrit.json.OutputFormat.JSON;
+import static javax.servlet.http.HttpServletResponse.SC_OK;
+import static org.slf4j.LoggerFactory.getLogger;
+
+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.gson.JsonElement;
+import com.google.gson.JsonObject;
+import com.google.inject.Inject;
+import com.google.inject.Provider;
+import com.google.inject.Singleton;
+import java.io.IOException;
+import org.scribe.builder.ServiceBuilder;
+import org.scribe.model.OAuthRequest;
+import org.scribe.model.Response;
+import org.scribe.model.Token;
+import org.scribe.model.Verb;
+import org.scribe.model.Verifier;
+import org.scribe.oauth.OAuthService;
+import org.slf4j.Logger;
+
+@Singleton
+public class BitbucketOAuthService implements OAuthServiceProvider {
+  private static final Logger log = getLogger(BitbucketOAuthService.class);
+  static final String CONFIG_SUFFIX = "-bitbucket-oauth";
+  private static final String BITBUCKET_PROVIDER_PREFIX = "bitbucket-oauth:";
+  private static final String PROTECTED_RESOURCE_URL = "https://bitbucket.org/api/1.0/user/";
+  private final boolean fixLegacyUserId;
+  private final OAuthService service;
+
+  @Inject
+  BitbucketOAuthService(
+      PluginConfigFactory cfgFactory,
+      @PluginName String pluginName,
+      @CanonicalWebUrl Provider<String> urlProvider) {
+    PluginConfig cfg = cfgFactory.getFromGerritConfig(pluginName + CONFIG_SUFFIX);
+
+    String canonicalWebUrl = CharMatcher.is('/').trimTrailingFrom(urlProvider.get()) + "/";
+    fixLegacyUserId = cfg.getBoolean(InitOAuth.FIX_LEGACY_USER_ID, false);
+    service =
+        new ServiceBuilder()
+            .provider(BitbucketApi.class)
+            .apiKey(cfg.getString(InitOAuth.CLIENT_ID))
+            .apiSecret(cfg.getString(InitOAuth.CLIENT_SECRET))
+            .callback(canonicalWebUrl + "oauth")
+            .build();
+  }
+
+  @Override
+  public OAuthUserInfo getUserInfo(OAuthToken token) throws IOException {
+    OAuthRequest request = new OAuthRequest(Verb.GET, PROTECTED_RESOURCE_URL);
+    Token t = new Token(token.getToken(), token.getSecret(), token.getRaw());
+    service.signRequest(t, request);
+    Response response = request.send();
+    if (response.getCode() != SC_OK) {
+      throw new IOException(
+          String.format(
+              "Status %s (%s) for request %s",
+              response.getCode(), response.getBody(), request.getUrl()));
+    }
+    JsonElement userJson = JSON.newGson().fromJson(response.getBody(), JsonElement.class);
+    if (log.isDebugEnabled()) {
+      log.debug("User info response: {}", response.getBody());
+    }
+    if (userJson.isJsonObject()) {
+      JsonObject jsonObject = userJson.getAsJsonObject();
+      JsonObject userObject = jsonObject.getAsJsonObject("user");
+      if (userObject == null || userObject.isJsonNull()) {
+        throw new IOException("Response doesn't contain 'user' field");
+      }
+      JsonElement usernameElement = userObject.get("username");
+      String username = usernameElement.getAsString();
+
+      JsonElement displayName = jsonObject.get("display_name");
+      return new OAuthUserInfo(
+          BITBUCKET_PROVIDER_PREFIX + username,
+          username,
+          null,
+          displayName == null || displayName.isJsonNull() ? null : displayName.getAsString(),
+          fixLegacyUserId ? username : null);
+    }
+
+    throw new IOException(String.format("Invalid JSON '%s': not a JSON Object", userJson));
+  }
+
+  @Override
+  public OAuthToken getAccessToken(OAuthVerifier rv) {
+    Verifier vi = new Verifier(rv.getValue());
+    Token to = service.getAccessToken(null, vi);
+    return new OAuthToken(to.getToken(), to.getSecret(), to.getRawResponse());
+  }
+
+  @Override
+  public String getAuthorizationUrl() {
+    return service.getAuthorizationUrl(null);
+  }
+
+  @Override
+  public String getVersion() {
+    return service.getVersion();
+  }
+
+  @Override
+  public String getName() {
+    return "Bitbucket OAuth2";
+  }
+}
diff --git a/app/gerrit/gerrit-oauth-provider/src/main/java/com/googlesource/gerrit/plugins/oauth/CasApi.java b/app/gerrit/gerrit-oauth-provider/src/main/java/com/googlesource/gerrit/plugins/oauth/CasApi.java
new file mode 100644
index 0000000..76d4011
--- /dev/null
+++ b/app/gerrit/gerrit-oauth-provider/src/main/java/com/googlesource/gerrit/plugins/oauth/CasApi.java
@@ -0,0 +1,53 @@
+// Copyright (C) 2016 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.oauth;
+
+import org.scribe.builder.api.DefaultApi20;
+import org.scribe.model.OAuthConfig;
+import org.scribe.model.Verb;
+import org.scribe.oauth.OAuthService;
+import org.scribe.utils.OAuthEncoder;
+
+public class CasApi extends DefaultApi20 {
+  private static final String AUTHORIZE_URL =
+      "%s/oauth2.0/authorize?response_type=code&client_id=%s&redirect_uri=%s";
+
+  private final String rootUrl;
+
+  public CasApi(String rootUrl) {
+    this.rootUrl = rootUrl;
+  }
+
+  @Override
+  public String getAccessTokenEndpoint() {
+    return String.format("%s/oauth2.0/accessToken", rootUrl);
+  }
+
+  @Override
+  public String getAuthorizationUrl(OAuthConfig config) {
+    return String.format(
+        AUTHORIZE_URL, rootUrl, config.getApiKey(), OAuthEncoder.encode(config.getCallback()));
+  }
+
+  @Override
+  public Verb getAccessTokenVerb() {
+    return Verb.POST;
+  }
+
+  @Override
+  public OAuthService createService(OAuthConfig config) {
+    return new OAuth20ServiceImpl(this, config);
+  }
+}
diff --git a/app/gerrit/gerrit-oauth-provider/src/main/java/com/googlesource/gerrit/plugins/oauth/CasOAuthService.java b/app/gerrit/gerrit-oauth-provider/src/main/java/com/googlesource/gerrit/plugins/oauth/CasOAuthService.java
new file mode 100644
index 0000000..e90c5b3
--- /dev/null
+++ b/app/gerrit/gerrit-oauth-provider/src/main/java/com/googlesource/gerrit/plugins/oauth/CasOAuthService.java
@@ -0,0 +1,171 @@
+// Copyright (C) 2016 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.oauth;
+
+import static com.google.gerrit.json.OutputFormat.JSON;
+
+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.gson.JsonArray;
+import com.google.gson.JsonElement;
+import com.google.gson.JsonObject;
+import com.google.inject.Inject;
+import com.google.inject.Provider;
+import com.google.inject.Singleton;
+import java.io.IOException;
+import javax.servlet.http.HttpServletResponse;
+import org.scribe.builder.ServiceBuilder;
+import org.scribe.model.OAuthRequest;
+import org.scribe.model.Response;
+import org.scribe.model.Token;
+import org.scribe.model.Verb;
+import org.scribe.model.Verifier;
+import org.scribe.oauth.OAuthService;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+@Singleton
+class CasOAuthService implements OAuthServiceProvider {
+  private static final Logger log = LoggerFactory.getLogger(CasOAuthService.class);
+  static final String CONFIG_SUFFIX = "-cas-oauth";
+  private static final String CAS_PROVIDER_PREFIX = "cas-oauth:";
+  private static final String PROTECTED_RESOURCE_URL = "%s/oauth2.0/profile";
+
+  private final String rootUrl;
+  private final boolean fixLegacyUserId;
+  private final OAuthService service;
+
+  @Inject
+  CasOAuthService(
+      PluginConfigFactory cfgFactory,
+      @PluginName String pluginName,
+      @CanonicalWebUrl Provider<String> urlProvider) {
+    PluginConfig cfg = cfgFactory.getFromGerritConfig(pluginName + CONFIG_SUFFIX);
+    rootUrl = cfg.getString(InitOAuth.ROOT_URL);
+    String canonicalWebUrl = CharMatcher.is('/').trimTrailingFrom(urlProvider.get()) + "/";
+    fixLegacyUserId = cfg.getBoolean(InitOAuth.FIX_LEGACY_USER_ID, false);
+    service =
+        new ServiceBuilder()
+            .provider(new CasApi(rootUrl))
+            .apiKey(cfg.getString(InitOAuth.CLIENT_ID))
+            .apiSecret(cfg.getString(InitOAuth.CLIENT_SECRET))
+            .callback(canonicalWebUrl + "oauth")
+            .build();
+  }
+
+  @Override
+  public OAuthUserInfo getUserInfo(OAuthToken token) throws IOException {
+    final String protectedResourceUrl = String.format(PROTECTED_RESOURCE_URL, rootUrl);
+    OAuthRequest request = new OAuthRequest(Verb.GET, protectedResourceUrl);
+    Token t = new Token(token.getToken(), token.getSecret(), token.getRaw());
+    service.signRequest(t, request);
+
+    Response response = request.send();
+    if (response.getCode() != HttpServletResponse.SC_OK) {
+      throw new IOException(
+          String.format(
+              "Status %s (%s) for request %s",
+              response.getCode(), response.getBody(), request.getUrl()));
+    }
+
+    if (log.isDebugEnabled()) {
+      log.debug("User info response: {}", response.getBody());
+    }
+
+    JsonElement userJson = JSON.newGson().fromJson(response.getBody(), JsonElement.class);
+    if (!userJson.isJsonObject()) {
+      throw new IOException(String.format("Invalid JSON '%s': not a JSON Object", userJson));
+    }
+    JsonObject jsonObject = userJson.getAsJsonObject();
+
+    JsonElement id = jsonObject.get("id");
+    if (id == null || id.isJsonNull()) {
+      throw new IOException(String.format("CAS response missing id: %s", response.getBody()));
+    }
+
+    JsonElement attrListJson = jsonObject.get("attributes");
+    if (attrListJson == null) {
+      throw new IOException(
+          String.format("CAS response missing attributes: %s", response.getBody()));
+    }
+
+    String email = null, name = null, login = null;
+
+    if (attrListJson.isJsonArray()) {
+      // It is possible for CAS to be configured to not return any attributes (email, name, login),
+      // in which case,
+      // CAS returns an empty JSON object "attributes":{}, rather than "null" or an empty JSON array
+      // "attributes": []
+
+      JsonArray attrJson = attrListJson.getAsJsonArray();
+      for (JsonElement elem : attrJson) {
+        if (elem == null || !elem.isJsonObject()) {
+          throw new IOException(String.format("Invalid JSON '%s': not a JSON Object", elem));
+        }
+        JsonObject obj = elem.getAsJsonObject();
+
+        String property = getStringElement(obj, "email");
+        if (property != null) email = property;
+        property = getStringElement(obj, "name");
+        if (property != null) name = property;
+        property = getStringElement(obj, "login");
+        if (property != null) login = property;
+      }
+    }
+
+    return new OAuthUserInfo(
+        CAS_PROVIDER_PREFIX + id.getAsString(),
+        login,
+        email,
+        name,
+        fixLegacyUserId ? id.getAsString() : null);
+  }
+
+  private String getStringElement(JsonObject o, String name) {
+    JsonElement elem = o.get(name);
+    if (elem == null || elem.isJsonNull()) return null;
+
+    return elem.getAsString();
+  }
+
+  @Override
+  public OAuthToken getAccessToken(OAuthVerifier rv) {
+    Verifier vi = new Verifier(rv.getValue());
+    Token to = service.getAccessToken(null, vi);
+    return new OAuthToken(to.getToken(), to.getSecret(), to.getRawResponse());
+  }
+
+  @Override
+  public String getAuthorizationUrl() {
+    return service.getAuthorizationUrl(null);
+  }
+
+  @Override
+  public String getVersion() {
+    return service.getVersion();
+  }
+
+  @Override
+  public String getName() {
+    return "Generic CAS OAuth2";
+  }
+}
diff --git a/app/gerrit/gerrit-oauth-provider/src/main/java/com/googlesource/gerrit/plugins/oauth/DexApi.java b/app/gerrit/gerrit-oauth-provider/src/main/java/com/googlesource/gerrit/plugins/oauth/DexApi.java
new file mode 100644
index 0000000..2386e24
--- /dev/null
+++ b/app/gerrit/gerrit-oauth-provider/src/main/java/com/googlesource/gerrit/plugins/oauth/DexApi.java
@@ -0,0 +1,65 @@
+// Copyright (C) 2017 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.oauth;
+
+import org.scribe.builder.api.DefaultApi20;
+import org.scribe.extractors.AccessTokenExtractor;
+import org.scribe.extractors.JsonTokenExtractor;
+import org.scribe.model.OAuthConfig;
+import org.scribe.model.Verb;
+import org.scribe.oauth.OAuthService;
+import org.scribe.utils.OAuthEncoder;
+
+public class DexApi extends DefaultApi20 {
+
+  private static final String AUTHORIZE_URL =
+      "%s/dex/auth?client_id=%s&response_type=code&redirect_uri=%s&scope=%s";
+
+  private final String rootUrl;
+
+  public DexApi(String rootUrl) {
+    this.rootUrl = rootUrl;
+  }
+
+  @Override
+  public String getAuthorizationUrl(OAuthConfig config) {
+    return String.format(
+        AUTHORIZE_URL,
+        rootUrl,
+        config.getApiKey(),
+        OAuthEncoder.encode(config.getCallback()),
+        config.getScope().replaceAll(" ", "+"));
+  }
+
+  @Override
+  public String getAccessTokenEndpoint() {
+    return String.format("%s/dex/token", rootUrl);
+  }
+
+  @Override
+  public Verb getAccessTokenVerb() {
+    return Verb.POST;
+  }
+
+  @Override
+  public OAuthService createService(OAuthConfig config) {
+    return new OAuth20ServiceImpl(this, config);
+  }
+
+  @Override
+  public AccessTokenExtractor getAccessTokenExtractor() {
+    return new JsonTokenExtractor();
+  }
+}
diff --git a/app/gerrit/gerrit-oauth-provider/src/main/java/com/googlesource/gerrit/plugins/oauth/DexOAuthService.java b/app/gerrit/gerrit-oauth-provider/src/main/java/com/googlesource/gerrit/plugins/oauth/DexOAuthService.java
new file mode 100644
index 0000000..255d394
--- /dev/null
+++ b/app/gerrit/gerrit-oauth-provider/src/main/java/com/googlesource/gerrit/plugins/oauth/DexOAuthService.java
@@ -0,0 +1,137 @@
+// Copyright (C) 2017 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.oauth;
+
+import static com.google.gerrit.json.OutputFormat.JSON;
+
+import com.google.common.base.CharMatcher;
+import com.google.common.base.Preconditions;
+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.gson.JsonElement;
+import com.google.gson.JsonObject;
+import com.google.inject.Inject;
+import com.google.inject.Provider;
+import com.google.inject.Singleton;
+import java.io.IOException;
+import org.apache.commons.codec.binary.Base64;
+import org.scribe.builder.ServiceBuilder;
+import org.scribe.model.Token;
+import org.scribe.model.Verifier;
+import org.scribe.oauth.OAuthService;
+
+@Singleton
+public class DexOAuthService implements OAuthServiceProvider {
+
+  static final String CONFIG_SUFFIX = "-dex-oauth";
+  private static final String DEX_PROVIDER_PREFIX = "dex-oauth:";
+  private final OAuthService service;
+  private final String rootUrl;
+  private final String domain;
+  private final String serviceName;
+
+  @Inject
+  DexOAuthService(
+      PluginConfigFactory cfgFactory,
+      @PluginName String pluginName,
+      @CanonicalWebUrl Provider<String> urlProvider) {
+    PluginConfig cfg = cfgFactory.getFromGerritConfig(pluginName + CONFIG_SUFFIX);
+    String canonicalWebUrl = CharMatcher.is('/').trimTrailingFrom(urlProvider.get()) + "/";
+
+    rootUrl = cfg.getString(InitOAuth.ROOT_URL);
+    domain = cfg.getString(InitOAuth.DOMAIN, null);
+    serviceName = cfg.getString(InitOAuth.SERVICE_NAME, "Dex OAuth2");
+
+    service =
+        new ServiceBuilder()
+            .provider(new DexApi(rootUrl))
+            .apiKey(cfg.getString(InitOAuth.CLIENT_ID))
+            .apiSecret(cfg.getString(InitOAuth.CLIENT_SECRET))
+            .scope("openid profile email offline_access")
+            .callback(canonicalWebUrl + "oauth")
+            .build();
+  }
+
+  private String parseJwt(String input) {
+    String[] parts = input.split("\\.");
+    Preconditions.checkState(parts.length == 3);
+    Preconditions.checkNotNull(parts[1]);
+    return new String(Base64.decodeBase64(parts[1]));
+  }
+
+  @Override
+  public OAuthUserInfo getUserInfo(OAuthToken token) throws IOException {
+    JsonElement tokenJson = JSON.newGson().fromJson(token.getRaw(), JsonElement.class);
+    JsonObject tokenObject = tokenJson.getAsJsonObject();
+    JsonElement id_token = tokenObject.get("id_token");
+
+    JsonElement claimJson =
+        JSON.newGson().fromJson(parseJwt(id_token.getAsString()), JsonElement.class);
+
+    // Dex does not support basic profile currently (2017-09), extracting info
+    // from access token claim
+
+    JsonObject claimObject = claimJson.getAsJsonObject();
+    JsonElement emailElement = claimObject.get("email");
+    JsonElement nameElement = claimObject.get("name");
+    if (emailElement == null || emailElement.isJsonNull()) {
+      throw new IOException("Response doesn't contain email field");
+    }
+    if (nameElement == null || nameElement.isJsonNull()) {
+      throw new IOException("Response doesn't contain name field");
+    }
+    String email = emailElement.getAsString();
+    String name = nameElement.getAsString();
+    String username = email;
+    if (domain != null && domain.length() > 0) {
+      username = email.replace("@" + domain, "");
+    }
+
+    return new OAuthUserInfo(
+        DEX_PROVIDER_PREFIX + email /*externalId*/,
+        username /*username*/,
+        email /*email*/,
+        name /*displayName*/,
+        null /*claimedIdentity*/);
+  }
+
+  @Override
+  public OAuthToken getAccessToken(OAuthVerifier rv) {
+    Verifier vi = new Verifier(rv.getValue());
+    Token to = service.getAccessToken(null, vi);
+    return new OAuthToken(to.getToken(), to.getSecret(), to.getRawResponse());
+  }
+
+  @Override
+  public String getAuthorizationUrl() {
+    return service.getAuthorizationUrl(null);
+  }
+
+  @Override
+  public String getVersion() {
+    return service.getVersion();
+  }
+
+  @Override
+  public String getName() {
+    return serviceName;
+  }
+}
diff --git a/app/gerrit/gerrit-oauth-provider/src/main/java/com/googlesource/gerrit/plugins/oauth/DisabledOAuthLoginProvider.java b/app/gerrit/gerrit-oauth-provider/src/main/java/com/googlesource/gerrit/plugins/oauth/DisabledOAuthLoginProvider.java
new file mode 100644
index 0000000..4a62e3d
--- /dev/null
+++ b/app/gerrit/gerrit-oauth-provider/src/main/java/com/googlesource/gerrit/plugins/oauth/DisabledOAuthLoginProvider.java
@@ -0,0 +1,38 @@
+// Copyright (C) 2017 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.oauth;
+
+import com.google.gerrit.extensions.annotations.PluginName;
+import com.google.gerrit.extensions.auth.oauth.OAuthLoginProvider;
+import com.google.gerrit.extensions.auth.oauth.OAuthUserInfo;
+import com.google.inject.Inject;
+import com.google.inject.Singleton;
+import java.io.IOException;
+
+@Singleton
+class DisabledOAuthLoginProvider implements OAuthLoginProvider {
+  private final String pluginName;
+
+  @Inject
+  DisabledOAuthLoginProvider(@PluginName String pluginName) {
+    this.pluginName = pluginName;
+  }
+
+  @Override
+  public OAuthUserInfo login(String username, String secret) throws IOException {
+    throw new UnsupportedOperationException(
+        "git over oauth is not implemented by " + pluginName + " plugin");
+  }
+}
diff --git a/app/gerrit/gerrit-oauth-provider/src/main/java/com/googlesource/gerrit/plugins/oauth/Facebook2Api.java b/app/gerrit/gerrit-oauth-provider/src/main/java/com/googlesource/gerrit/plugins/oauth/Facebook2Api.java
new file mode 100644
index 0000000..a547bfb
--- /dev/null
+++ b/app/gerrit/gerrit-oauth-provider/src/main/java/com/googlesource/gerrit/plugins/oauth/Facebook2Api.java
@@ -0,0 +1,25 @@
+// Copyright (C) 2018 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.oauth;
+
+import org.scribe.builder.api.FacebookApi;
+import org.scribe.extractors.AccessTokenExtractor;
+
+public class Facebook2Api extends FacebookApi {
+  @Override
+  public AccessTokenExtractor getAccessTokenExtractor() {
+    return OAuth2AccessTokenJsonExtractor.instance();
+  }
+}
diff --git a/app/gerrit/gerrit-oauth-provider/src/main/java/com/googlesource/gerrit/plugins/oauth/FacebookOAuthService.java b/app/gerrit/gerrit-oauth-provider/src/main/java/com/googlesource/gerrit/plugins/oauth/FacebookOAuthService.java
new file mode 100644
index 0000000..bc5818a
--- /dev/null
+++ b/app/gerrit/gerrit-oauth-provider/src/main/java/com/googlesource/gerrit/plugins/oauth/FacebookOAuthService.java
@@ -0,0 +1,142 @@
+// Copyright (C) 2017 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.oauth;
+
+import static com.google.gerrit.json.OutputFormat.JSON;
+
+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.gson.JsonElement;
+import com.google.gson.JsonObject;
+import com.google.inject.Inject;
+import com.google.inject.Provider;
+import com.google.inject.Singleton;
+import java.io.IOException;
+import javax.servlet.http.HttpServletResponse;
+import org.scribe.builder.ServiceBuilder;
+import org.scribe.model.OAuthRequest;
+import org.scribe.model.Response;
+import org.scribe.model.Token;
+import org.scribe.model.Verb;
+import org.scribe.model.Verifier;
+import org.scribe.oauth.OAuthService;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+@Singleton
+class FacebookOAuthService implements OAuthServiceProvider {
+  private static final Logger log = LoggerFactory.getLogger(FacebookOAuthService.class);
+  static final String CONFIG_SUFFIX = "-facebook-oauth";
+  private static final String PROTECTED_RESOURCE_URL = "https://graph.facebook.com/me";
+
+  private static final String FACEBOOK_PROVIDER_PREFIX = "facebook-oauth:";
+  private static final String SCOPE = "email";
+  private static final String FIELDS_QUERY = "fields";
+  private static final String FIELDS = "email,name";
+  private final OAuthService service;
+
+  @Inject
+  FacebookOAuthService(
+      PluginConfigFactory cfgFactory,
+      @PluginName String pluginName,
+      @CanonicalWebUrl Provider<String> urlProvider) {
+
+    PluginConfig cfg = cfgFactory.getFromGerritConfig(pluginName + CONFIG_SUFFIX);
+    String canonicalWebUrl = CharMatcher.is('/').trimTrailingFrom(urlProvider.get()) + "/";
+
+    service =
+        new ServiceBuilder()
+            .provider(Facebook2Api.class)
+            .apiKey(cfg.getString(InitOAuth.CLIENT_ID))
+            .apiSecret(cfg.getString(InitOAuth.CLIENT_SECRET))
+            .callback(canonicalWebUrl + "oauth")
+            .scope(SCOPE)
+            .build();
+  }
+
+  @Override
+  public OAuthUserInfo getUserInfo(OAuthToken token) throws IOException {
+    OAuthRequest request = new OAuthRequest(Verb.GET, PROTECTED_RESOURCE_URL);
+    Token t = new Token(token.getToken(), token.getSecret(), token.getRaw());
+    request.addQuerystringParameter(FIELDS_QUERY, FIELDS);
+    service.signRequest(t, request);
+    Response response = request.send();
+
+    if (response.getCode() != HttpServletResponse.SC_OK) {
+      throw new IOException(
+          String.format(
+              "Status %s (%s) for request %s",
+              response.getCode(), response.getBody(), request.getUrl()));
+    }
+    JsonElement userJson = JSON.newGson().fromJson(response.getBody(), JsonElement.class);
+
+    if (log.isDebugEnabled()) {
+      log.debug("User info response: {}", response.getBody());
+    }
+    if (userJson.isJsonObject()) {
+      JsonObject jsonObject = userJson.getAsJsonObject();
+      JsonElement id = jsonObject.get("id");
+      if (id == null || id.isJsonNull()) {
+        throw new IOException("Response doesn't contain id field");
+      }
+      JsonElement email = jsonObject.get("email");
+      JsonElement name = jsonObject.get("name");
+      // Heads up!
+      // Lets keep `login` equal to `email`, since `username` field is
+      // deprecated for Facebook API versions v2.0 and higher
+      JsonElement login = jsonObject.get("email");
+
+      return new OAuthUserInfo(
+          FACEBOOK_PROVIDER_PREFIX + id.getAsString(),
+          login == null || login.isJsonNull() ? null : login.getAsString(),
+          email == null || email.isJsonNull() ? null : email.getAsString(),
+          name == null || name.isJsonNull() ? null : name.getAsString(),
+          null);
+    }
+
+    throw new IOException(String.format("Invalid JSON '%s': not a JSON Object", userJson));
+  }
+
+  @Override
+  public OAuthToken getAccessToken(OAuthVerifier rv) {
+    Verifier vi = new Verifier(rv.getValue());
+    Token to = service.getAccessToken(null, vi);
+    OAuthToken result = new OAuthToken(to.getToken(), to.getSecret(), to.getRawResponse());
+
+    return result;
+  }
+
+  @Override
+  public String getAuthorizationUrl() {
+    return service.getAuthorizationUrl(null);
+  }
+
+  @Override
+  public String getVersion() {
+    return service.getVersion();
+  }
+
+  @Override
+  public String getName() {
+    return "Facebook OAuth2";
+  }
+}
diff --git a/app/gerrit/gerrit-oauth-provider/src/main/java/com/googlesource/gerrit/plugins/oauth/GitHub2Api.java b/app/gerrit/gerrit-oauth-provider/src/main/java/com/googlesource/gerrit/plugins/oauth/GitHub2Api.java
new file mode 100644
index 0000000..4b8419b
--- /dev/null
+++ b/app/gerrit/gerrit-oauth-provider/src/main/java/com/googlesource/gerrit/plugins/oauth/GitHub2Api.java
@@ -0,0 +1,35 @@
+// 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.oauth;
+
+import org.scribe.builder.api.DefaultApi20;
+import org.scribe.model.OAuthConfig;
+import org.scribe.utils.OAuthEncoder;
+
+public class GitHub2Api extends DefaultApi20 {
+  private static final String AUTHORIZE_URL =
+      "https://github.com/login/oauth/authorize?client_id=%s&redirect_uri=%s";
+
+  @Override
+  public String getAccessTokenEndpoint() {
+    return "https://github.com/login/oauth/access_token";
+  }
+
+  @Override
+  public String getAuthorizationUrl(OAuthConfig config) {
+    return String.format(
+        AUTHORIZE_URL, config.getApiKey(), OAuthEncoder.encode(config.getCallback()));
+  }
+}
diff --git a/app/gerrit/gerrit-oauth-provider/src/main/java/com/googlesource/gerrit/plugins/oauth/GitHubOAuthService.java b/app/gerrit/gerrit-oauth-provider/src/main/java/com/googlesource/gerrit/plugins/oauth/GitHubOAuthService.java
new file mode 100644
index 0000000..1c73c0e
--- /dev/null
+++ b/app/gerrit/gerrit-oauth-provider/src/main/java/com/googlesource/gerrit/plugins/oauth/GitHubOAuthService.java
@@ -0,0 +1,132 @@
+// 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.oauth;
+
+import static com.google.gerrit.json.OutputFormat.JSON;
+
+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.gson.JsonElement;
+import com.google.gson.JsonObject;
+import com.google.inject.Inject;
+import com.google.inject.Provider;
+import com.google.inject.Singleton;
+import java.io.IOException;
+import javax.servlet.http.HttpServletResponse;
+import org.scribe.builder.ServiceBuilder;
+import org.scribe.model.OAuthRequest;
+import org.scribe.model.Response;
+import org.scribe.model.Token;
+import org.scribe.model.Verb;
+import org.scribe.model.Verifier;
+import org.scribe.oauth.OAuthService;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+@Singleton
+class GitHubOAuthService implements OAuthServiceProvider {
+  private static final Logger log = LoggerFactory.getLogger(GitHubOAuthService.class);
+  static final String CONFIG_SUFFIX = "-github-oauth";
+  private static final String GITHUB_PROVIDER_PREFIX = "github-oauth:";
+  private static final String PROTECTED_RESOURCE_URL = "https://api.github.com/user";
+
+  private static final String SCOPE = "user:email";
+  private final boolean fixLegacyUserId;
+  private final OAuthService service;
+
+  @Inject
+  GitHubOAuthService(
+      PluginConfigFactory cfgFactory,
+      @PluginName String pluginName,
+      @CanonicalWebUrl Provider<String> urlProvider) {
+    PluginConfig cfg = cfgFactory.getFromGerritConfig(pluginName + CONFIG_SUFFIX);
+    String canonicalWebUrl = CharMatcher.is('/').trimTrailingFrom(urlProvider.get()) + "/";
+    fixLegacyUserId = cfg.getBoolean(InitOAuth.FIX_LEGACY_USER_ID, false);
+    service =
+        new ServiceBuilder()
+            .provider(GitHub2Api.class)
+            .apiKey(cfg.getString(InitOAuth.CLIENT_ID))
+            .apiSecret(cfg.getString(InitOAuth.CLIENT_SECRET))
+            .callback(canonicalWebUrl + "oauth")
+            .scope(SCOPE)
+            .build();
+  }
+
+  @Override
+  public OAuthUserInfo getUserInfo(OAuthToken token) throws IOException {
+    OAuthRequest request = new OAuthRequest(Verb.GET, PROTECTED_RESOURCE_URL);
+    Token t = new Token(token.getToken(), token.getSecret(), token.getRaw());
+    service.signRequest(t, request);
+    Response response = request.send();
+    if (response.getCode() != HttpServletResponse.SC_OK) {
+      throw new IOException(
+          String.format(
+              "Status %s (%s) for request %s",
+              response.getCode(), response.getBody(), request.getUrl()));
+    }
+    JsonElement userJson = JSON.newGson().fromJson(response.getBody(), JsonElement.class);
+    if (log.isDebugEnabled()) {
+      log.debug("User info response: {}", response.getBody());
+    }
+    if (userJson.isJsonObject()) {
+      JsonObject jsonObject = userJson.getAsJsonObject();
+      JsonElement id = jsonObject.get("id");
+      if (id == null || id.isJsonNull()) {
+        throw new IOException("Response doesn't contain id field");
+      }
+      JsonElement email = jsonObject.get("email");
+      JsonElement name = jsonObject.get("name");
+      JsonElement login = jsonObject.get("login");
+      return new OAuthUserInfo(
+          GITHUB_PROVIDER_PREFIX + id.getAsString(),
+          login == null || login.isJsonNull() ? null : login.getAsString(),
+          email == null || email.isJsonNull() ? null : email.getAsString(),
+          name == null || name.isJsonNull() ? null : name.getAsString(),
+          fixLegacyUserId ? id.getAsString() : null);
+    }
+
+    throw new IOException(String.format("Invalid JSON '%s': not a JSON Object", userJson));
+  }
+
+  @Override
+  public OAuthToken getAccessToken(OAuthVerifier rv) {
+    Verifier vi = new Verifier(rv.getValue());
+    Token to = service.getAccessToken(null, vi);
+    OAuthToken result = new OAuthToken(to.getToken(), to.getSecret(), to.getRawResponse());
+    return result;
+  }
+
+  @Override
+  public String getAuthorizationUrl() {
+    return service.getAuthorizationUrl(null);
+  }
+
+  @Override
+  public String getVersion() {
+    return service.getVersion();
+  }
+
+  @Override
+  public String getName() {
+    return "GitHub OAuth2";
+  }
+}
diff --git a/app/gerrit/gerrit-oauth-provider/src/main/java/com/googlesource/gerrit/plugins/oauth/GitLabApi.java b/app/gerrit/gerrit-oauth-provider/src/main/java/com/googlesource/gerrit/plugins/oauth/GitLabApi.java
new file mode 100644
index 0000000..db0851f
--- /dev/null
+++ b/app/gerrit/gerrit-oauth-provider/src/main/java/com/googlesource/gerrit/plugins/oauth/GitLabApi.java
@@ -0,0 +1,57 @@
+// Copyright (C) 2017 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.oauth;
+
+import org.scribe.builder.api.DefaultApi20;
+import org.scribe.extractors.AccessTokenExtractor;
+import org.scribe.model.OAuthConfig;
+import org.scribe.model.Verb;
+import org.scribe.oauth.OAuthService;
+
+public class GitLabApi extends DefaultApi20 {
+  private static final String AUTHORIZE_URL =
+      "%s/oauth/authorize?client_id=%s&response_type=code&redirect_uri=%s";
+
+  private final String rootUrl;
+
+  public GitLabApi(String rootUrl) {
+    this.rootUrl = rootUrl;
+  }
+
+  @Override
+  public String getAuthorizationUrl(OAuthConfig config) {
+    return String.format(AUTHORIZE_URL, rootUrl, config.getApiKey(), config.getCallback());
+  }
+
+  @Override
+  public String getAccessTokenEndpoint() {
+    return String.format("%s/oauth/token", rootUrl);
+  }
+
+  @Override
+  public Verb getAccessTokenVerb() {
+    return Verb.POST;
+  }
+
+  @Override
+  public OAuthService createService(OAuthConfig config) {
+    return new OAuth20ServiceImpl(this, config);
+  }
+
+  @Override
+  public AccessTokenExtractor getAccessTokenExtractor() {
+    return OAuth2AccessTokenJsonExtractor.instance();
+  }
+}
diff --git a/app/gerrit/gerrit-oauth-provider/src/main/java/com/googlesource/gerrit/plugins/oauth/GitLabOAuthService.java b/app/gerrit/gerrit-oauth-provider/src/main/java/com/googlesource/gerrit/plugins/oauth/GitLabOAuthService.java
new file mode 100644
index 0000000..ed4c456
--- /dev/null
+++ b/app/gerrit/gerrit-oauth-provider/src/main/java/com/googlesource/gerrit/plugins/oauth/GitLabOAuthService.java
@@ -0,0 +1,126 @@
+// Copyright (C) 2017 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.oauth;
+
+import static com.google.gerrit.json.OutputFormat.JSON;
+import static javax.servlet.http.HttpServletResponse.SC_OK;
+import static org.slf4j.LoggerFactory.getLogger;
+
+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.gson.JsonElement;
+import com.google.gson.JsonObject;
+import com.google.inject.Inject;
+import com.google.inject.Provider;
+import com.google.inject.Singleton;
+import java.io.IOException;
+import org.scribe.builder.ServiceBuilder;
+import org.scribe.model.OAuthRequest;
+import org.scribe.model.Response;
+import org.scribe.model.Token;
+import org.scribe.model.Verb;
+import org.scribe.model.Verifier;
+import org.scribe.oauth.OAuthService;
+import org.slf4j.Logger;
+
+@Singleton
+public class GitLabOAuthService implements OAuthServiceProvider {
+  private static final Logger log = getLogger(GitLabOAuthService.class);
+  static final String CONFIG_SUFFIX = "-gitlab-oauth";
+  private static final String PROTECTED_RESOURCE_URL = "%s/api/v3/user";
+  private static final String GITLAB_PROVIDER_PREFIX = "gitlab-oauth:";
+  private final OAuthService service;
+  private final String rootUrl;
+
+  @Inject
+  GitLabOAuthService(
+      PluginConfigFactory cfgFactory,
+      @PluginName String pluginName,
+      @CanonicalWebUrl Provider<String> urlProvider) {
+    PluginConfig cfg = cfgFactory.getFromGerritConfig(pluginName + CONFIG_SUFFIX);
+    String canonicalWebUrl = CharMatcher.is('/').trimTrailingFrom(urlProvider.get()) + "/";
+    rootUrl = cfg.getString(InitOAuth.ROOT_URL);
+    service =
+        new ServiceBuilder()
+            .provider(new GitLabApi(rootUrl))
+            .apiKey(cfg.getString(InitOAuth.CLIENT_ID))
+            .apiSecret(cfg.getString(InitOAuth.CLIENT_SECRET))
+            .callback(canonicalWebUrl + "oauth")
+            .build();
+  }
+
+  @Override
+  public OAuthUserInfo getUserInfo(OAuthToken token) throws IOException {
+    final String protectedResourceUrl = String.format(PROTECTED_RESOURCE_URL, rootUrl);
+    OAuthRequest request = new OAuthRequest(Verb.GET, protectedResourceUrl);
+    Token t = new Token(token.getToken(), token.getSecret(), token.getRaw());
+    service.signRequest(t, request);
+
+    Response response = request.send();
+    if (response.getCode() != SC_OK) {
+      throw new IOException(
+          String.format(
+              "Status %s (%s) for request %s",
+              response.getCode(), response.getBody(), request.getUrl()));
+    }
+    JsonElement userJson = JSON.newGson().fromJson(response.getBody(), JsonElement.class);
+    if (log.isDebugEnabled()) {
+      log.debug("User info response: {}", response.getBody());
+    }
+    JsonObject jsonObject = userJson.getAsJsonObject();
+    if (jsonObject == null || jsonObject.isJsonNull()) {
+      throw new IOException("Response doesn't contain 'user' field" + jsonObject);
+    }
+    JsonElement id = jsonObject.get("id");
+    JsonElement username = jsonObject.get("username");
+    JsonElement email = jsonObject.get("email");
+    JsonElement name = jsonObject.get("name");
+    return new OAuthUserInfo(
+        GITLAB_PROVIDER_PREFIX + id.getAsString(),
+        username == null || username.isJsonNull() ? null : username.getAsString(),
+        email == null || email.isJsonNull() ? null : email.getAsString(),
+        name == null || name.isJsonNull() ? null : name.getAsString(),
+        null);
+  }
+
+  @Override
+  public OAuthToken getAccessToken(OAuthVerifier rv) {
+    Verifier vi = new Verifier(rv.getValue());
+    Token to = service.getAccessToken(null, vi);
+    return new OAuthToken(to.getToken(), to.getSecret(), to.getRawResponse());
+  }
+
+  @Override
+  public String getAuthorizationUrl() {
+    return service.getAuthorizationUrl(null);
+  }
+
+  @Override
+  public String getVersion() {
+    return service.getVersion();
+  }
+
+  @Override
+  public String getName() {
+    return "GitLab OAuth2";
+  }
+}
diff --git a/app/gerrit/gerrit-oauth-provider/src/main/java/com/googlesource/gerrit/plugins/oauth/Google2Api.java b/app/gerrit/gerrit-oauth-provider/src/main/java/com/googlesource/gerrit/plugins/oauth/Google2Api.java
new file mode 100644
index 0000000..88c640d
--- /dev/null
+++ b/app/gerrit/gerrit-oauth-provider/src/main/java/com/googlesource/gerrit/plugins/oauth/Google2Api.java
@@ -0,0 +1,63 @@
+// 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.oauth;
+
+import static org.scribe.utils.OAuthEncoder.encode;
+
+import org.scribe.builder.api.DefaultApi20;
+import org.scribe.extractors.AccessTokenExtractor;
+import org.scribe.model.OAuthConfig;
+import org.scribe.model.Verb;
+import org.scribe.oauth.OAuthService;
+import org.scribe.utils.Preconditions;
+
+// Source: https://github.com/FeedTheCoffers/scribe-java-extras
+// License: Apache 2
+// https://github.com/FeedTheCoffers/scribe-java-extras/blob/master/pom.xml
+public class Google2Api extends DefaultApi20 {
+  private static final String AUTHORIZE_URL =
+      "https://accounts.google.com/o/oauth2/auth?response_type=code&client_id=%s&redirect_uri=%s&scope=%s";
+
+  @Override
+  public String getAccessTokenEndpoint() {
+    return "https://accounts.google.com/o/oauth2/token";
+  }
+
+  @Override
+  public String getAuthorizationUrl(OAuthConfig config) {
+    Preconditions.checkValidUrl(
+        config.getCallback(), "Must provide a valid url as callback. Google does not support OOB");
+    Preconditions.checkEmptyString(
+        config.getScope(), "Must provide a valid value as scope. Google does not support no scope");
+
+    return String.format(
+        AUTHORIZE_URL, config.getApiKey(), encode(config.getCallback()), encode(config.getScope()));
+  }
+
+  @Override
+  public Verb getAccessTokenVerb() {
+    return Verb.POST;
+  }
+
+  @Override
+  public OAuthService createService(OAuthConfig config) {
+    return new OAuth20ServiceImpl(this, config);
+  }
+
+  @Override
+  public AccessTokenExtractor getAccessTokenExtractor() {
+    return OAuth2AccessTokenJsonExtractor.instance();
+  }
+}
diff --git a/app/gerrit/gerrit-oauth-provider/src/main/java/com/googlesource/gerrit/plugins/oauth/GoogleOAuthService.java b/app/gerrit/gerrit-oauth-provider/src/main/java/com/googlesource/gerrit/plugins/oauth/GoogleOAuthService.java
new file mode 100644
index 0000000..d6fcacf
--- /dev/null
+++ b/app/gerrit/gerrit-oauth-provider/src/main/java/com/googlesource/gerrit/plugins/oauth/GoogleOAuthService.java
@@ -0,0 +1,233 @@
+// 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.oauth;
+
+import static com.google.gerrit.json.OutputFormat.JSON;
+
+import com.google.common.base.CharMatcher;
+import com.google.common.base.Preconditions;
+import com.google.common.base.Strings;
+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.gson.JsonElement;
+import com.google.gson.JsonObject;
+import com.google.inject.Inject;
+import com.google.inject.Provider;
+import com.google.inject.Singleton;
+import java.io.IOException;
+import java.io.UnsupportedEncodingException;
+import java.net.URLEncoder;
+import java.nio.charset.StandardCharsets;
+import java.util.Arrays;
+import java.util.List;
+import javax.servlet.http.HttpServletResponse;
+import org.apache.commons.codec.binary.Base64;
+import org.scribe.builder.ServiceBuilder;
+import org.scribe.model.OAuthRequest;
+import org.scribe.model.Response;
+import org.scribe.model.Token;
+import org.scribe.model.Verb;
+import org.scribe.model.Verifier;
+import org.scribe.oauth.OAuthService;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+@Singleton
+class GoogleOAuthService implements OAuthServiceProvider {
+  private static final Logger log = LoggerFactory.getLogger(GoogleOAuthService.class);
+  static final String CONFIG_SUFFIX = "-google-oauth";
+  private static final String GOOGLE_PROVIDER_PREFIX = "google-oauth:";
+  private static final String PROTECTED_RESOURCE_URL =
+      "https://www.googleapis.com/oauth2/v2/userinfo";
+  private static final String SCOPE = "email profile";
+  private final OAuthService service;
+  private final String canonicalWebUrl;
+  private final List<String> domains;
+  private final boolean useEmailAsUsername;
+  private final boolean fixLegacyUserId;
+
+  @Inject
+  GoogleOAuthService(
+      PluginConfigFactory cfgFactory,
+      @PluginName String pluginName,
+      @CanonicalWebUrl Provider<String> urlProvider) {
+    PluginConfig cfg = cfgFactory.getFromGerritConfig(pluginName + CONFIG_SUFFIX);
+    this.canonicalWebUrl = CharMatcher.is('/').trimTrailingFrom(urlProvider.get()) + "/";
+    if (cfg.getBoolean(InitOAuth.LINK_TO_EXISTING_OPENID_ACCOUNT, false)) {
+      log.warn(
+          String.format(
+              "The support for: %s is disconinued", InitOAuth.LINK_TO_EXISTING_OPENID_ACCOUNT));
+    }
+    fixLegacyUserId = cfg.getBoolean(InitOAuth.FIX_LEGACY_USER_ID, false);
+    this.domains = Arrays.asList(cfg.getStringList(InitOAuth.DOMAIN));
+    this.useEmailAsUsername = cfg.getBoolean(InitOAuth.USE_EMAIL_AS_USERNAME, false);
+    this.service =
+        new ServiceBuilder()
+            .provider(Google2Api.class)
+            .apiKey(cfg.getString(InitOAuth.CLIENT_ID))
+            .apiSecret(cfg.getString(InitOAuth.CLIENT_SECRET))
+            .callback(canonicalWebUrl + "oauth")
+            .scope(SCOPE)
+            .build();
+    if (log.isDebugEnabled()) {
+      log.debug("OAuth2: canonicalWebUrl={}", canonicalWebUrl);
+      log.debug("OAuth2: scope={}", SCOPE);
+      log.debug("OAuth2: domains={}", domains);
+      log.debug("OAuth2: useEmailAsUsername={}", useEmailAsUsername);
+    }
+  }
+
+  @Override
+  public OAuthUserInfo getUserInfo(OAuthToken token) throws IOException {
+    OAuthRequest request = new OAuthRequest(Verb.GET, PROTECTED_RESOURCE_URL);
+    Token t = new Token(token.getToken(), token.getSecret(), token.getRaw());
+    service.signRequest(t, request);
+    Response response = request.send();
+    if (response.getCode() != HttpServletResponse.SC_OK) {
+      throw new IOException(
+          String.format(
+              "Status %s (%s) for request %s",
+              response.getCode(), response.getBody(), request.getUrl()));
+    }
+    JsonElement userJson = JSON.newGson().fromJson(response.getBody(), JsonElement.class);
+    if (log.isDebugEnabled()) {
+      log.debug("User info response: {}", response.getBody());
+    }
+    if (userJson.isJsonObject()) {
+      JsonObject jsonObject = userJson.getAsJsonObject();
+      JsonElement id = jsonObject.get("id");
+      if (id == null || id.isJsonNull()) {
+        throw new IOException("Response doesn't contain id field");
+      }
+      JsonElement email = jsonObject.get("email");
+      JsonElement name = jsonObject.get("name");
+      String login = null;
+
+      if (domains.size() > 0) {
+        boolean domainMatched = false;
+        JsonObject jwtToken = retrieveJWTToken(token);
+        String hdClaim = retrieveHostedDomain(jwtToken);
+        for (String domain : domains) {
+          if (domain.equalsIgnoreCase(hdClaim)) {
+            domainMatched = true;
+            break;
+          }
+        }
+        if (!domainMatched) {
+          // TODO(davido): improve error reporting in OAuth extension point
+          log.error("Error: hosted domain validation failed: {}", Strings.nullToEmpty(hdClaim));
+          return null;
+        }
+      }
+      if (useEmailAsUsername && !email.isJsonNull()) {
+        login = email.getAsString().split("@")[0];
+      }
+      return new OAuthUserInfo(
+          GOOGLE_PROVIDER_PREFIX + id.getAsString() /*externalId*/,
+          login /*username*/,
+          email == null || email.isJsonNull() ? null : email.getAsString() /*email*/,
+          name == null || name.isJsonNull() ? null : name.getAsString() /*displayName*/,
+          fixLegacyUserId ? id.getAsString() : null /*claimedIdentity*/);
+    }
+
+    throw new IOException(String.format("Invalid JSON '%s': not a JSON Object", userJson));
+  }
+
+  private JsonObject retrieveJWTToken(OAuthToken token) {
+    JsonElement idToken = JSON.newGson().fromJson(token.getRaw(), JsonElement.class);
+    if (idToken != null && idToken.isJsonObject()) {
+      JsonObject idTokenObj = idToken.getAsJsonObject();
+      JsonElement idTokenElement = idTokenObj.get("id_token");
+      if (idTokenElement != null && !idTokenElement.isJsonNull()) {
+        String payload = decodePayload(idTokenElement.getAsString());
+        if (!Strings.isNullOrEmpty(payload)) {
+          JsonElement tokenJsonElement = JSON.newGson().fromJson(payload, JsonElement.class);
+          if (tokenJsonElement.isJsonObject()) {
+            return tokenJsonElement.getAsJsonObject();
+          }
+        }
+      }
+    }
+    return null;
+  }
+
+  private static String retrieveHostedDomain(JsonObject jwtToken) {
+    JsonElement hdClaim = jwtToken.get("hd");
+    if (hdClaim != null && !hdClaim.isJsonNull()) {
+      String hd = hdClaim.getAsString();
+      log.debug("OAuth2: hd={}", hd);
+      return hd;
+    }
+    log.debug("OAuth2: JWT doesn't contain hd element");
+    return null;
+  }
+
+  /**
+   * Decode payload from JWT according to spec: "header.payload.signature"
+   *
+   * @param idToken Base64 encoded tripple, separated with dot
+   * @return openid_id part of payload, when contained, null otherwise
+   */
+  private static String decodePayload(String idToken) {
+    Preconditions.checkNotNull(idToken);
+    String[] jwtParts = idToken.split("\\.");
+    Preconditions.checkState(jwtParts.length == 3);
+    String payloadStr = jwtParts[1];
+    Preconditions.checkNotNull(payloadStr);
+    return new String(Base64.decodeBase64(payloadStr));
+  }
+
+  @Override
+  public OAuthToken getAccessToken(OAuthVerifier rv) {
+    Verifier vi = new Verifier(rv.getValue());
+    Token to = service.getAccessToken(null, vi);
+    OAuthToken result = new OAuthToken(to.getToken(), to.getSecret(), to.getRawResponse());
+    return result;
+  }
+
+  @Override
+  public String getAuthorizationUrl() {
+    String url = service.getAuthorizationUrl(null);
+    try {
+      if (domains.size() == 1) {
+        url += "&hd=" + URLEncoder.encode(domains.get(0), StandardCharsets.UTF_8.name());
+      } else if (domains.size() > 1) {
+        url += "&hd=*";
+      }
+    } catch (UnsupportedEncodingException e) {
+      throw new IllegalArgumentException(e);
+    }
+    if (log.isDebugEnabled()) {
+      log.debug("OAuth2: authorization URL={}", url);
+    }
+    return url;
+  }
+
+  @Override
+  public String getVersion() {
+    return service.getVersion();
+  }
+
+  @Override
+  public String getName() {
+    return "Google OAuth2";
+  }
+}
diff --git a/app/gerrit/gerrit-oauth-provider/src/main/java/com/googlesource/gerrit/plugins/oauth/HttpModule.java b/app/gerrit/gerrit-oauth-provider/src/main/java/com/googlesource/gerrit/plugins/oauth/HttpModule.java
new file mode 100644
index 0000000..e9e0b8f
--- /dev/null
+++ b/app/gerrit/gerrit-oauth-provider/src/main/java/com/googlesource/gerrit/plugins/oauth/HttpModule.java
@@ -0,0 +1,116 @@
+// 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.oauth;
+
+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.server.config.PluginConfig;
+import com.google.gerrit.server.config.PluginConfigFactory;
+import com.google.inject.Inject;
+import com.google.inject.servlet.ServletModule;
+
+class HttpModule extends ServletModule {
+
+  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 + GoogleOAuthService.CONFIG_SUFFIX);
+    if (cfg.getString(InitOAuth.CLIENT_ID) != null) {
+      bind(OAuthServiceProvider.class)
+          .annotatedWith(Exports.named(GoogleOAuthService.CONFIG_SUFFIX))
+          .to(GoogleOAuthService.class);
+    }
+
+    cfg = cfgFactory.getFromGerritConfig(pluginName + GitHubOAuthService.CONFIG_SUFFIX);
+    if (cfg.getString(InitOAuth.CLIENT_ID) != null) {
+      bind(OAuthServiceProvider.class)
+          .annotatedWith(Exports.named(GitHubOAuthService.CONFIG_SUFFIX))
+          .to(GitHubOAuthService.class);
+    }
+
+    cfg = cfgFactory.getFromGerritConfig(pluginName + BitbucketOAuthService.CONFIG_SUFFIX);
+    if (cfg.getString(InitOAuth.CLIENT_ID) != null) {
+      bind(OAuthServiceProvider.class)
+          .annotatedWith(Exports.named(BitbucketOAuthService.CONFIG_SUFFIX))
+          .to(BitbucketOAuthService.class);
+    }
+
+    cfg = cfgFactory.getFromGerritConfig(pluginName + CasOAuthService.CONFIG_SUFFIX);
+    if (cfg.getString(InitOAuth.CLIENT_ID) != null) {
+      bind(OAuthServiceProvider.class)
+          .annotatedWith(Exports.named(CasOAuthService.CONFIG_SUFFIX))
+          .to(CasOAuthService.class);
+    }
+
+    cfg = cfgFactory.getFromGerritConfig(pluginName + FacebookOAuthService.CONFIG_SUFFIX);
+    if (cfg.getString(InitOAuth.CLIENT_ID) != null) {
+      bind(OAuthServiceProvider.class)
+          .annotatedWith(Exports.named(FacebookOAuthService.CONFIG_SUFFIX))
+          .to(FacebookOAuthService.class);
+    }
+
+    cfg = cfgFactory.getFromGerritConfig(pluginName + GitLabOAuthService.CONFIG_SUFFIX);
+    if (cfg.getString(InitOAuth.CLIENT_ID) != null) {
+      bind(OAuthServiceProvider.class)
+          .annotatedWith(Exports.named(GitLabOAuthService.CONFIG_SUFFIX))
+          .to(GitLabOAuthService.class);
+    }
+
+    cfg = cfgFactory.getFromGerritConfig(pluginName + DexOAuthService.CONFIG_SUFFIX);
+    if (cfg.getString(InitOAuth.CLIENT_ID) != null) {
+      bind(OAuthServiceProvider.class)
+          .annotatedWith(Exports.named(DexOAuthService.CONFIG_SUFFIX))
+          .to(DexOAuthService.class);
+    }
+
+    cfg = cfgFactory.getFromGerritConfig(pluginName + KeycloakOAuthService.CONFIG_SUFFIX);
+    if (cfg.getString(InitOAuth.CLIENT_ID) != null) {
+      bind(OAuthServiceProvider.class)
+          .annotatedWith(Exports.named(KeycloakOAuthService.CONFIG_SUFFIX))
+          .to(KeycloakOAuthService.class);
+    }
+
+    cfg = cfgFactory.getFromGerritConfig(pluginName + Office365OAuthService.CONFIG_SUFFIX);
+    if (cfg.getString(InitOAuth.CLIENT_ID) != null) {
+      bind(OAuthServiceProvider.class)
+          .annotatedWith(Exports.named(Office365OAuthService.CONFIG_SUFFIX))
+          .to(Office365OAuthService.class);
+    }
+
+    cfg = cfgFactory.getFromGerritConfig(pluginName + WarsawHackerspaceOAuthService.CONFIG_SUFFIX);
+    if (cfg.getString(InitOAuth.CLIENT_ID) != null) {
+      bind(OAuthServiceProvider.class)
+          .annotatedWith(Exports.named(WarsawHackerspaceOAuthService.CONFIG_SUFFIX))
+          .to(WarsawHackerspaceOAuthService.class);
+    }
+
+    cfg = cfgFactory.getFromGerritConfig(pluginName + WarsawHackerspaceOAuthService.CONFIG_SUFFIX);
+    if (cfg.getString(InitOAuth.CLIENT_ID) != null) {
+      bind(OAuthServiceProvider.class)
+          .annotatedWith(Exports.named(WarsawHackerspaceOAuthService.CONFIG_SUFFIX))
+          .to(WarsawHackerspaceOAuthService.class);
+    }
+  }
+}
diff --git a/app/gerrit/gerrit-oauth-provider/src/main/java/com/googlesource/gerrit/plugins/oauth/InitOAuth.java b/app/gerrit/gerrit-oauth-provider/src/main/java/com/googlesource/gerrit/plugins/oauth/InitOAuth.java
new file mode 100644
index 0000000..50c0590
--- /dev/null
+++ b/app/gerrit/gerrit-oauth-provider/src/main/java/com/googlesource/gerrit/plugins/oauth/InitOAuth.java
@@ -0,0 +1,161 @@
+// 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.oauth;
+
+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 InitOAuth implements InitStep {
+  static final String PLUGIN_SECTION = "plugin";
+  static final String CLIENT_ID = "client-id";
+  static final String CLIENT_SECRET = "client-secret";
+  static final String LINK_TO_EXISTING_OPENID_ACCOUNT = "link-to-existing-openid-accounts";
+  static final String FIX_LEGACY_USER_ID = "fix-legacy-user-id";
+  static final String DOMAIN = "domain";
+  static final String USE_EMAIL_AS_USERNAME = "use-email-as-username";
+  static final String ROOT_URL = "root-url";
+  static final String REALM = "realm";
+  static final String SERVICE_NAME = "service-name";
+  static String FIX_LEGACY_USER_ID_QUESTION = "Fix legacy user id, without oauth provider prefix?";
+
+  private final ConsoleUI ui;
+  private final Section googleOAuthProviderSection;
+  private final Section githubOAuthProviderSection;
+  private final Section bitbucketOAuthProviderSection;
+  private final Section casOAuthProviderSection;
+  private final Section facebookOAuthProviderSection;
+  private final Section gitlabOAuthProviderSection;
+  private final Section dexOAuthProviderSection;
+  private final Section keycloakOAuthProviderSection;
+  private final Section office365OAuthProviderSection;
+  private final Section airVantageOAuthProviderSection;
+  private final Section warsawHackerspaceOAuthProviderSection;
+
+  @Inject
+  InitOAuth(ConsoleUI ui, Section.Factory sections, @PluginName String pluginName) {
+    this.ui = ui;
+    this.googleOAuthProviderSection =
+        sections.get(PLUGIN_SECTION, pluginName + GoogleOAuthService.CONFIG_SUFFIX);
+    this.githubOAuthProviderSection =
+        sections.get(PLUGIN_SECTION, pluginName + GitHubOAuthService.CONFIG_SUFFIX);
+    this.bitbucketOAuthProviderSection =
+        sections.get(PLUGIN_SECTION, pluginName + BitbucketOAuthService.CONFIG_SUFFIX);
+    this.casOAuthProviderSection =
+        sections.get(PLUGIN_SECTION, pluginName + CasOAuthService.CONFIG_SUFFIX);
+    this.facebookOAuthProviderSection =
+        sections.get(PLUGIN_SECTION, pluginName + FacebookOAuthService.CONFIG_SUFFIX);
+    this.gitlabOAuthProviderSection =
+        sections.get(PLUGIN_SECTION, pluginName + GitLabOAuthService.CONFIG_SUFFIX);
+    this.dexOAuthProviderSection =
+        sections.get(PLUGIN_SECTION, pluginName + DexOAuthService.CONFIG_SUFFIX);
+    this.keycloakOAuthProviderSection =
+        sections.get(PLUGIN_SECTION, pluginName + KeycloakOAuthService.CONFIG_SUFFIX);
+    this.office365OAuthProviderSection =
+        sections.get(PLUGIN_SECTION, pluginName + Office365OAuthService.CONFIG_SUFFIX);
+    this.airVantageOAuthProviderSection =
+        sections.get(PLUGIN_SECTION, pluginName + AirVantageOAuthService.CONFIG_SUFFIX);
+    this.warsawHackerspaceOAuthProviderSection = 
+        sections.get(PLUGIN_SECTION, pluginName + WarsawHackerspaceOAuthService.CONFIG_SUFFIX);
+  }
+
+  @Override
+  public void run() throws Exception {
+    ui.header("OAuth Authentication Provider");
+
+    boolean configureGoogleOAuthProvider =
+        ui.yesno(true, "Use Google OAuth provider for Gerrit login ?");
+    if (configureGoogleOAuthProvider) {
+      configureOAuth(googleOAuthProviderSection);
+      googleOAuthProviderSection.string(FIX_LEGACY_USER_ID_QUESTION, FIX_LEGACY_USER_ID, "false");
+    }
+
+    boolean configueGitHubOAuthProvider =
+        ui.yesno(true, "Use GitHub OAuth provider for Gerrit login ?");
+    if (configueGitHubOAuthProvider) {
+      configureOAuth(githubOAuthProviderSection);
+      githubOAuthProviderSection.string(FIX_LEGACY_USER_ID_QUESTION, FIX_LEGACY_USER_ID, "false");
+    }
+
+    boolean configureBitbucketOAuthProvider =
+        ui.yesno(true, "Use Bitbucket OAuth provider for Gerrit login ?");
+    if (configureBitbucketOAuthProvider) {
+      configureOAuth(bitbucketOAuthProviderSection);
+      bitbucketOAuthProviderSection.string(
+          FIX_LEGACY_USER_ID_QUESTION, FIX_LEGACY_USER_ID, "false");
+    }
+
+    boolean configureCasOAuthProvider = ui.yesno(true, "Use CAS OAuth provider for Gerrit login ?");
+    if (configureCasOAuthProvider) {
+      casOAuthProviderSection.string("CAS Root URL", ROOT_URL, null);
+      configureOAuth(casOAuthProviderSection);
+      casOAuthProviderSection.string(FIX_LEGACY_USER_ID_QUESTION, FIX_LEGACY_USER_ID, "false");
+    }
+
+    boolean configueFacebookOAuthProvider =
+        ui.yesno(true, "Use Facebook OAuth provider for Gerrit login ?");
+    if (configueFacebookOAuthProvider) {
+      configureOAuth(facebookOAuthProviderSection);
+    }
+
+    boolean configureGitLabOAuthProvider =
+        ui.yesno(true, "Use GitLab OAuth provider for Gerrit login ?");
+    if (configureGitLabOAuthProvider) {
+      gitlabOAuthProviderSection.string("GitLab Root URL", ROOT_URL, null);
+      configureOAuth(gitlabOAuthProviderSection);
+    }
+
+    boolean configureDexOAuthProvider = ui.yesno(true, "Use Dex OAuth provider for Gerrit login ?");
+    if (configureDexOAuthProvider) {
+      dexOAuthProviderSection.string("Dex Root URL", ROOT_URL, null);
+      configureOAuth(dexOAuthProviderSection);
+    }
+
+    boolean configureKeycloakOAuthProvider =
+        ui.yesno(true, "Use Keycloak OAuth provider for Gerrit login ?");
+    if (configureKeycloakOAuthProvider) {
+      keycloakOAuthProviderSection.string("Keycloak Root URL", ROOT_URL, null);
+      keycloakOAuthProviderSection.string("Keycloak Realm", REALM, null);
+      configureOAuth(keycloakOAuthProviderSection);
+    }
+
+    boolean configureOffice365OAuthProvider =
+        ui.yesno(true, "Use Office365 OAuth provider for Gerrit login ?");
+    if (configureOffice365OAuthProvider) {
+      configureOAuth(office365OAuthProviderSection);
+    }
+
+    boolean configureAirVantageOAuthProvider =
+        ui.yesno(true, "Use AirVantage OAuth provider for Gerrit login ?");
+    if (configureAirVantageOAuthProvider) {
+      configureOAuth(airVantageOAuthProviderSection);
+    }
+
+    boolean configureWarsawHackerspaceOAuthProvider = 
+        ui.yesno(true, "Use Warsaw Hackerspace OAuth provider for Gerrit login?");
+    if (configureWarsawHackerspaceOAuthProvider) {
+      configureOAuth(warsawHackerspaceOAuthProviderSection);
+    }
+  }
+
+  private void configureOAuth(Section s) {
+    s.string("Application client id", CLIENT_ID, null);
+    s.passwordForKey("Application client secret", CLIENT_SECRET);
+  }
+
+  @Override
+  public void postRun() throws Exception {}
+}
diff --git a/app/gerrit/gerrit-oauth-provider/src/main/java/com/googlesource/gerrit/plugins/oauth/KeycloakApi.java b/app/gerrit/gerrit-oauth-provider/src/main/java/com/googlesource/gerrit/plugins/oauth/KeycloakApi.java
new file mode 100644
index 0000000..581d562
--- /dev/null
+++ b/app/gerrit/gerrit-oauth-provider/src/main/java/com/googlesource/gerrit/plugins/oauth/KeycloakApi.java
@@ -0,0 +1,68 @@
+// Copyright (C) 2017 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.oauth;
+
+import org.scribe.builder.api.DefaultApi20;
+import org.scribe.extractors.AccessTokenExtractor;
+import org.scribe.extractors.JsonTokenExtractor;
+import org.scribe.model.OAuthConfig;
+import org.scribe.model.Verb;
+import org.scribe.oauth.OAuthService;
+import org.scribe.utils.OAuthEncoder;
+
+public class KeycloakApi extends DefaultApi20 {
+
+  private static final String AUTHORIZE_URL =
+      "%s/auth/realms/%s/protocol/openid-connect/auth?client_id=%s&response_type=code&redirect_uri=%s&scope=%s";
+
+  private final String rootUrl;
+  private final String realm;
+
+  public KeycloakApi(String rootUrl, String realm) {
+    this.rootUrl = rootUrl;
+    this.realm = realm;
+  }
+
+  @Override
+  public String getAuthorizationUrl(OAuthConfig config) {
+    return String.format(
+        AUTHORIZE_URL,
+        rootUrl,
+        realm,
+        config.getApiKey(),
+        OAuthEncoder.encode(config.getCallback()),
+        config.getScope().replaceAll(" ", "+"));
+  }
+
+  @Override
+  public String getAccessTokenEndpoint() {
+    return String.format("%s/auth/realms/%s/protocol/openid-connect/token", rootUrl, realm);
+  }
+
+  @Override
+  public Verb getAccessTokenVerb() {
+    return Verb.POST;
+  }
+
+  @Override
+  public OAuthService createService(OAuthConfig config) {
+    return new OAuth20ServiceImpl(this, config);
+  }
+
+  @Override
+  public AccessTokenExtractor getAccessTokenExtractor() {
+    return new JsonTokenExtractor();
+  }
+}
diff --git a/app/gerrit/gerrit-oauth-provider/src/main/java/com/googlesource/gerrit/plugins/oauth/KeycloakOAuthService.java b/app/gerrit/gerrit-oauth-provider/src/main/java/com/googlesource/gerrit/plugins/oauth/KeycloakOAuthService.java
new file mode 100644
index 0000000..b6a0cdf
--- /dev/null
+++ b/app/gerrit/gerrit-oauth-provider/src/main/java/com/googlesource/gerrit/plugins/oauth/KeycloakOAuthService.java
@@ -0,0 +1,138 @@
+// Copyright (C) 2017 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.oauth;
+
+import static com.google.gerrit.json.OutputFormat.JSON;
+
+import com.google.common.base.CharMatcher;
+import com.google.common.base.Preconditions;
+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.gson.JsonElement;
+import com.google.gson.JsonObject;
+import com.google.inject.Inject;
+import com.google.inject.Provider;
+import java.io.IOException;
+import org.apache.commons.codec.binary.Base64;
+import org.scribe.builder.ServiceBuilder;
+import org.scribe.model.Token;
+import org.scribe.model.Verifier;
+import org.scribe.oauth.OAuthService;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+public class KeycloakOAuthService implements OAuthServiceProvider {
+
+  private static final Logger log = LoggerFactory.getLogger(KeycloakOAuthService.class);
+
+  static final String CONFIG_SUFFIX = "-keycloak-oauth";
+  private static final String KEYCLOAK_PROVIDER_PREFIX = "keycloak-oauth:";
+  private final OAuthService service;
+  private final String serviceName;
+
+  @Inject
+  KeycloakOAuthService(
+      PluginConfigFactory cfgFactory,
+      @PluginName String pluginName,
+      @CanonicalWebUrl Provider<String> urlProvider) {
+    PluginConfig cfg = cfgFactory.getFromGerritConfig(pluginName + CONFIG_SUFFIX);
+    String canonicalWebUrl = CharMatcher.is('/').trimTrailingFrom(urlProvider.get()) + "/";
+
+    String rootUrl = cfg.getString(InitOAuth.ROOT_URL);
+    String realm = cfg.getString(InitOAuth.REALM);
+    serviceName = cfg.getString(InitOAuth.SERVICE_NAME, "Keycloak OAuth2");
+
+    service =
+        new ServiceBuilder()
+            .provider(new KeycloakApi(rootUrl, realm))
+            .apiKey(cfg.getString(InitOAuth.CLIENT_ID))
+            .apiSecret(cfg.getString(InitOAuth.CLIENT_SECRET))
+            .scope("openid")
+            .callback(canonicalWebUrl + "oauth")
+            .build();
+  }
+
+  private String parseJwt(String input) {
+    String[] parts = input.split("\\.");
+    Preconditions.checkState(parts.length == 3);
+    Preconditions.checkNotNull(parts[1]);
+    return new String(Base64.decodeBase64(parts[1]));
+  }
+
+  @Override
+  public OAuthUserInfo getUserInfo(OAuthToken token) throws IOException {
+    JsonElement tokenJson = JSON.newGson().fromJson(token.getRaw(), JsonElement.class);
+    JsonObject tokenObject = tokenJson.getAsJsonObject();
+    JsonElement id_token = tokenObject.get("id_token");
+
+    JsonElement claimJson =
+        JSON.newGson().fromJson(parseJwt(id_token.getAsString()), JsonElement.class);
+
+    JsonObject claimObject = claimJson.getAsJsonObject();
+    if (log.isDebugEnabled()) {
+      log.debug("Claim object: {}", claimObject);
+    }
+    JsonElement usernameElement = claimObject.get("preferred_username");
+    JsonElement emailElement = claimObject.get("email");
+    JsonElement nameElement = claimObject.get("name");
+    if (usernameElement == null || usernameElement.isJsonNull()) {
+      throw new IOException("Response doesn't contain preferred_username field");
+    }
+    if (emailElement == null || emailElement.isJsonNull()) {
+      throw new IOException("Response doesn't contain email field");
+    }
+    if (nameElement == null || nameElement.isJsonNull()) {
+      throw new IOException("Response doesn't contain name field");
+    }
+    String username = usernameElement.getAsString();
+    String email = emailElement.getAsString();
+    String name = nameElement.getAsString();
+
+    return new OAuthUserInfo(
+        KEYCLOAK_PROVIDER_PREFIX + username /*externalId*/,
+        username /*username*/,
+        email /*email*/,
+        name /*displayName*/,
+        null /*claimedIdentity*/);
+  }
+
+  @Override
+  public OAuthToken getAccessToken(OAuthVerifier rv) {
+    Verifier vi = new Verifier(rv.getValue());
+    Token to = service.getAccessToken(null, vi);
+    return new OAuthToken(to.getToken(), to.getSecret(), to.getRawResponse());
+  }
+
+  @Override
+  public String getAuthorizationUrl() {
+    return service.getAuthorizationUrl(null);
+  }
+
+  @Override
+  public String getVersion() {
+    return service.getVersion();
+  }
+
+  @Override
+  public String getName() {
+    return serviceName;
+  }
+}
diff --git a/app/gerrit/gerrit-oauth-provider/src/main/java/com/googlesource/gerrit/plugins/oauth/Module.java b/app/gerrit/gerrit-oauth-provider/src/main/java/com/googlesource/gerrit/plugins/oauth/Module.java
new file mode 100644
index 0000000..72d59d1
--- /dev/null
+++ b/app/gerrit/gerrit-oauth-provider/src/main/java/com/googlesource/gerrit/plugins/oauth/Module.java
@@ -0,0 +1,37 @@
+// Copyright (C) 2017 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.oauth;
+
+import com.google.gerrit.extensions.annotations.Exports;
+import com.google.gerrit.extensions.annotations.PluginName;
+import com.google.gerrit.extensions.auth.oauth.OAuthLoginProvider;
+import com.google.inject.AbstractModule;
+import com.google.inject.Inject;
+
+public class Module extends AbstractModule {
+  private final String pluginName;
+
+  @Inject
+  Module(@PluginName String pluginName) {
+    this.pluginName = pluginName;
+  }
+
+  @Override
+  protected void configure() {
+    bind(OAuthLoginProvider.class)
+        .annotatedWith(Exports.named(pluginName))
+        .to(DisabledOAuthLoginProvider.class);
+  }
+}
diff --git a/app/gerrit/gerrit-oauth-provider/src/main/java/com/googlesource/gerrit/plugins/oauth/OAuth20ServiceImpl.java b/app/gerrit/gerrit-oauth-provider/src/main/java/com/googlesource/gerrit/plugins/oauth/OAuth20ServiceImpl.java
new file mode 100644
index 0000000..ecd8f26
--- /dev/null
+++ b/app/gerrit/gerrit-oauth-provider/src/main/java/com/googlesource/gerrit/plugins/oauth/OAuth20ServiceImpl.java
@@ -0,0 +1,93 @@
+// Copyright (C) 2017 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.oauth;
+
+import static org.slf4j.LoggerFactory.getLogger;
+
+import org.scribe.builder.api.DefaultApi20;
+import org.scribe.model.OAuthConfig;
+import org.scribe.model.OAuthConstants;
+import org.scribe.model.OAuthRequest;
+import org.scribe.model.Response;
+import org.scribe.model.Token;
+import org.scribe.model.Verifier;
+import org.scribe.oauth.OAuthService;
+import org.slf4j.Logger;
+
+/** TODO(gildur): remove when updating to newer scribe lib */
+final class OAuth20ServiceImpl implements OAuthService {
+  private static final Logger log = getLogger(OAuth20ServiceImpl.class);
+
+  private static final String VERSION = "2.0";
+
+  private static final String GRANT_TYPE = "grant_type";
+  private static final String GRANT_TYPE_VALUE = "authorization_code";
+
+  private final DefaultApi20 api;
+  private final OAuthConfig config;
+
+  /**
+   * Default constructor
+   *
+   * @param api OAuth2.0 api information
+   * @param config OAuth 2.0 configuration param object
+   */
+  public OAuth20ServiceImpl(DefaultApi20 api, OAuthConfig config) {
+    this.api = api;
+    this.config = config;
+  }
+
+  @Override
+  public Token getAccessToken(Token requestToken, Verifier verifier) {
+    OAuthRequest request = new OAuthRequest(api.getAccessTokenVerb(), api.getAccessTokenEndpoint());
+    request.addBodyParameter(OAuthConstants.CLIENT_ID, config.getApiKey());
+    request.addBodyParameter(OAuthConstants.CLIENT_SECRET, config.getApiSecret());
+    request.addBodyParameter(OAuthConstants.CODE, verifier.getValue());
+    request.addBodyParameter(OAuthConstants.REDIRECT_URI, config.getCallback());
+    if (config.hasScope()) {
+      request.addBodyParameter(OAuthConstants.SCOPE, config.getScope());
+    }
+    request.addBodyParameter(GRANT_TYPE, GRANT_TYPE_VALUE);
+    if (log.isDebugEnabled()) {
+      log.debug("Access token request: {}", request);
+    }
+    Response response = request.send();
+    if (log.isDebugEnabled()) {
+      log.debug("Access token response: {}", response.getBody());
+    }
+    return api.getAccessTokenExtractor().extract(response.getBody());
+  }
+
+  @Override
+  public Token getRequestToken() {
+    throw new UnsupportedOperationException(
+        "Unsupported operation, please use 'getAuthorizationUrl' and redirect your users there");
+  }
+
+  @Override
+  public String getVersion() {
+    return VERSION;
+  }
+
+  @Override
+  public void signRequest(Token accessToken, OAuthRequest request) {
+    request.addQuerystringParameter(OAuthConstants.ACCESS_TOKEN, accessToken.getToken());
+  }
+
+  @Override
+  public String getAuthorizationUrl(Token requestToken) {
+    return api.getAuthorizationUrl(config);
+  }
+}
diff --git a/app/gerrit/gerrit-oauth-provider/src/main/java/com/googlesource/gerrit/plugins/oauth/OAuth2AccessTokenJsonExtractor.java b/app/gerrit/gerrit-oauth-provider/src/main/java/com/googlesource/gerrit/plugins/oauth/OAuth2AccessTokenJsonExtractor.java
new file mode 100644
index 0000000..6c2f1a0
--- /dev/null
+++ b/app/gerrit/gerrit-oauth-provider/src/main/java/com/googlesource/gerrit/plugins/oauth/OAuth2AccessTokenJsonExtractor.java
@@ -0,0 +1,49 @@
+// Copyright (C) 2018 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.oauth;
+
+import static org.scribe.model.OAuthConstants.ACCESS_TOKEN;
+
+import com.google.common.annotations.VisibleForTesting;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+import org.scribe.exceptions.OAuthException;
+import org.scribe.extractors.AccessTokenExtractor;
+import org.scribe.model.Token;
+import org.scribe.utils.Preconditions;
+
+class OAuth2AccessTokenJsonExtractor implements AccessTokenExtractor {
+  private static final Pattern ACCESS_TOKEN_REGEX_PATTERN =
+      Pattern.compile("\"" + ACCESS_TOKEN + "\"\\s*:\\s*\"(\\S*?)\"");
+
+  private OAuth2AccessTokenJsonExtractor() {}
+
+  private static final AccessTokenExtractor INSTANCE = new OAuth2AccessTokenJsonExtractor();
+
+  static AccessTokenExtractor instance() {
+    return INSTANCE;
+  }
+
+  @VisibleForTesting
+  @Override
+  public Token extract(String response) {
+    Preconditions.checkEmptyString(response, "Cannot extract a token from a null or empty String");
+    Matcher matcher = ACCESS_TOKEN_REGEX_PATTERN.matcher(response);
+    if (matcher.find()) {
+      return new Token(matcher.group(1), "", response);
+    }
+    throw new OAuthException("Cannot extract an access token. Response was: " + response);
+  }
+}
diff --git a/app/gerrit/gerrit-oauth-provider/src/main/java/com/googlesource/gerrit/plugins/oauth/Office365Api.java b/app/gerrit/gerrit-oauth-provider/src/main/java/com/googlesource/gerrit/plugins/oauth/Office365Api.java
new file mode 100644
index 0000000..8a28520
--- /dev/null
+++ b/app/gerrit/gerrit-oauth-provider/src/main/java/com/googlesource/gerrit/plugins/oauth/Office365Api.java
@@ -0,0 +1,62 @@
+// Copyright (C) 2018 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.oauth;
+
+import static org.scribe.utils.OAuthEncoder.encode;
+
+import org.scribe.builder.api.DefaultApi20;
+import org.scribe.extractors.AccessTokenExtractor;
+import org.scribe.model.OAuthConfig;
+import org.scribe.model.Verb;
+import org.scribe.oauth.OAuthService;
+import org.scribe.utils.Preconditions;
+
+public class Office365Api extends DefaultApi20 {
+  private static final String AUTHORIZE_URL =
+      "https://login.microsoftonline.com/organizations/oauth2/v2.0/authorize?client_id=%s&response_type=code&redirect_uri=%s&scope=%s";
+
+  @Override
+  public String getAccessTokenEndpoint() {
+    return "https://login.microsoftonline.com/organizations/oauth2/v2.0/token";
+  }
+
+  @Override
+  public String getAuthorizationUrl(OAuthConfig config) {
+    Preconditions.checkValidUrl(
+        config.getCallback(),
+        "Must provide a valid url as callback. Office365 does not support OOB");
+    Preconditions.checkEmptyString(
+        config.getScope(),
+        "Must provide a valid value as scope. Office365 does not support no scope");
+
+    return String.format(
+        AUTHORIZE_URL, config.getApiKey(), encode(config.getCallback()), encode(config.getScope()));
+  }
+
+  @Override
+  public Verb getAccessTokenVerb() {
+    return Verb.POST;
+  }
+
+  @Override
+  public OAuthService createService(OAuthConfig config) {
+    return new OAuth20ServiceImpl(this, config);
+  }
+
+  @Override
+  public AccessTokenExtractor getAccessTokenExtractor() {
+    return OAuth2AccessTokenJsonExtractor.instance();
+  }
+}
diff --git a/app/gerrit/gerrit-oauth-provider/src/main/java/com/googlesource/gerrit/plugins/oauth/Office365OAuthService.java b/app/gerrit/gerrit-oauth-provider/src/main/java/com/googlesource/gerrit/plugins/oauth/Office365OAuthService.java
new file mode 100644
index 0000000..aee8f63
--- /dev/null
+++ b/app/gerrit/gerrit-oauth-provider/src/main/java/com/googlesource/gerrit/plugins/oauth/Office365OAuthService.java
@@ -0,0 +1,143 @@
+// Copyright (C) 2018 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.oauth;
+
+import static com.google.gerrit.json.OutputFormat.JSON;
+
+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.gson.JsonElement;
+import com.google.gson.JsonObject;
+import com.google.inject.Inject;
+import com.google.inject.Provider;
+import com.google.inject.Singleton;
+import java.io.IOException;
+import javax.servlet.http.HttpServletResponse;
+import org.scribe.builder.ServiceBuilder;
+import org.scribe.model.OAuthRequest;
+import org.scribe.model.Response;
+import org.scribe.model.Token;
+import org.scribe.model.Verb;
+import org.scribe.model.Verifier;
+import org.scribe.oauth.OAuthService;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+@Singleton
+class Office365OAuthService implements OAuthServiceProvider {
+  private static final Logger log = LoggerFactory.getLogger(Office365OAuthService.class);
+  static final String CONFIG_SUFFIX = "-office365-oauth";
+  private static final String OFFICE365_PROVIDER_PREFIX = "office365-oauth:";
+  private static final String PROTECTED_RESOURCE_URL = "https://graph.microsoft.com/v1.0/me";
+  private static final String SCOPE =
+      "openid offline_access https://graph.microsoft.com/user.readbasic.all";
+  private final OAuthService service;
+  private final String canonicalWebUrl;
+  private final boolean useEmailAsUsername;
+
+  @Inject
+  Office365OAuthService(
+      PluginConfigFactory cfgFactory,
+      @PluginName String pluginName,
+      @CanonicalWebUrl Provider<String> urlProvider) {
+    PluginConfig cfg = cfgFactory.getFromGerritConfig(pluginName + CONFIG_SUFFIX);
+    this.canonicalWebUrl = CharMatcher.is('/').trimTrailingFrom(urlProvider.get()) + "/";
+    this.useEmailAsUsername = cfg.getBoolean(InitOAuth.USE_EMAIL_AS_USERNAME, false);
+    this.service =
+        new ServiceBuilder()
+            .provider(Office365Api.class)
+            .apiKey(cfg.getString(InitOAuth.CLIENT_ID))
+            .apiSecret(cfg.getString(InitOAuth.CLIENT_SECRET))
+            .callback(canonicalWebUrl + "oauth")
+            .scope(SCOPE)
+            .build();
+    if (log.isDebugEnabled()) {
+      log.debug("OAuth2: canonicalWebUrl={}", canonicalWebUrl);
+      log.debug("OAuth2: scope={}", SCOPE);
+      log.debug("OAuth2: useEmailAsUsername={}", useEmailAsUsername);
+    }
+  }
+
+  @Override
+  public OAuthUserInfo getUserInfo(OAuthToken token) throws IOException {
+    OAuthRequest request = new OAuthRequest(Verb.GET, PROTECTED_RESOURCE_URL);
+    request.addHeader("Accept", "*/*");
+    request.addHeader("Authorization", "Bearer " + token.getToken());
+    Response response = request.send();
+    if (response.getCode() != HttpServletResponse.SC_OK) {
+      throw new IOException(
+          String.format(
+              "Status %s (%s) for request %s",
+              response.getCode(), response.getBody(), request.getUrl()));
+    }
+    JsonElement userJson = JSON.newGson().fromJson(response.getBody(), JsonElement.class);
+    if (log.isDebugEnabled()) {
+      log.debug("User info response: {}", response.getBody());
+    }
+    if (userJson.isJsonObject()) {
+      JsonObject jsonObject = userJson.getAsJsonObject();
+      JsonElement id = jsonObject.get("id");
+      if (id == null || id.isJsonNull()) {
+        throw new IOException("Response doesn't contain id field");
+      }
+      JsonElement email = jsonObject.get("mail");
+      JsonElement name = jsonObject.get("displayName");
+      String login = null;
+
+      if (useEmailAsUsername && !email.isJsonNull()) {
+        login = email.getAsString().split("@")[0];
+      }
+      return new OAuthUserInfo(
+          OFFICE365_PROVIDER_PREFIX + id.getAsString() /*externalId*/,
+          login /*username*/,
+          email == null || email.isJsonNull() ? null : email.getAsString() /*email*/,
+          name == null || name.isJsonNull() ? null : name.getAsString() /*displayName*/,
+          null);
+    }
+
+    throw new IOException(String.format("Invalid JSON '%s': not a JSON Object", userJson));
+  }
+
+  @Override
+  public OAuthToken getAccessToken(OAuthVerifier rv) {
+    Verifier vi = new Verifier(rv.getValue());
+    Token to = service.getAccessToken(null, vi);
+    OAuthToken result = new OAuthToken(to.getToken(), to.getSecret(), to.getRawResponse());
+    return result;
+  }
+
+  @Override
+  public String getAuthorizationUrl() {
+    String url = service.getAuthorizationUrl(null);
+    return url;
+  }
+
+  @Override
+  public String getVersion() {
+    return service.getVersion();
+  }
+
+  @Override
+  public String getName() {
+    return "Office365 OAuth2";
+  }
+}
diff --git a/app/gerrit/gerrit-oauth-provider/src/main/java/com/googlesource/gerrit/plugins/oauth/WarsawHackerspaceApi.java b/app/gerrit/gerrit-oauth-provider/src/main/java/com/googlesource/gerrit/plugins/oauth/WarsawHackerspaceApi.java
new file mode 100644
index 0000000..d66cff7
--- /dev/null
+++ b/app/gerrit/gerrit-oauth-provider/src/main/java/com/googlesource/gerrit/plugins/oauth/WarsawHackerspaceApi.java
@@ -0,0 +1,65 @@
+// Copyright (C) 2018 The Android Open Source Project
+// Copyright (C) 2019 Serge Bazanski <q3k@hackerspace.pl>
+//
+// 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.oauth;
+
+import static java.lang.String.format;
+import static org.scribe.utils.OAuthEncoder.encode;
+
+import org.scribe.builder.api.DefaultApi20;
+import org.scribe.extractors.AccessTokenExtractor;
+import org.scribe.extractors.JsonTokenExtractor;
+import org.scribe.model.OAuthConfig;
+import org.scribe.model.Verb;
+import org.scribe.oauth.OAuthService;
+import org.scribe.utils.Preconditions;
+
+public class WarsawHackerspaceApi extends DefaultApi20 {
+
+  private static final String AUTHORIZE_URL =
+      "https://sso.hackerspace.pl/oauth/authorize?client_id=%s&response_type=code&scope=%s&redirect_uri=%s";
+  private static final String ACCESS_TOKEN_ENDPOINT = "https://sso.hackerspace.pl/oauth/token";
+
+  @Override
+  public String getAuthorizationUrl(OAuthConfig config) {
+    Preconditions.checkValidUrl(
+        config.getCallback(),
+        "Must provide a valid url as callback. Warsaw Hackerspace SSO does not support OOB");
+    Preconditions.checkEmptyString(
+        config.getScope(),
+        "Must provide a valid value as scope. Warsaw Hackerspace SSO does not support no scope");
+    return format(AUTHORIZE_URL, config.getApiKey(), encode(config.getScope()), encode(config.getCallback()));
+  }
+
+  @Override
+  public String getAccessTokenEndpoint() {
+    return ACCESS_TOKEN_ENDPOINT;
+  }
+
+  @Override
+  public Verb getAccessTokenVerb() {
+    return Verb.POST;
+  }
+
+  @Override
+  public AccessTokenExtractor getAccessTokenExtractor() {
+    return new JsonTokenExtractor();
+  }
+
+  @Override
+  public OAuthService createService(OAuthConfig config) {
+    return new OAuth20ServiceImpl(this, config);
+  }
+}
diff --git a/app/gerrit/gerrit-oauth-provider/src/main/java/com/googlesource/gerrit/plugins/oauth/WarsawHackerspaceOAuthService.java b/app/gerrit/gerrit-oauth-provider/src/main/java/com/googlesource/gerrit/plugins/oauth/WarsawHackerspaceOAuthService.java
new file mode 100644
index 0000000..728386f
--- /dev/null
+++ b/app/gerrit/gerrit-oauth-provider/src/main/java/com/googlesource/gerrit/plugins/oauth/WarsawHackerspaceOAuthService.java
@@ -0,0 +1,128 @@
+// Copyright (C) 2018 The Android Open Source Project
+// Copyright (C) 2019 Serge Bazanski <q3k@hackerspace.pl>
+//
+// 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.oauth;
+
+import static com.google.gerrit.json.OutputFormat.JSON;
+import static javax.servlet.http.HttpServletResponse.SC_OK;
+import static org.slf4j.LoggerFactory.getLogger;
+
+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.gson.JsonElement;
+import com.google.gson.JsonObject;
+import com.google.inject.Inject;
+import com.google.inject.Provider;
+import com.google.inject.Singleton;
+import java.io.IOException;
+import org.scribe.builder.ServiceBuilder;
+import org.scribe.model.OAuthRequest;
+import org.scribe.model.Response;
+import org.scribe.model.Token;
+import org.scribe.model.Verb;
+import org.scribe.model.Verifier;
+import org.scribe.oauth.OAuthService;
+import org.slf4j.Logger;
+
+@Singleton
+public class WarsawHackerspaceOAuthService implements OAuthServiceProvider {
+  private static final Logger log = getLogger(WarsawHackerspaceOAuthService.class);
+  static final String CONFIG_SUFFIX = "-warsawhackerspace-oauth";
+  private static final String HSWAW_PROVIDER_PREFIX = "warsawhackerspace-oauth:";
+  private static final String PROTECTED_RESOURCE_URL =
+      "https://sso.hackerspace.pl/api/1/userinfo";
+  private final OAuthService service;
+
+  @Inject
+  WarsawHackerspaceOAuthService(
+      PluginConfigFactory cfgFactory,
+      @PluginName String pluginName,
+      @CanonicalWebUrl Provider<String> urlProvider) {
+    PluginConfig cfg = cfgFactory.getFromGerritConfig(pluginName + CONFIG_SUFFIX);
+    String canonicalWebUrl = CharMatcher.is('/').trimTrailingFrom(urlProvider.get()) + "/";
+
+    service =
+        new ServiceBuilder()
+            .provider(WarsawHackerspaceApi.class)
+            .apiKey(cfg.getString(InitOAuth.CLIENT_ID))
+            .apiSecret(cfg.getString(InitOAuth.CLIENT_SECRET))
+            .scope("profile:read")
+            .callback(canonicalWebUrl + "oauth")
+            .build();
+  }
+
+  @Override
+  public OAuthUserInfo getUserInfo(OAuthToken token) throws IOException {
+    OAuthRequest request = new OAuthRequest(Verb.GET, PROTECTED_RESOURCE_URL);
+    Token t = new Token(token.getToken(), token.getSecret(), token.getRaw());
+    service.signRequest(t, request);
+    Response response = request.send();
+    if (response.getCode() != SC_OK) {
+      throw new IOException(
+          String.format(
+              "Status %s (%s) for request %s",
+              response.getCode(), response.getBody(), request.getUrl()));
+    }
+    JsonElement userJson = JSON.newGson().fromJson(response.getBody(), JsonElement.class);
+    if (log.isDebugEnabled()) {
+      log.debug("User info response: {}", response.getBody());
+    }
+    if (userJson.isJsonObject()) {
+      JsonObject jsonObject = userJson.getAsJsonObject();
+      JsonElement id = jsonObject.get("sub");
+      if (id == null || id.isJsonNull()) {
+        throw new IOException("Response doesn't contain uid field");
+      }
+      JsonElement email = jsonObject.get("email");
+      return new OAuthUserInfo(
+          HSWAW_PROVIDER_PREFIX + id.getAsString(),
+          id.getAsString(),
+          email.getAsString(),
+          id.getAsString(),
+          id.getAsString());
+    }
+
+    throw new IOException(String.format("Invalid JSON '%s': not a JSON Object", userJson));
+  }
+
+  @Override
+  public OAuthToken getAccessToken(OAuthVerifier rv) {
+    Verifier vi = new Verifier(rv.getValue());
+    Token to = service.getAccessToken(null, vi);
+    return new OAuthToken(to.getToken(), to.getSecret(), to.getRawResponse());
+  }
+
+  @Override
+  public String getAuthorizationUrl() {
+    return service.getAuthorizationUrl(null);
+  }
+
+  @Override
+  public String getVersion() {
+    return service.getVersion();
+  }
+
+  @Override
+  public String getName() {
+    return "Warsaw Hackerspace OAuth2";
+  }
+}
diff --git a/app/gerrit/gerrit-oauth-provider/src/test/java/com/googlesource/gerrit/plugins/oauth/OAuth2AccessTokenJsonExtractorTest.java b/app/gerrit/gerrit-oauth-provider/src/test/java/com/googlesource/gerrit/plugins/oauth/OAuth2AccessTokenJsonExtractorTest.java
new file mode 100644
index 0000000..09df7ee
--- /dev/null
+++ b/app/gerrit/gerrit-oauth-provider/src/test/java/com/googlesource/gerrit/plugins/oauth/OAuth2AccessTokenJsonExtractorTest.java
@@ -0,0 +1,70 @@
+// Copyright (C) 2018 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.oauth;
+
+import static org.junit.Assert.assertEquals;
+import static org.scribe.model.OAuthConstants.ACCESS_TOKEN;
+
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.rules.ExpectedException;
+import org.scribe.exceptions.OAuthException;
+import org.scribe.extractors.AccessTokenExtractor;
+import org.scribe.model.Token;
+
+public class OAuth2AccessTokenJsonExtractorTest {
+  private static final AccessTokenExtractor extractor = OAuth2AccessTokenJsonExtractor.instance();
+  private static final String TOKEN = "I0122HHJKLEM21F3WLPYHDKGKZULAUO4SGMV3ABKFTDT3T3X";
+  private static final String RESPONSE = "{\"" + ACCESS_TOKEN + "\":\"" + TOKEN + "\"}'";
+  private static final String RESPONSE_NON_JSON = ACCESS_TOKEN + "=" + TOKEN;
+  private static final String RESPONSE_WITH_BLANKS =
+      "{ \"" + ACCESS_TOKEN + "\" : \"" + TOKEN + "\"}'";
+  private static final String MESSAGE = "Cannot extract a token from a null or empty String";
+
+  @Rule public ExpectedException exception = ExpectedException.none();
+
+  @Test
+  public void parseResponse() throws Exception {
+    Token token = extractor.extract(RESPONSE);
+    assertEquals(token.getToken(), TOKEN);
+  }
+
+  @Test
+  public void parseResponseWithBlanks() throws Exception {
+    Token token = extractor.extract(RESPONSE_WITH_BLANKS);
+    assertEquals(token.getToken(), TOKEN);
+  }
+
+  @Test
+  public void failParseNonJsonResponse() throws Exception {
+    exception.expect(OAuthException.class);
+    exception.expectMessage("Cannot extract an access token. Response was: " + RESPONSE_NON_JSON);
+    extractor.extract(RESPONSE_NON_JSON);
+  }
+
+  @Test
+  public void shouldThrowExceptionIfForNullParameter() throws Exception {
+    exception.expect(IllegalArgumentException.class);
+    exception.expectMessage(MESSAGE);
+    extractor.extract(null);
+  }
+
+  @Test
+  public void shouldThrowExceptionIfForEmptyString() throws Exception {
+    exception.expect(IllegalArgumentException.class);
+    exception.expectMessage(MESSAGE);
+    extractor.extract("");
+  }
+}
diff --git a/app/gerrit/gerrit-oauth-provider/tools/bzl/BUILD b/app/gerrit/gerrit-oauth-provider/tools/bzl/BUILD
new file mode 100644
index 0000000..c5ed0b7
--- /dev/null
+++ b/app/gerrit/gerrit-oauth-provider/tools/bzl/BUILD
@@ -0,0 +1 @@
+# Empty file required by Bazel
diff --git a/app/gerrit/gerrit-oauth-provider/tools/bzl/classpath.bzl b/app/gerrit/gerrit-oauth-provider/tools/bzl/classpath.bzl
new file mode 100644
index 0000000..c921d01
--- /dev/null
+++ b/app/gerrit/gerrit-oauth-provider/tools/bzl/classpath.bzl
@@ -0,0 +1,6 @@
+load(
+    "@com_googlesource_gerrit_bazlets//tools:classpath.bzl",
+    _classpath_collector = "classpath_collector",
+)
+
+classpath_collector = _classpath_collector
diff --git a/app/gerrit/gerrit-oauth-provider/tools/bzl/junit.bzl b/app/gerrit/gerrit-oauth-provider/tools/bzl/junit.bzl
new file mode 100644
index 0000000..97307bd
--- /dev/null
+++ b/app/gerrit/gerrit-oauth-provider/tools/bzl/junit.bzl
@@ -0,0 +1,6 @@
+load(
+    "@com_googlesource_gerrit_bazlets//tools:junit.bzl",
+    _junit_tests = "junit_tests",
+)
+
+junit_tests = _junit_tests
diff --git a/app/gerrit/gerrit-oauth-provider/tools/bzl/maven_jar.bzl b/app/gerrit/gerrit-oauth-provider/tools/bzl/maven_jar.bzl
new file mode 100644
index 0000000..35ea8ce
--- /dev/null
+++ b/app/gerrit/gerrit-oauth-provider/tools/bzl/maven_jar.bzl
@@ -0,0 +1,3 @@
+load("@com_googlesource_gerrit_bazlets//tools:maven_jar.bzl", _maven_jar = "maven_jar")
+
+maven_jar = _maven_jar
diff --git a/app/gerrit/gerrit-oauth-provider/tools/bzl/plugin.bzl b/app/gerrit/gerrit-oauth-provider/tools/bzl/plugin.bzl
new file mode 100644
index 0000000..4d2dbdd
--- /dev/null
+++ b/app/gerrit/gerrit-oauth-provider/tools/bzl/plugin.bzl
@@ -0,0 +1,10 @@
+load(
+    "@com_googlesource_gerrit_bazlets//:gerrit_plugin.bzl",
+    _gerrit_plugin = "gerrit_plugin",
+    _plugin_deps = "PLUGIN_DEPS",
+    _plugin_test_deps = "PLUGIN_TEST_DEPS",
+)
+
+gerrit_plugin = _gerrit_plugin
+PLUGIN_DEPS = _plugin_deps
+PLUGIN_TEST_DEPS = _plugin_test_deps
diff --git a/app/gerrit/gerrit-oauth-provider/tools/eclipse/BUILD b/app/gerrit/gerrit-oauth-provider/tools/eclipse/BUILD
new file mode 100644
index 0000000..0dced85
--- /dev/null
+++ b/app/gerrit/gerrit-oauth-provider/tools/eclipse/BUILD
@@ -0,0 +1,9 @@
+load("//app/gerrit/gerrit-oauth-provider/tools/bzl:classpath.bzl", "classpath_collector")
+
+classpath_collector(
+    name = "main_classpath_collect",
+    testonly = 1,
+    deps = [
+        "//:gerrit-oauth-provider__plugin_test_deps",
+    ],
+)
diff --git a/app/gerrit/gerrit-oauth-provider/tools/eclipse/project.sh b/app/gerrit/gerrit-oauth-provider/tools/eclipse/project.sh
new file mode 100755
index 0000000..8e4ed79
--- /dev/null
+++ b/app/gerrit/gerrit-oauth-provider/tools/eclipse/project.sh
@@ -0,0 +1,15 @@
+#!/bin/bash
+# Copyright (C) 2017 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.
+`bazel query @com_googlesource_gerrit_bazlets//tools/eclipse:project --output location | sed s/BUILD:.*//`project.py -n oauth -r .
diff --git a/app/gerrit/gerrit-oauth-provider/tools/workspace-status.sh b/app/gerrit/gerrit-oauth-provider/tools/workspace-status.sh
new file mode 100755
index 0000000..8fba304
--- /dev/null
+++ b/app/gerrit/gerrit-oauth-provider/tools/workspace-status.sh
@@ -0,0 +1,17 @@
+#!/bin/bash
+
+# This script will be run by bazel when the build process starts to
+# generate key-value information that represents the status of the
+# workspace. The output should be like
+#
+# KEY1 VALUE1
+# KEY2 VALUE2
+#
+# If the script exits with non-zero code, it's considered as a failure
+# and the output will be discarded.
+
+function rev() {
+  cd $1; git describe --always --match "v[0-9].*" --dirty
+}
+
+echo STABLE_BUILD_GERRIT-OAUTH-PROVIDER_LABEL $(rev .)
diff --git a/tools/workspace-status.sh b/tools/workspace-status.sh
new file mode 100755
index 0000000..8fba304
--- /dev/null
+++ b/tools/workspace-status.sh
@@ -0,0 +1,17 @@
+#!/bin/bash
+
+# This script will be run by bazel when the build process starts to
+# generate key-value information that represents the status of the
+# workspace. The output should be like
+#
+# KEY1 VALUE1
+# KEY2 VALUE2
+#
+# If the script exits with non-zero code, it's considered as a failure
+# and the output will be discarded.
+
+function rev() {
+  cd $1; git describe --always --match "v[0-9].*" --dirty
+}
+
+echo STABLE_BUILD_GERRIT-OAUTH-PROVIDER_LABEL $(rev .)