]> git.argeo.org Git - lgpl/argeo-commons.git/blob - org.argeo.cms/src/org/argeo/cms/internal/http/CmsAuthenticator.java
Prepare next development cycle
[lgpl/argeo-commons.git] / org.argeo.cms / src / org / argeo / cms / internal / http / CmsAuthenticator.java
1 package org.argeo.cms.internal.http;
2
3 import javax.security.auth.Subject;
4 import javax.security.auth.login.LoginContext;
5 import javax.security.auth.login.LoginException;
6
7 import org.argeo.api.cms.CmsAuth;
8 import org.argeo.cms.CurrentUser;
9 import org.argeo.cms.auth.RemoteAuthCallbackHandler;
10 import org.argeo.cms.auth.RemoteAuthRequest;
11 import org.argeo.cms.auth.RemoteAuthResponse;
12 import org.argeo.cms.auth.RemoteAuthUtils;
13 import org.argeo.cms.http.RemoteAuthHttpExchange;
14
15 import com.sun.net.httpserver.Authenticator;
16 import com.sun.net.httpserver.HttpExchange;
17 import com.sun.net.httpserver.HttpPrincipal;
18
19 /** An {@link Authenticator} implementation based on CMS authentication. */
20 public class CmsAuthenticator extends Authenticator {
21 // TODO make it configurable
22 private final String httpAuthRealm = "Argeo";
23 private final boolean forceBasic = false;
24
25 @Override
26 public Result authenticate(HttpExchange exch) {
27 RemoteAuthHttpExchange remoteAuthExchange = new RemoteAuthHttpExchange(exch);
28 ClassLoader currentThreadContextClassLoader = Thread.currentThread().getContextClassLoader();
29 Thread.currentThread().setContextClassLoader(CmsAuthenticator.class.getClassLoader());
30 LoginContext lc;
31 try {
32 lc = CmsAuth.USER.newLoginContext(new RemoteAuthCallbackHandler(remoteAuthExchange, remoteAuthExchange));
33 lc.login();
34 } catch (LoginException e) {
35 if (authIsRequired(remoteAuthExchange, remoteAuthExchange)) {
36 int statusCode = RemoteAuthUtils.askForWwwAuth(remoteAuthExchange, remoteAuthExchange, httpAuthRealm,
37 forceBasic);
38 return new Authenticator.Retry(statusCode);
39
40 } else {
41 lc = RemoteAuthUtils.anonymousLogin(remoteAuthExchange, remoteAuthExchange);
42 }
43 if (lc == null)
44 return new Authenticator.Failure(403);
45 } finally {
46 Thread.currentThread().setContextClassLoader(currentThreadContextClassLoader);
47 }
48
49 Subject subject = lc.getSubject();
50
51 String username = CurrentUser.getUsername(subject);
52 HttpPrincipal httpPrincipal = new HttpPrincipal(username, httpAuthRealm);
53 return new Authenticator.Success(httpPrincipal);
54 }
55
56 protected boolean authIsRequired(RemoteAuthRequest remoteAuthRequest, RemoteAuthResponse remoteAuthResponse) {
57 return true;
58 }
59
60 }