Skip to content

Commit 90b66bb

Browse files
committed
Merge remote-tracking branch 'oauth/master'
* oauth/master: Travis CI: Bump Bazel version to 0.9.0 Add support for Office365 OAuth 2.0 Change-Id: I4dedc8e6881324ab10ba8ee55cb9fbd95b70d1c3
2 parents 3325e8c + d138a9e commit 90b66bb

File tree

6 files changed

+243
-1
lines changed

6 files changed

+243
-1
lines changed

.travis.yml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,7 @@ install: true
2929
before_install:
3030
- OS=linux
3131
- ARCH=x86_64
32-
- V=0.8.1
32+
- V=0.9.0
3333
- if [[ "$TRAVIS_OS_NAME" == "osx" ]]; then OS=darwin; fi
3434
- GH_BASE="https://github.com/bazelbuild/bazel/releases/download/$V"
3535
- GH_ARTIFACT="bazel-$V-installer-$OS-$ARCH.sh"

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@ Supported OAuth providers:
1515
* [GitLab](https://about.gitlab.com/)
1616
* [Google](https://developers.google.com/identity/protocols/OAuth2)
1717
* [Keycloak](http://www.keycloak.org/)
18+
* [Office365](https://docs.microsoft.com/en-us/azure/active-directory/develop/active-directory-v2-protocols)
1819

1920
See the [Wiki](https://github.com/davido/gerrit-oauth-provider/wiki) what it can do for you.
2021

src/main/java/com/googlesource/gerrit/plugins/oauth/HttpModule.java

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -91,5 +91,12 @@ protected void configureServlets() {
9191
.annotatedWith(Exports.named(KeycloakOAuthService.CONFIG_SUFFIX))
9292
.to(KeycloakOAuthService.class);
9393
}
94+
95+
cfg = cfgFactory.getFromGerritConfig(pluginName + Office365OAuthService.CONFIG_SUFFIX);
96+
if (cfg.getString(InitOAuth.CLIENT_ID) != null) {
97+
bind(OAuthServiceProvider.class)
98+
.annotatedWith(Exports.named(Office365OAuthService.CONFIG_SUFFIX))
99+
.to(Office365OAuthService.class);
100+
}
94101
}
95102
}

src/main/java/com/googlesource/gerrit/plugins/oauth/InitOAuth.java

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,7 @@ class InitOAuth implements InitStep {
4141
private final Section gitlabOAuthProviderSection;
4242
private final Section dexOAuthProviderSection;
4343
private final Section keycloakOAuthProviderSection;
44+
private final Section office365OAuthProviderSection;
4445

4546
@Inject
4647
InitOAuth(ConsoleUI ui, Section.Factory sections, @PluginName String pluginName) {
@@ -61,6 +62,8 @@ class InitOAuth implements InitStep {
6162
sections.get(PLUGIN_SECTION, pluginName + DexOAuthService.CONFIG_SUFFIX);
6263
this.keycloakOAuthProviderSection =
6364
sections.get(PLUGIN_SECTION, pluginName + KeycloakOAuthService.CONFIG_SUFFIX);
65+
this.office365OAuthProviderSection =
66+
sections.get(PLUGIN_SECTION, pluginName + Office365OAuthService.CONFIG_SUFFIX);
6467
}
6568

6669
@Override
@@ -122,6 +125,12 @@ public void run() throws Exception {
122125
keycloakOAuthProviderSection.string("Keycloak Realm", REALM, null);
123126
configureOAuth(keycloakOAuthProviderSection);
124127
}
128+
129+
boolean configureOffice365OAuthProvider =
130+
ui.yesno(true, "Use Office365 OAuth provider for Gerrit login ?");
131+
if (configureOffice365OAuthProvider) {
132+
configureOAuth(office365OAuthProviderSection);
133+
}
125134
}
126135

127136
private void configureOAuth(Section s) {
Lines changed: 82 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,82 @@
1+
// Copyright (C) 2018 The Android Open Source Project
2+
//
3+
// Licensed under the Apache License, Version 2.0 (the "License");
4+
// you may not use this file except in compliance with the License.
5+
// You may obtain a copy of the License at
6+
//
7+
// http://www.apache.org/licenses/LICENSE-2.0
8+
//
9+
// Unless required by applicable law or agreed to in writing, software
10+
// distributed under the License is distributed on an "AS IS" BASIS,
11+
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
// See the License for the specific language governing permissions and
13+
// limitations under the License.
14+
15+
package com.googlesource.gerrit.plugins.oauth;
16+
17+
import static org.scribe.utils.OAuthEncoder.encode;
18+
19+
import java.util.regex.Matcher;
20+
import java.util.regex.Pattern;
21+
import org.scribe.builder.api.DefaultApi20;
22+
import org.scribe.exceptions.OAuthException;
23+
import org.scribe.extractors.AccessTokenExtractor;
24+
import org.scribe.model.OAuthConfig;
25+
import org.scribe.model.Token;
26+
import org.scribe.model.Verb;
27+
import org.scribe.oauth.OAuthService;
28+
import org.scribe.utils.Preconditions;
29+
30+
public class Office365Api extends DefaultApi20 {
31+
private static final String AUTHORIZE_URL =
32+
"https://login.microsoftonline.com/organizations/oauth2/v2.0/authorize?client_id=%s&response_type=code&redirect_uri=%s&scope=%s";
33+
34+
@Override
35+
public String getAccessTokenEndpoint() {
36+
return "https://login.microsoftonline.com/organizations/oauth2/v2.0/token";
37+
}
38+
39+
@Override
40+
public String getAuthorizationUrl(OAuthConfig config) {
41+
Preconditions.checkValidUrl(
42+
config.getCallback(),
43+
"Must provide a valid url as callback. Office365 does not support OOB");
44+
Preconditions.checkEmptyString(
45+
config.getScope(),
46+
"Must provide a valid value as scope. Office365 does not support no scope");
47+
48+
return String.format(
49+
AUTHORIZE_URL, config.getApiKey(), encode(config.getCallback()), encode(config.getScope()));
50+
}
51+
52+
@Override
53+
public Verb getAccessTokenVerb() {
54+
return Verb.POST;
55+
}
56+
57+
@Override
58+
public OAuthService createService(OAuthConfig config) {
59+
return new OAuth20ServiceImpl(this, config);
60+
}
61+
62+
@Override
63+
public AccessTokenExtractor getAccessTokenExtractor() {
64+
return new Office365JsonTokenExtractor();
65+
}
66+
67+
private static final class Office365JsonTokenExtractor implements AccessTokenExtractor {
68+
private Pattern accessTokenPattern = Pattern.compile("\"access_token\"\\s*:\\s*\"(\\S*?)\"");
69+
70+
@Override
71+
public Token extract(String response) {
72+
Preconditions.checkEmptyString(
73+
response, "Cannot extract a token from a null or empty String");
74+
Matcher matcher = accessTokenPattern.matcher(response);
75+
if (matcher.find()) {
76+
return new Token(matcher.group(1), "", response);
77+
}
78+
79+
throw new OAuthException("Cannot extract an acces token. Response was: " + response);
80+
}
81+
}
82+
}
Lines changed: 143 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,143 @@
1+
// Copyright (C) 2018 The Android Open Source Project
2+
//
3+
// Licensed under the Apache License, Version 2.0 (the "License");
4+
// you may not use this file except in compliance with the License.
5+
// You may obtain a copy of the License at
6+
//
7+
// http://www.apache.org/licenses/LICENSE-2.0
8+
//
9+
// Unless required by applicable law or agreed to in writing, software
10+
// distributed under the License is distributed on an "AS IS" BASIS,
11+
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
// See the License for the specific language governing permissions and
13+
// limitations under the License.
14+
15+
package com.googlesource.gerrit.plugins.oauth;
16+
17+
import com.google.common.base.CharMatcher;
18+
import com.google.gerrit.extensions.annotations.PluginName;
19+
import com.google.gerrit.extensions.auth.oauth.OAuthServiceProvider;
20+
import com.google.gerrit.extensions.auth.oauth.OAuthToken;
21+
import com.google.gerrit.extensions.auth.oauth.OAuthUserInfo;
22+
import com.google.gerrit.extensions.auth.oauth.OAuthVerifier;
23+
import com.google.gerrit.server.OutputFormat;
24+
import com.google.gerrit.server.config.CanonicalWebUrl;
25+
import com.google.gerrit.server.config.PluginConfig;
26+
import com.google.gerrit.server.config.PluginConfigFactory;
27+
import com.google.gson.JsonElement;
28+
import com.google.gson.JsonObject;
29+
import com.google.inject.Inject;
30+
import com.google.inject.Provider;
31+
import com.google.inject.Singleton;
32+
import java.io.IOException;
33+
import javax.servlet.http.HttpServletResponse;
34+
import org.scribe.builder.ServiceBuilder;
35+
import org.scribe.model.OAuthRequest;
36+
import org.scribe.model.Response;
37+
import org.scribe.model.Token;
38+
import org.scribe.model.Verb;
39+
import org.scribe.model.Verifier;
40+
import org.scribe.oauth.OAuthService;
41+
import org.slf4j.Logger;
42+
import org.slf4j.LoggerFactory;
43+
44+
@Singleton
45+
class Office365OAuthService implements OAuthServiceProvider {
46+
private static final Logger log = LoggerFactory.getLogger(Office365OAuthService.class);
47+
static final String CONFIG_SUFFIX = "-office365-oauth";
48+
private static final String OFFICE365_PROVIDER_PREFIX = "office365-oauth:";
49+
private static final String PROTECTED_RESOURCE_URL = "https://graph.microsoft.com/v1.0/me";
50+
private static final String SCOPE =
51+
"openid offline_access https://graph.microsoft.com/user.readbasic.all";
52+
private final OAuthService service;
53+
private final String canonicalWebUrl;
54+
private final boolean useEmailAsUsername;
55+
56+
@Inject
57+
Office365OAuthService(
58+
PluginConfigFactory cfgFactory,
59+
@PluginName String pluginName,
60+
@CanonicalWebUrl Provider<String> urlProvider) {
61+
PluginConfig cfg = cfgFactory.getFromGerritConfig(pluginName + CONFIG_SUFFIX);
62+
this.canonicalWebUrl = CharMatcher.is('/').trimTrailingFrom(urlProvider.get()) + "/";
63+
this.useEmailAsUsername = cfg.getBoolean(InitOAuth.USE_EMAIL_AS_USERNAME, false);
64+
this.service =
65+
new ServiceBuilder()
66+
.provider(Office365Api.class)
67+
.apiKey(cfg.getString(InitOAuth.CLIENT_ID))
68+
.apiSecret(cfg.getString(InitOAuth.CLIENT_SECRET))
69+
.callback(canonicalWebUrl + "oauth")
70+
.scope(SCOPE)
71+
.build();
72+
if (log.isDebugEnabled()) {
73+
log.debug("OAuth2: canonicalWebUrl={}", canonicalWebUrl);
74+
log.debug("OAuth2: scope={}", SCOPE);
75+
log.debug("OAuth2: useEmailAsUsername={}", useEmailAsUsername);
76+
}
77+
}
78+
79+
@Override
80+
public OAuthUserInfo getUserInfo(OAuthToken token) throws IOException {
81+
OAuthRequest request = new OAuthRequest(Verb.GET, PROTECTED_RESOURCE_URL);
82+
request.addHeader("Accept", "*/*");
83+
request.addHeader("Authorization", "Bearer " + token.getToken());
84+
Response response = request.send();
85+
if (response.getCode() != HttpServletResponse.SC_OK) {
86+
throw new IOException(
87+
String.format(
88+
"Status %s (%s) for request %s",
89+
response.getCode(), response.getBody(), request.getUrl()));
90+
}
91+
JsonElement userJson =
92+
OutputFormat.JSON.newGson().fromJson(response.getBody(), JsonElement.class);
93+
if (log.isDebugEnabled()) {
94+
log.debug("User info response: {}", response.getBody());
95+
}
96+
if (userJson.isJsonObject()) {
97+
JsonObject jsonObject = userJson.getAsJsonObject();
98+
JsonElement id = jsonObject.get("id");
99+
if (id == null || id.isJsonNull()) {
100+
throw new IOException(String.format("Response doesn't contain id field"));
101+
}
102+
JsonElement email = jsonObject.get("mail");
103+
JsonElement name = jsonObject.get("displayName");
104+
String login = null;
105+
106+
if (useEmailAsUsername && !email.isJsonNull()) {
107+
login = email.getAsString().split("@")[0];
108+
}
109+
return new OAuthUserInfo(
110+
OFFICE365_PROVIDER_PREFIX + id.getAsString() /*externalId*/,
111+
login /*username*/,
112+
email == null || email.isJsonNull() ? null : email.getAsString() /*email*/,
113+
name == null || name.isJsonNull() ? null : name.getAsString() /*displayName*/,
114+
null);
115+
}
116+
117+
throw new IOException(String.format("Invalid JSON '%s': not a JSON Object", userJson));
118+
}
119+
120+
@Override
121+
public OAuthToken getAccessToken(OAuthVerifier rv) {
122+
Verifier vi = new Verifier(rv.getValue());
123+
Token to = service.getAccessToken(null, vi);
124+
OAuthToken result = new OAuthToken(to.getToken(), to.getSecret(), to.getRawResponse());
125+
return result;
126+
}
127+
128+
@Override
129+
public String getAuthorizationUrl() {
130+
String url = service.getAuthorizationUrl(null);
131+
return url;
132+
}
133+
134+
@Override
135+
public String getVersion() {
136+
return service.getVersion();
137+
}
138+
139+
@Override
140+
public String getName() {
141+
return "Office365 OAuth2";
142+
}
143+
}

0 commit comments

Comments
 (0)