-
Notifications
You must be signed in to change notification settings - Fork 0
/
SamlController.java
303 lines (272 loc) · 12.1 KB
/
SamlController.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
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
package org.appng.application.authentication.saml;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang3.StringUtils;
import org.appng.api.BusinessException;
import org.appng.api.Environment;
import org.appng.api.Scope;
import org.appng.api.SiteProperties;
import org.appng.api.model.Application;
import org.appng.api.model.AuthSubject.PasswordChangePolicy;
import org.appng.api.model.Group;
import org.appng.api.model.Site;
import org.appng.api.model.Subject;
import org.appng.api.model.UserType;
import org.appng.api.support.ElementHelper;
import org.appng.application.authentication.AbstractLogon;
import org.appng.application.authentication.AuthenticationSettings;
import org.appng.application.authentication.MessageConstants;
import org.appng.core.domain.SubjectImpl;
import org.appng.core.service.CoreService;
import org.appng.tools.ui.StringNormalizer;
import org.appng.xml.platform.Message;
import org.appng.xml.platform.MessageType;
import org.appng.xml.platform.Messages;
import org.opensaml.saml.saml2.core.Assertion;
import org.opensaml.saml.saml2.core.Attribute;
import org.opensaml.saml.saml2.core.AttributeStatement;
import org.opensaml.saml.saml2.core.AttributeValue;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.MessageSource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.RequestEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import com.coveo.saml.SamlClient;
import com.coveo.saml.SamlException;
import com.coveo.saml.SamlLogoutResponse;
import com.coveo.saml.SamlResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
/**
* <a href="https://learn.microsoft.com/en-us/azure/active-directory/develop/single-sign-on-saml-protocol"><img alt=
* "smal-workflow" src=
* "https://learn.microsoft.com/en-us/azure/active-directory/develop/media/single-sign-on-saml-protocol/active-directory-saml-single-sign-on-workflow.png"
* /></a><br/>
* <br/>
* <a href= "https://learn.microsoft.com/de-de/azure/active-directory/fundamentals/auth-saml"><img alt="SAML Auth" src=
* "https://learn.microsoft.com/de-de/azure/active-directory/fundamentals/media/authentication-patterns/saml-auth.png"
* /></a>
*/
@Slf4j
@RestController
@RequiredArgsConstructor
@SuppressWarnings("unchecked")
public class SamlController implements InitializingBean {
private static String SAML_NAME_ID = "SamlNameID";
private static String SAML_GIVENNAME = "givenname";
private static String SAML_SURNAME = "surname";
@SuppressWarnings("rawtypes")
private static final ResponseEntity NOT_IMPLEMENTED = ResponseEntity.status(HttpStatus.NOT_IMPLEMENTED).build();
private final Site site;
private final Application application;
private final CoreService coreService;
private final MessageSource messageSource;
private @Value("${site." + SiteProperties.MANAGER_PATH + "}") String managerPath;
private @Value("${" + AuthenticationSettings.SAML_ENABLED + "}") boolean samlEnabled;
private @Value("${" + AuthenticationSettings.SAML_CLIENT_ID + "}") String clientId;
private @Value("${" + AuthenticationSettings.SAML_FORWARD_TARGET + "}") String forwardTarget;
private List<String> userGroups;
private SamlClient samlClient;
public static String CLAIM = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/";
@Override
public void afterPropertiesSet() throws Exception {
if (samlEnabled) {
byte[] samlDescriptor = application.getProperties().getClob(AuthenticationSettings.SAML_DESCRIPTOR)
.getBytes(StandardCharsets.UTF_8);
userGroups = application.getProperties().getList(AuthenticationSettings.SAML_CREATE_NEW_USER_WITH_GROUPS,
",");
String endpoint = getEndpoint();
samlClient = SamlClient.fromMetadata(clientId, endpoint,
new InputStreamReader(new ByteArrayInputStream(samlDescriptor)), SamlClient.SamlIdpBinding.POST);
LOGGER.info("Created SAML client '{}' with endpoint {} and IDP {}", clientId, endpoint,
samlClient.getIdentityProviderUrl());
} else {
LOGGER.debug("SAML is disabled");
}
}
@GetMapping(path = { "/saml", "/saml/login" }, produces = MediaType.TEXT_HTML_VALUE)
public void login(HttpServletResponse response) throws IOException, SamlException {
if (!samlEnabled) {
response.setStatus(NOT_IMPLEMENTED.getStatusCodeValue());
return;
}
samlClient.redirectToIdentityProvider(response, null);
}
@PostMapping(path = "/saml", produces = MediaType.TEXT_PLAIN_VALUE, consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
public ResponseEntity<Void> reply(HttpServletRequest request, Environment environment) {
if (!samlEnabled) {
return NOT_IMPLEMENTED;
}
String messageText = MessageConstants.USER_LOGIN_FAIL;
MessageType level = MessageType.ERROR;
String target = forwardTarget;
try {
String parameter = request.getParameter("SAMLResponse");
SamlResponse samlResp = samlClient.decodeAndValidateSamlResponse(parameter, request.getMethod());
String email = samlResp.getNameID();
LOGGER.debug("Received SAMLResponse for {}", email);
Assertion assertion = samlResp.getAssertion();
Map<String, List<String>> attributes = new HashMap<>();
for (AttributeStatement as : assertion.getAttributeStatements()) {
for (Attribute attr : as.getAttributes()) {
String name = attr.getName();
List<String> values = attr.getAttributeValues().stream().filter(v -> (v instanceof AttributeValue))
.map(AttributeValue.class::cast).map(AttributeValue::getTextContent)
.collect(Collectors.toList());
attributes.put(name, values);
LOGGER.debug("Attribute {} with values {}", name, StringUtils.join(values, ", "));
}
}
// https://learn.microsoft.com/en-us/azure/active-directory/develop/reference-saml-tokens
Subject subject = coreService.getSubjectByEmail(email);
if (null == subject && !userGroups.isEmpty()) {
subject = createUser(environment, email, attributes);
}
if (null != subject) {
if (subject.isLocked()) {
messageText = MessageConstants.USER_IS_LOCKED;
} else {
boolean success = coreService.loginByUserName(environment, subject.getAuthName());
LOGGER.info("Logged in {} : {}", subject.getAuthName(), success);
if (success) {
messageText = MessageConstants.USER_AUTHENTICATED;
level = MessageType.OK;
List<String> groupNames = environment.getSubject().getGroups().stream().map(Group::getName)
.collect(Collectors.toList());
target = managerPath
+ AbstractLogon.getSuccessPage(application.getProperties(), success, groupNames);
environment.setAttribute(Scope.SESSION, SAML_NAME_ID, email);
}
}
} else {
messageText = MessageConstants.USER_UNKNOWN;
level = MessageType.INVALID;
}
} catch (SamlException e) {
LOGGER.error("Error processing SAML Response", e);
}
Messages messages = new Messages();
Message message = new Message();
message.setClazz(level);
message.setContent(messageSource.getMessage(messageText, new Object[0], environment.getLocale()));
messages.getMessageList().add(message);
ElementHelper.addMessages(environment, messages);
HttpHeaders headers = new HttpHeaders();
headers.set(HttpHeaders.LOCATION, target);
LOGGER.info("Forwarding to {}", target);
return new ResponseEntity<>(headers, HttpStatus.FOUND);
}
private Subject createUser(Environment environment, String email, Map<String, List<String>> attributes) {
String givenname = attributes.get(CLAIM + SAML_GIVENNAME).get(0);
String surname = attributes.get(CLAIM + SAML_SURNAME).get(0);
String userName = (givenname + "." + surname).toLowerCase();
userName = StringNormalizer.normalize(StringUtils.replace(userName, StringUtils.SPACE, StringUtils.EMPTY));
try {
SubjectImpl user = new SubjectImpl();
user.setEmail(email);
user.setLanguage(environment.getLocale().getLanguage());
user.setName(userName);
user.setTimeZone(environment.getTimeZone().getID());
user.setPasswordChangePolicy(PasswordChangePolicy.MUST_NOT);
user.setRealname(givenname + " " + surname);
user.setDescription("automatically created from SAML login at " + new Date());
user.setUserType(UserType.LOCAL_USER);
Subject newUser = coreService.createSubject(user);
coreService.addGroupsToSubject(user.getName(), userGroups, true);
LOGGER.info("Created user {} with group(s)", userName, StringUtils.join(userGroups, ", "));
return newUser;
} catch (BusinessException e) {
LOGGER.error("Error creating new user " + userName, e);
}
return null;
}
@PostMapping(path = "/saml/sign-on", produces = { MediaType.TEXT_PLAIN_VALUE }, consumes = {
MediaType.TEXT_PLAIN_VALUE, MediaType.APPLICATION_XML_VALUE })
public ResponseEntity<String> signOn(@RequestBody String payload) {
if (!samlEnabled) {
return NOT_IMPLEMENTED;
}
return new ResponseEntity<>(payload, HttpStatus.OK);
}
@PostMapping(path = "/saml/logout", consumes = { MediaType.APPLICATION_FORM_URLENCODED_VALUE })
public ResponseEntity<Void> logout(HttpServletRequest request, Environment environment) {
if (!samlEnabled) {
return NOT_IMPLEMENTED;
}
LOGGER.debug("logout request: {}", request.getParameterMap());
String response = request.getParameter("SAMLResponse");
try {
SamlLogoutResponse samlResp = samlClient.decodeAndValidateSamlLogoutResponse(response, request.getMethod());
LOGGER.debug("logout response: {}", samlResp);
} catch (SamlException e) {
LOGGER.error("Error processing logout", e);
return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
}
return new ResponseEntity<>(HttpStatus.OK);
}
@GetMapping(path = "/saml/logout")
public void logout(HttpServletResponse response) {
if (!samlEnabled) {
response.setStatus(NOT_IMPLEMENTED.getStatusCodeValue());
return;
}
try {
samlClient.redirectToIdentityProviderLogout(response, "status", "statustext");
} catch (IOException | SamlException e) {
LOGGER.error("Error processing logout", e);
response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
}
}
public boolean isEnabled() {
return samlEnabled;
}
public String getEndpoint() {
return String.format("%s/service/%s/%s/rest/saml", site.getDomain(), site.getName(), application.getName());
}
public String getLogoutPath() {
return String.format("%s/service/%s/%s/rest/saml/logout", site.getDomain(), site.getName(),
application.getName());
}
public void logout(Environment environment) {
String nameID = environment.getAttribute(Scope.SESSION, SAML_NAME_ID);
if (StringUtils.isNotBlank(nameID)) {
try {
// hand-crafted SP initiated logout
// https://learn.microsoft.com/en-us/azure/active-directory/develop/single-sign-out-saml-protocol
RestTemplate restTemplate = new RestTemplate();
MultiValueMap<String, String> map = new LinkedMultiValueMap<>();
map.add("SAMLRequest", samlClient.getLogoutRequest(nameID));
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
URI url = new URI(samlClient.getIdentityProviderUrl());
ResponseEntity<String> logout = restTemplate
.exchange(new RequestEntity<>(map, headers, HttpMethod.POST, url), String.class);
LOGGER.info("Logging out {} at {} returned {}", nameID, url, logout.getStatusCode());
} catch (SamlException | URISyntaxException e) {
LOGGER.error("Error performing logout", e);
}
}
}
}