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