/
UserManagedAuthzApprovalHandler.java
244 lines (207 loc) · 10.7 KB
/
UserManagedAuthzApprovalHandler.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
/*******************************************************************************
* Cloud Foundry
* Copyright (c) [2009-2014] Pivotal Software, Inc. All Rights Reserved.
*
* This product is licensed to you under the Apache License, Version 2.0 (the "License").
* You may not use this product except in compliance with the License.
*
* This product includes a number of subcomponents with
* separate copyright notices and license terms. Your use of these
* subcomponents is subject to the terms and conditions of the
* subcomponent's license, as noted in the LICENSE file.
*******************************************************************************/
package org.cloudfoundry.identity.uaa.oauth;
import static org.cloudfoundry.identity.uaa.oauth.approval.Approval.ApprovalStatus.APPROVED;
import static org.cloudfoundry.identity.uaa.oauth.approval.Approval.ApprovalStatus.DENIED;
import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.cloudfoundry.identity.uaa.authentication.Origin;
import org.cloudfoundry.identity.uaa.oauth.client.ClientConstants;
import org.cloudfoundry.identity.uaa.oauth.approval.Approval;
import org.cloudfoundry.identity.uaa.oauth.approval.ApprovalStore;
import org.cloudfoundry.identity.uaa.rest.QueryableResourceManager;
import org.cloudfoundry.identity.uaa.util.UaaTokenUtils;
import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.common.util.OAuth2Utils;
import org.springframework.security.oauth2.provider.AuthorizationRequest;
import org.springframework.security.oauth2.provider.ClientDetails;
import org.springframework.security.oauth2.provider.approval.UserApprovalHandler;
public class UserManagedAuthzApprovalHandler implements UserApprovalHandler {
private static final String SCOPE_PREFIX = "scope.";
private static Log logger = LogFactory.getLog(UserManagedAuthzApprovalHandler.class);
private final String approvalParameter = OAuth2Utils.USER_OAUTH_APPROVAL;
private ApprovalStore approvalStore;
private QueryableResourceManager<ClientDetails> clientDetailsService;
private int approvalExpiryInMillis = -1;
/**
* @param clientDetailsService the clientDetailsService to set
*/
public void setClientDetailsService(QueryableResourceManager<ClientDetails> clientDetailsService) {
this.clientDetailsService = clientDetailsService;
}
public void setApprovalStore(ApprovalStore approvalStore) {
this.approvalStore = approvalStore;
}
@Override
public boolean isApproved(AuthorizationRequest authorizationRequest, Authentication userAuthentication) {
String flag = authorizationRequest.getApprovalParameters().get(approvalParameter);
boolean userApproval = flag != null && flag.toLowerCase().equals("true");
if (logger.isDebugEnabled()) {
StringBuilder builder = new StringBuilder("Looking up user approved authorizations for ");
builder.append("client_id=").append(authorizationRequest.getClientId());
builder.append(" and username=").append(userAuthentication.getName());
logger.debug(builder.toString());
}
Collection<String> requestedScopes = authorizationRequest.getScope();
// Factor in auto approved scopes
Set<String> autoApprovedScopes = new HashSet<>();
ClientDetails client = clientDetailsService.retrieve(authorizationRequest.getClientId());
if (null != client) {
if (null != requestedScopes) {
for (String requestedScope : requestedScopes) {
if (client.isAutoApprove(requestedScope)) {
autoApprovedScopes.add(requestedScope);
}
}
}
Map<String, Object> additionalInfo = client.getAdditionalInformation();
if (null != additionalInfo) {
Object autoApproved = additionalInfo.get(ClientConstants.AUTO_APPROVE);
if (null != autoApproved && autoApproved instanceof Collection<?>) {
@SuppressWarnings("unchecked")
Collection<? extends String> scopes = (Collection<? extends String>) autoApproved;
autoApprovedScopes.addAll(scopes);
} else if (null != autoApproved && autoApproved instanceof Boolean && (Boolean) autoApproved || "true".equals(autoApproved)) {
autoApprovedScopes.addAll(client.getScope());
}
}
}
//translate scope to user scopes - including wild cards
autoApprovedScopes = retainAutoApprovedScopes(requestedScopes, autoApprovedScopes);
if (userApproval) {
// Store the scopes that have been approved / denied
Date expiry = computeExpiry();
// Get the approved scopes, calculate the denied scope
Map<String, String> approvalParameters = authorizationRequest.getApprovalParameters();
Set<String> approvedScopes = new HashSet<>();
approvedScopes.addAll(autoApprovedScopes);
boolean foundUserApprovalParameter = false;
for (String approvalParameter : approvalParameters.keySet()) {
if (approvalParameter.startsWith(SCOPE_PREFIX)) {
approvedScopes.add(approvalParameters.get(approvalParameter).substring(SCOPE_PREFIX.length()));
foundUserApprovalParameter = true;
}
}
if (foundUserApprovalParameter) {
authorizationRequest.setScope(approvedScopes);
for (String requestedScope : requestedScopes) {
if (approvedScopes.contains(requestedScope)) {
Approval approval = new Approval()
.setUserId(getUserId(userAuthentication))
.setClientId(authorizationRequest.getClientId())
.setScope(requestedScope)
.setExpiresAt(expiry)
.setStatus(APPROVED);
approvalStore.addApproval(approval);
}
else {
Approval approval = new Approval()
.setUserId(getUserId(userAuthentication))
.setClientId(authorizationRequest.getClientId())
.setScope(requestedScope)
.setExpiresAt(expiry)
.setStatus(DENIED);
approvalStore.addApproval(approval);
}
}
}
else { // Deny all except auto approved scopes
authorizationRequest.setScope(autoApprovedScopes);
for (String requestedScope : requestedScopes) {
if (!autoApprovedScopes.contains(requestedScope)) {
Approval approval = new Approval()
.setUserId(getUserId(userAuthentication))
.setClientId(authorizationRequest.getClientId())
.setScope(requestedScope)
.setExpiresAt(expiry)
.setStatus(DENIED);
approvalStore.addApproval(approval);
}
}
}
if (userAuthentication.isAuthenticated()) {
return true;
}
} else {
// Find the stored approvals for that user and client
List<Approval> userApprovals = approvalStore.getApprovals(getUserId(userAuthentication), authorizationRequest.getClientId());
// Look at the scopes and see if they have expired
Set<String> validUserApprovedScopes = new HashSet<>();
Set<String> approvedScopes = new HashSet<>();
approvedScopes.addAll(autoApprovedScopes);
validUserApprovedScopes.addAll(autoApprovedScopes);
Date today = new Date();
for (Approval approval : userApprovals) {
if (approval.getExpiresAt().after(today)) {
validUserApprovedScopes.add(approval.getScope());
if (approval.getStatus() == APPROVED) {
approvedScopes.add(approval.getScope());
}
}
}
if (logger.isDebugEnabled()) {
logger.debug("Valid user approved/denied scopes are " + validUserApprovedScopes);
}
// If the requested scopes have already been acted upon by the user,
// this request is approved
if (validUserApprovedScopes.containsAll(requestedScopes) && userAuthentication.isAuthenticated()) {
approvedScopes = retainAutoApprovedScopes(requestedScopes, approvedScopes);
// Set only the scopes that have been approved by the user
authorizationRequest.setScope(approvedScopes);
return true;
}
}
return false;
}
protected Set<String> retainAutoApprovedScopes(Collection<String> requestedScopes, Set<String> autoApprovedScopes) {
return UaaTokenUtils.instance().retainAutoApprovedScopes(requestedScopes, autoApprovedScopes);
}
protected String getUserId(Authentication authentication) {
return Origin.getUserId(authentication);
}
private Date computeExpiry() {
Calendar expiresAt = Calendar.getInstance();
if (approvalExpiryInMillis == -1) { // use default of 1 month
expiresAt.add(Calendar.MONTH, 1);
}
else {
expiresAt.add(Calendar.MILLISECOND, approvalExpiryInMillis);
}
return expiresAt.getTime();
}
public void setApprovalExpiryInSeconds(int approvalExpirySeconds) {
this.approvalExpiryInMillis = approvalExpirySeconds * 1000;
}
@Override
public AuthorizationRequest checkForPreApproval(AuthorizationRequest authorizationRequest, Authentication userAuthentication) {
return authorizationRequest;
}
@Override
public AuthorizationRequest updateAfterApproval(AuthorizationRequest authorizationRequest, Authentication userAuthentication) {
return authorizationRequest;
}
@Override
public Map<String, Object> getUserApprovalRequest(AuthorizationRequest authorizationRequest, Authentication userAuthentication) {
Map<String, Object> model = new HashMap<String, Object>();
model.putAll(authorizationRequest.getRequestParameters());
return model;
}
}