/
TokenEndpoint.java
255 lines (234 loc) · 10.7 KB
/
TokenEndpoint.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
254
255
/**
* Copyright 2013 DuraSpace, Inc.
*
* 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 org.fcrepo.auth.oauth.api;
import static javax.servlet.http.HttpServletResponse.SC_BAD_REQUEST;
import static javax.servlet.http.HttpServletResponse.SC_OK;
import static javax.servlet.http.HttpServletResponse.SC_UNAUTHORIZED;
import static javax.ws.rs.core.MediaType.APPLICATION_FORM_URLENCODED;
import static javax.ws.rs.core.MediaType.APPLICATION_JSON;
import static javax.ws.rs.core.Response.status;
import static org.apache.oltu.oauth2.as.response.OAuthASResponse.tokenResponse;
import static org.apache.oltu.oauth2.common.OAuth.OAUTH_GRANT_TYPE;
import static org.apache.oltu.oauth2.common.error.OAuthError.TokenResponse.INVALID_CLIENT;
import static org.apache.oltu.oauth2.common.error.OAuthError.TokenResponse.INVALID_GRANT;
import static org.apache.oltu.oauth2.common.error.OAuthError.TokenResponse.UNAUTHORIZED_CLIENT;
import static org.apache.oltu.oauth2.common.message.OAuthResponse.errorResponse;
import static org.apache.oltu.oauth2.common.message.types.GrantType.AUTHORIZATION_CODE;
import static org.fcrepo.auth.oauth.Constants.CLIENT_PROPERTY;
import static org.fcrepo.auth.oauth.Constants.OAUTH_WORKSPACE;
import static org.fcrepo.auth.oauth.Constants.PRINCIPAL_PROPERTY;
import static org.fcrepo.auth.oauth.api.Util.createOauthWorkspace;
import static org.slf4j.LoggerFactory.getLogger;
import java.security.AccessControlException;
import java.util.Set;
import javax.annotation.PostConstruct;
import javax.jcr.Node;
import javax.jcr.PathNotFoundException;
import javax.jcr.RepositoryException;
import javax.jcr.Session;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.Response;
import org.apache.oltu.oauth2.as.issuer.MD5Generator;
import org.apache.oltu.oauth2.as.issuer.OAuthIssuer;
import org.apache.oltu.oauth2.as.issuer.OAuthIssuerImpl;
import org.apache.oltu.oauth2.as.request.OAuthTokenRequest;
import org.apache.oltu.oauth2.as.response.OAuthASResponse;
import org.apache.oltu.oauth2.common.OAuth;
import org.apache.oltu.oauth2.common.exception.OAuthProblemException;
import org.apache.oltu.oauth2.common.exception.OAuthSystemException;
import org.apache.oltu.oauth2.common.message.OAuthResponse;
import org.apache.oltu.oauth2.common.message.types.GrantType;
import org.fcrepo.AbstractResource;
import org.slf4j.Logger;
import org.springframework.stereotype.Component;
/**
* @author ajs6f
* @date Jul 1, 2013
*/
@Component
@Path("/token")
public class TokenEndpoint extends AbstractResource {
public static final String INVALID_CLIENT_DESCRIPTION =
"Client authentication failed (e.g., unknown client, no client authentication included, or unsupported authentication method).";
private static final Logger LOGGER = getLogger(TokenEndpoint.class);
/**
* @param request An HTTP request
* @return A token-bearing HTTP response
* @throws OAuthSystemException
* @throws RepositoryException
*/
@POST
@Consumes(APPLICATION_FORM_URLENCODED)
@Produces(APPLICATION_JSON)
public Response getToken(@Context final HttpServletRequest request) throws
OAuthSystemException, RepositoryException {
LOGGER.debug("Received request for token carried on request: {}",
request);
OAuthTokenRequest oauthRequest = null;
final OAuthIssuer oauthIssuerImpl =
new OAuthIssuerImpl(new MD5Generator());
try {
oauthRequest = new OAuthTokenRequest(request);
// TODO check if clientid is valid
if (isNotValid()) {
final OAuthResponse response =
OAuthASResponse.errorResponse(SC_BAD_REQUEST).setError(
INVALID_CLIENT).setErrorDescription(
INVALID_CLIENT_DESCRIPTION).buildJSONMessage();
return status(response.getResponseStatus()).entity(
response.getBody()).build();
}
// TODO check if client_secret is valid
if (isNotValid()) {
final OAuthResponse response =
OAuthASResponse
.errorResponse(SC_UNAUTHORIZED)
.setError(UNAUTHORIZED_CLIENT)
.setErrorDescription(INVALID_CLIENT_DESCRIPTION)
.buildJSONMessage();
return status(response.getResponseStatus()).entity(
response.getBody()).build();
}
// do checking for different grant types
if (oauthRequest.getParam(OAUTH_GRANT_TYPE).equals(
AUTHORIZATION_CODE.toString())) {
if (!isValidAuthCode(oauthRequest)) {
final OAuthResponse response =
errorResponse(SC_BAD_REQUEST).setError(
INVALID_GRANT).setErrorDescription(
"invalid authorization code")
.buildJSONMessage();
return status(response.getResponseStatus()).entity(
response.getBody()).build();
}
} else if (oauthRequest.getParam(OAUTH_GRANT_TYPE).equals(
GrantType.PASSWORD.toString())) {
// TODO check if username/password is valid
if (isNotValid()) {
final OAuthResponse response =
errorResponse(SC_BAD_REQUEST).setError(
INVALID_GRANT).setErrorDescription(
"invalid username or password")
.buildJSONMessage();
return status(response.getResponseStatus()).entity(
response.getBody()).build();
}
} else if (oauthRequest.getParam(OAuth.OAUTH_GRANT_TYPE).equals(
GrantType.REFRESH_TOKEN.toString())) {
// refresh token is not supported in this implementation
final OAuthResponse response =
errorResponse(SC_BAD_REQUEST).setError(INVALID_GRANT)
.setErrorDescription(
"invalid username or password")
.buildJSONMessage();
return status(response.getResponseStatus()).entity(
response.getBody()).build();
}
final String token = oauthIssuerImpl.accessToken();
LOGGER.debug("Created token: {}", token);
saveToken(token, oauthRequest.getClientId(), oauthRequest
.getUsername());
final OAuthResponse response =
tokenResponse(SC_OK).setAccessToken(token).setExpiresIn(
"3600").buildJSONMessage();
return status(response.getResponseStatus()).entity(
response.getBody()).build();
} catch (final OAuthProblemException e) {
final OAuthResponse res =
errorResponse(SC_BAD_REQUEST).error(e).buildJSONMessage();
return status(res.getResponseStatus()).entity(res.getBody())
.build();
}
}
/**
* @param oauthRequest
* @return An answer to whether or not this request matches up with an
* authorization code issued at the {@link AuthzEndpoint}
* @throws RepositoryException
*/
private boolean isValidAuthCode(final OAuthTokenRequest oauthRequest)
throws RepositoryException {
final String client = oauthRequest.getClientId();
LOGGER.debug("Request has authorization client: {}", client);
final String code = oauthRequest.getCode();
final Set<String> scopes = oauthRequest.getScopes();
final Session session = sessions.getSession(OAUTH_WORKSPACE);
try {
final Node authCodeNode =
session.getNode("/authorization-codes/" + code);
LOGGER.debug("Found authorization code node stored: {}",
authCodeNode.getPath());
// if the client is right
if (authCodeNode.getProperty(CLIENT_PROPERTY).getString().equals(
client)) {
// final Set<String> storedScopes =
// newHashSet(map(authCodeNode
// .getProperty(SCOPES_PROPERTY).getValues(),
// value2string));
// and if there is at least one scope in common
// if (intersection(storedScopes, scopes).size() > 0) {
return true;
// }
}
} catch (final PathNotFoundException e) {
// this wasn't a code we stored
return false;
} finally {
session.logout();
}
throw new AccessControlException(
"Could not establish validity or invalidity of authorization code! Code:" +
code);
}
/**
* Stores a token for later use by the configured {@link OAuthRSProvider}
*
* @param token
* @param client
* @param username
* @throws RepositoryException
*/
private void saveToken(final String token, final String client,
final String username) throws RepositoryException {
final Session session = sessions.getSession(OAUTH_WORKSPACE);
try {
final Node tokenNode =
jcrTools.findOrCreateNode(session, "/tokens/" + token);
tokenNode.setProperty(CLIENT_PROPERTY, client);
tokenNode.setProperty(PRINCIPAL_PROPERTY, username);
session.save();
} finally {
session.logout();
}
}
private boolean isNotValid() {
// TODO actually do some checking of client ID and secret and so forth
return false;
}
/**
* Create the OAuth workspace in JCR to store all our tokens
* @throws RepositoryException
*/
@PostConstruct
public void init() throws RepositoryException {
createOauthWorkspace(sessions);
}
}