-
Notifications
You must be signed in to change notification settings - Fork 0
/
SamlController.java
167 lines (146 loc) · 6.49 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
package org.appng.application.authentication.saml;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
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.Environment;
import org.appng.api.model.Application;
import org.appng.api.model.Site;
import org.appng.api.model.Subject;
import org.appng.core.service.CoreService;
import org.opensaml.core.xml.XMLObject;
import org.opensaml.core.xml.schema.XSString;
import org.opensaml.saml.saml2.core.Assertion;
import org.opensaml.saml.saml2.core.Attribute;
import org.opensaml.saml.saml2.core.AttributeStatement;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
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 com.coveo.saml.SamlClient;
import com.coveo.saml.SamlException;
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 {
@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 @Value("${samlEnabled:false}") boolean samlEnabled;
private @Value("${samlClientId:}") String clientId;
// private @Value("${samlAssertionConsumerUrl:}") String assertionConsumerUrl;
private SamlClient samlClient;
@Override
public void afterPropertiesSet() throws Exception {
if (samlEnabled) {
byte[] samlDescriptor = application.getProperties().getClob("samlDescriptor")
.getBytes(StandardCharsets.UTF_8);
String assertionConsumerUrl = String.format("%s/service/%s/%s/rest/saml", site.getDomain(), site.getName(),
application.getName());
samlClient = SamlClient.fromMetadata(clientId, assertionConsumerUrl,
new InputStreamReader(new ByteArrayInputStream(samlDescriptor)), SamlClient.SamlIdpBinding.POST);
LOGGER.debug("Created SAML client for '' with endpoint {}", clientId, assertionConsumerUrl);
} 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/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", produces = { MediaType.TEXT_PLAIN_VALUE }, consumes = {
MediaType.TEXT_PLAIN_VALUE, MediaType.APPLICATION_XML_VALUE })
public ResponseEntity<String> logout(@RequestBody String payload) {
if (!samlEnabled) {
return NOT_IMPLEMENTED;
}
return new ResponseEntity<>(payload, HttpStatus.OK);
}
@PostMapping(path = "/saml", produces = { MediaType.TEXT_PLAIN_VALUE }, consumes = { MediaType.TEXT_PLAIN_VALUE,
MediaType.APPLICATION_XML_VALUE, MediaType.APPLICATION_FORM_URLENCODED_VALUE })
public ResponseEntity<Void> reply(HttpServletRequest request, Environment environment) {
if (!samlEnabled) {
return NOT_IMPLEMENTED;
}
ResponseEntity<Void> response = new ResponseEntity<>(HttpStatus.UNAUTHORIZED);
try {
String parameter = request.getParameter("SAMLResponse");
LOGGER.debug("Received SAMLResponse: {}", parameter);
SamlResponse samlResp = samlClient.decodeAndValidateSamlResponse(parameter, request.getMethod());
Assertion assertion = samlResp.getAssertion();
Map<String, List<XMLObject>> stringAttributes = new HashMap<>();
for (AttributeStatement as : assertion.getAttributeStatements()) {
for (Attribute attr : as.getAttributes()) {
String name = attr.getName();
List<XMLObject> values = attr.getAttributeValues().stream()//.filter(v -> (v instanceof XSString))
//.map(XSString.class::cast).map(XSString::getValue)
.collect(Collectors.toList());
stringAttributes.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
// String emailAttributeName = "Email";
// List<String> emails = stringAttributes.get(emailAttributeName);
// if (!emails.isEmpty()) {
// String email = emails.get(0);
// Subject subject = coreService.getSubjectByEmail(email);
// if (null == subject) {
// // TODO create subject with basic user group?
//
// } else {
// coreService.loginByUserName(environment, subject.getAuthName());
// HttpHeaders headers = new HttpHeaders();
// // TODO forward to certain application
// headers.set(HttpHeaders.LOCATION, "/manager");
// response = new ResponseEntity<>(headers, HttpStatus.FOUND);
// }
// }
} catch (SamlException e) {
LOGGER.error("Error processing SAML Response", e);
response = new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
}
return response;
}
}