forked from recampbell/google-login
/
GoogleOAuth2SecurityRealm.java
253 lines (225 loc) · 10.5 KB
/
GoogleOAuth2SecurityRealm.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
/*
* The MIT License
*
* Copyright (c) 2004-2009, Sun Microsystems, Inc., Kohsuke Kawaguchi
*
* 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.
*/
package org.jenkinsci.plugins.googlelogin;
import com.google.api.client.auth.oauth2.AuthorizationCodeFlow;
import com.google.api.client.auth.oauth2.BearerToken;
import com.google.api.client.auth.oauth2.ClientParametersAuthentication;
import com.google.api.client.auth.oauth2.Credential;
import com.google.api.client.auth.oauth2.TokenResponse;
import com.google.api.client.auth.openidconnect.IdToken;
import com.google.api.client.auth.openidconnect.IdTokenResponse;
import com.google.api.client.http.GenericUrl;
import com.google.api.client.http.HttpRequest;
import com.google.api.client.http.HttpRequestFactory;
import com.google.api.client.http.HttpRequestInitializer;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.JsonObjectParser;
import com.google.api.client.json.jackson2.JacksonFactory;
import hudson.Extension;
import hudson.Util;
import hudson.model.Descriptor;
import hudson.model.User;
import hudson.security.SecurityRealm;
import hudson.util.HttpResponses;
import hudson.util.Secret;
import jenkins.model.Jenkins;
import org.acegisecurity.Authentication;
import org.acegisecurity.AuthenticationException;
import org.acegisecurity.AuthenticationManager;
import org.acegisecurity.BadCredentialsException;
import org.acegisecurity.GrantedAuthority;
import org.acegisecurity.context.SecurityContextHolder;
import org.acegisecurity.providers.UsernamePasswordAuthenticationToken;
import org.acegisecurity.providers.anonymous.AnonymousAuthenticationToken;
import org.kohsuke.stapler.DataBoundConstructor;
import org.kohsuke.stapler.Header;
import org.kohsuke.stapler.HttpRedirect;
import org.kohsuke.stapler.HttpResponse;
import org.kohsuke.stapler.QueryParameter;
import org.kohsuke.stapler.StaplerRequest;
import java.io.IOException;
import java.util.Arrays;
/**
* Login with Google using OpenID Connect / OAuth 2
*
*/
public class GoogleOAuth2SecurityRealm extends SecurityRealm {
/**
* OAuth 2 scope. This is enough to call a variety of userinfo api's.
*/
private static final String SCOPE = "profile email";
/**
* Global instance of the JSON factory.
*/
private static final JsonFactory JSON_FACTORY = new JacksonFactory();
private static final GenericUrl TOKEN_SERVER_URL = new GenericUrl("https://accounts.google.com/o/oauth2/token");
private static final String AUTHORIZATION_SERVER_URL = "https://accounts.google.com/o/oauth2/auth";
private static final HttpTransport HTTP_TRANSPORT = new NetHttpTransport();
/**
* The clientID from the Google Developer console.
*/
private final String clientId;
/**
* The client secret from the Google Developer console.
*/
private final Secret clientSecret;
/**
* If this is non-null, access will be restricted to this domain.
*/
private final String domain;
@DataBoundConstructor
public GoogleOAuth2SecurityRealm(String clientId, String clientSecret, String domain) throws IOException {
this.clientId = clientId;
this.clientSecret = Secret.fromString(clientSecret);
this.domain = Util.fixEmpty(domain);
}
public String getClientId() {
return clientId;
}
public Secret getClientSecret() {
return clientSecret;
}
public String getDomain() {
return domain;
}
/**
* Login begins with our {@link #doCommenceLogin(String,String)} method.
*/
@Override
public String getLoginUrl() {
return "securityRealm/commenceLogin";
}
/**
* Acegi has this notion that first an {@link org.acegisecurity.Authentication} object is created
* by collecting user information and then the act of authentication is done
* later (by {@link org.acegisecurity.AuthenticationManager}) to verify it. But in case of OpenID,
* we create an {@link org.acegisecurity.Authentication} only after we verified the user identity,
* so {@link org.acegisecurity.AuthenticationManager} becomes no-op.
*/
@Override
public SecurityComponents createSecurityComponents() {
return new SecurityComponents(
new AuthenticationManager() {
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
if (authentication instanceof AnonymousAuthenticationToken)
return authentication;
throw new BadCredentialsException("Unexpected authentication type: " + authentication);
}
}
);
}
/**
* The login process starts from here.
*/
public HttpResponse doCommenceLogin(@QueryParameter String from, @Header("Referer") final String referer) throws IOException {
final String redirectOnFinish;
if (from != null) {
redirectOnFinish = from;
} else if (referer != null) {
redirectOnFinish = referer;
} else {
redirectOnFinish = Jenkins.getInstance().getRootUrl();
}
final AuthorizationCodeFlow flow = new AuthorizationCodeFlow.Builder(
BearerToken.queryParameterAccessMethod(), HTTP_TRANSPORT, JSON_FACTORY, TOKEN_SERVER_URL,
new ClientParametersAuthentication(clientId, clientSecret.getPlainText()), clientId, AUTHORIZATION_SERVER_URL)
.setScopes(Arrays.asList(SCOPE))
.build();
return new OAuthSession(flow,from, buildOAuthRedirectUrl(), domain) {
@Override
public HttpResponse onSuccess(String authorizationCode) {
try {
IdTokenResponse response = IdTokenResponse.execute(
flow.newTokenRequest(authorizationCode).setRedirectUri(buildOAuthRedirectUrl()));
IdToken idToken = IdToken.parse(JSON_FACTORY,response.getIdToken());
if (domain != null && ! domain.equals(idToken.getPayload().get("hd"))) {
return HttpResponses.errorWithoutStack(401, "Unauthorized");
}
final Credential credential = flow.createAndStoreCredential(response, null);
HttpRequestFactory requestFactory =
HTTP_TRANSPORT.createRequestFactory(new HttpRequestInitializer() {
public void initialize(HttpRequest request) throws IOException {
credential.initialize(request);
request.setParser(new JsonObjectParser(JSON_FACTORY));
}
});
GenericUrl url = new GenericUrl("https://www.googleapis.com/userinfo/v2/me");
HttpRequest request = requestFactory.buildGetRequest(url);
GoogleUserInfo info = request.execute().parseAs(GoogleUserInfo.class);
GrantedAuthority[] authorities = new GrantedAuthority[]{SecurityRealm.AUTHENTICATED_AUTHORITY};
// logs this user in.
UsernamePasswordAuthenticationToken token =
new UsernamePasswordAuthenticationToken(info.getEmail(), "", authorities);
SecurityContextHolder.getContext().setAuthentication(token);
// update the user profile.
User u = User.get(token.getName());
info.updateProfile(u);
return new HttpRedirect(redirectOnFinish);
} catch (IOException e) {
return HttpResponses.error(500,e);
}
}
}.doCommenceLogin();
}
private String buildOAuthRedirectUrl() {
String rootUrl = Jenkins.getInstance().getRootUrl();
if (rootUrl == null) {
throw new NullPointerException("Jenkins root url should not be null");
} else {
return rootUrl + "securityRealm/finishLogin";
}
}
/**
* This is where the user comes back to at the end of the OpenID redirect ping-pong.
*/
public HttpResponse doFinishLogin(StaplerRequest request) throws IOException {
return OAuthSession.getCurrent().doFinishLogin(request);
}
@Extension
public static final class DescriptorImpl extends Descriptor<SecurityRealm> {
public String getDisplayName() {
return "Login with Google";
}
/*
TODO: Find some way to validate the credentials.
This current returns "Invalid OAuth 2 grant type: CLIENT_CREDENTIALS"
public FormValidation doCheckApiSecret(@QueryParameter String clientId, @QueryParameter String value) {
if (clientId == null) {
return FormValidation.error("API Key is required");
}
ClientCredentialsTokenRequest tokenRequest = new ClientCredentialsTokenRequest(HTTP_TRANSPORT, JSON_FACTORY, TOKEN_SERVER_URL)
.setClientAuthentication(new ClientParametersAuthentication(clientId, value))
.setScopes(Collections.singleton(SCOPE));
try {
TokenResponse response = tokenRequest.execute();
return FormValidation.ok("Credentials are valid");
} catch (IOException e) {
return FormValidation.error(e,"Credentials are invalid, or do not have expected scopes.");
}
}
*/
}
}