]> git.argeo.org Git - lgpl/argeo-commons.git/blob - org/argeo/cms/auth/HttpSessionLoginModule.java
Prepare next development cycle
[lgpl/argeo-commons.git] / org / argeo / cms / auth / HttpSessionLoginModule.java
1 package org.argeo.cms.auth;
2
3 import java.io.IOException;
4 import java.security.cert.X509Certificate;
5 import java.util.Base64;
6 import java.util.Collection;
7 import java.util.Locale;
8 import java.util.Map;
9 import java.util.StringTokenizer;
10
11 import javax.security.auth.Subject;
12 import javax.security.auth.callback.Callback;
13 import javax.security.auth.callback.CallbackHandler;
14 import javax.security.auth.callback.UnsupportedCallbackException;
15 import javax.security.auth.login.LoginException;
16 import javax.security.auth.spi.LoginModule;
17 import javax.servlet.http.HttpServletRequest;
18 import javax.servlet.http.HttpServletResponse;
19 import javax.servlet.http.HttpSession;
20
21 import org.apache.commons.logging.Log;
22 import org.apache.commons.logging.LogFactory;
23 import org.argeo.cms.CmsException;
24 import org.argeo.cms.internal.kernel.Activator;
25 import org.osgi.framework.BundleContext;
26 import org.osgi.framework.FrameworkUtil;
27 import org.osgi.framework.InvalidSyntaxException;
28 import org.osgi.framework.ServiceReference;
29 import org.osgi.service.http.HttpContext;
30 import org.osgi.service.useradmin.Authorization;
31
32 public class HttpSessionLoginModule implements LoginModule {
33 private final static Log log = LogFactory.getLog(HttpSessionLoginModule.class);
34
35 private Subject subject = null;
36 private CallbackHandler callbackHandler = null;
37 private Map<String, Object> sharedState = null;
38
39 private HttpServletRequest request = null;
40 private HttpServletResponse response = null;
41
42 private BundleContext bc;
43
44 private Authorization authorization;
45 private Locale locale;
46
47 @SuppressWarnings("unchecked")
48 @Override
49 public void initialize(Subject subject, CallbackHandler callbackHandler, Map<String, ?> sharedState,
50 Map<String, ?> options) {
51 bc = FrameworkUtil.getBundle(HttpSessionLoginModule.class).getBundleContext();
52 assert bc != null;
53 this.subject = subject;
54 this.callbackHandler = callbackHandler;
55 this.sharedState = (Map<String, Object>) sharedState;
56 }
57
58 @Override
59 public boolean login() throws LoginException {
60 if (callbackHandler == null)
61 return false;
62 HttpRequestCallback httpCallback = new HttpRequestCallback();
63 try {
64 callbackHandler.handle(new Callback[] { httpCallback });
65 } catch (IOException e) {
66 throw new LoginException("Cannot handle http callback: " + e.getMessage());
67 } catch (UnsupportedCallbackException e) {
68 return false;
69 }
70 request = httpCallback.getRequest();
71 if (request == null)
72 return false;
73 authorization = (Authorization) request.getAttribute(HttpContext.AUTHORIZATION);
74 if (authorization == null) {// search by session ID
75 HttpSession httpSession = request.getSession(false);
76 if (httpSession == null) {
77 // TODO make sure this is always safe
78 if (log.isTraceEnabled())
79 log.trace("Create http session");
80 httpSession = request.getSession(true);
81 }
82 String httpSessionId = httpSession.getId();
83 if (log.isTraceEnabled())
84 log.trace("HTTP login: " + request.getPathInfo() + " #" + httpSessionId);
85 Collection<ServiceReference<CmsSession>> sr;
86 try {
87 sr = bc.getServiceReferences(CmsSession.class,
88 "(" + CmsSession.SESSION_LOCAL_ID + "=" + httpSessionId + ")");
89 } catch (InvalidSyntaxException e) {
90 throw new CmsException("Cannot get CMS session for id " + httpSessionId, e);
91 }
92 if (sr.size() == 1) {
93 CmsSession cmsSession = bc.getService(sr.iterator().next());
94 locale = cmsSession.getLocale();
95 authorization = cmsSession.getAuthorization();
96 if (authorization.getName() == null)
97 authorization = null;// anonymous is not sufficient
98 if (log.isTraceEnabled())
99 log.trace("Retrieved authorization from " + cmsSession);
100 } else if (sr.size() == 0)
101 authorization = null;
102 else
103 throw new CmsException(sr.size() + ">1 web sessions detected for http session " + httpSessionId);
104
105 }
106 sharedState.put(CmsAuthUtils.SHARED_STATE_HTTP_REQUEST, request);
107 extractHttpAuth(request);
108 extractClientCertificate(request);
109 if (authorization == null) {
110 if (log.isTraceEnabled())
111 log.trace("HTTP login: " + false);
112 return false;
113 } else {
114 if (log.isTraceEnabled())
115 log.trace("HTTP login: " + true);
116 return true;
117 }
118 }
119
120 @Override
121 public boolean commit() throws LoginException {
122 byte[] outToken = (byte[]) sharedState.get(CmsAuthUtils.SHARED_STATE_SPNEGO_OUT_TOKEN);
123 if (outToken != null) {
124 response.setHeader(CmsAuthUtils.HEADER_WWW_AUTHENTICATE,
125 "Negotiate " + java.util.Base64.getEncoder().encodeToString(outToken));
126 }
127
128 if (authorization != null) {
129 // Locale locale = request.getLocale();
130 if (locale == null)
131 locale = request.getLocale();
132 subject.getPublicCredentials().add(locale);
133 CmsAuthUtils.addAuthorization(subject, authorization, locale, request);
134 CmsAuthUtils.registerSessionAuthorization(request, subject, authorization, locale);
135 cleanUp();
136 return true;
137 } else {
138 cleanUp();
139 return false;
140 }
141 }
142
143 @Override
144 public boolean abort() throws LoginException {
145 cleanUp();
146 return false;
147 }
148
149 private void cleanUp() {
150 authorization = null;
151 request = null;
152 }
153
154 @Override
155 public boolean logout() throws LoginException {
156 cleanUp();
157 return true;
158 }
159
160 private void extractHttpAuth(final HttpServletRequest httpRequest) {
161 String authHeader = httpRequest.getHeader(CmsAuthUtils.HEADER_AUTHORIZATION);
162 if (authHeader != null) {
163 StringTokenizer st = new StringTokenizer(authHeader);
164 if (st.hasMoreTokens()) {
165 String basic = st.nextToken();
166 if (basic.equalsIgnoreCase("Basic")) {
167 try {
168 // TODO manipulate char[]
169 Base64.Decoder decoder = Base64.getDecoder();
170 String credentials = new String(decoder.decode(st.nextToken()), "UTF-8");
171 // log.debug("Credentials: " + credentials);
172 int p = credentials.indexOf(":");
173 if (p != -1) {
174 final String login = credentials.substring(0, p).trim();
175 final char[] password = credentials.substring(p + 1).trim().toCharArray();
176 sharedState.put(CmsAuthUtils.SHARED_STATE_NAME, login);
177 sharedState.put(CmsAuthUtils.SHARED_STATE_PWD, password);
178 } else {
179 throw new CmsException("Invalid authentication token");
180 }
181 } catch (Exception e) {
182 throw new CmsException("Couldn't retrieve authentication", e);
183 }
184 } else if (basic.equalsIgnoreCase("Negotiate")) {
185 String spnegoToken = st.nextToken();
186 Base64.Decoder decoder = Base64.getDecoder();
187 byte[] authToken = decoder.decode(spnegoToken);
188 sharedState.put(CmsAuthUtils.SHARED_STATE_SPNEGO_TOKEN, authToken);
189 }
190 }
191 }
192
193 // auth token
194 // String mail = request.getParameter(LdapAttrs.mail.name());
195 // String authPassword = request.getParameter(LdapAttrs.authPassword.name());
196 // if (authPassword != null) {
197 // sharedState.put(CmsAuthUtils.SHARED_STATE_PWD, authPassword);
198 // if (mail != null)
199 // sharedState.put(CmsAuthUtils.SHARED_STATE_NAME, mail);
200 // }
201 }
202
203 private void extractClientCertificate(HttpServletRequest req) {
204 X509Certificate[] certs = (X509Certificate[]) req.getAttribute("javax.servlet.request.X509Certificate");
205 if (null != certs && certs.length > 0) {// Servlet container verified the client certificate
206 String certDn = certs[0].getSubjectX500Principal().getName();
207 sharedState.put(CmsAuthUtils.SHARED_STATE_NAME, certDn);
208 sharedState.put(CmsAuthUtils.SHARED_STATE_CERTIFICATE_CHAIN, certs);
209 if (log.isDebugEnabled())
210 log.debug("Client certificate " + certDn + " verified by servlet container");
211 } // Reverse proxy verified the client certificate
212 String clientDnHttpHeader = Activator.getHttpProxySslHeader();
213 if (clientDnHttpHeader != null) {
214 String certDn = req.getHeader(clientDnHttpHeader);
215 // TODO retrieve more cf. https://httpd.apache.org/docs/current/mod/mod_ssl.html
216 // String issuerDn = req.getHeader("SSL_CLIENT_I_DN");
217 if (certDn != null && !certDn.trim().equals("(null)")) {
218 sharedState.put(CmsAuthUtils.SHARED_STATE_NAME, certDn);
219 sharedState.put(CmsAuthUtils.SHARED_STATE_CERTIFICATE_CHAIN, "");
220 if (log.isDebugEnabled())
221 log.debug("Client certificate " + certDn + " verified by reverse proxy");
222 }
223 }
224 }
225
226 }