]> git.argeo.org Git - lgpl/argeo-commons.git/blob - internal/http/CmsAuthenticator.java
Prepare next development cycle
[lgpl/argeo-commons.git] / 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.auth.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
14 import com.sun.net.httpserver.Authenticator;
15 import com.sun.net.httpserver.HttpExchange;
16 import com.sun.net.httpserver.HttpPrincipal;
17
18 /** An {@link Authenticator} implementation based on CMS authentication. */
19 public class CmsAuthenticator extends Authenticator {
20 // TODO make it configurable
21 private final String httpAuthRealm = "Argeo";
22 private final boolean forceBasic = false;
23
24 @Override
25 public Result authenticate(HttpExchange exch) {
26 // if (log.isTraceEnabled())
27 // HttpUtils.logRequestHeaders(log, request);
28 RemoteAuthHttpExchange remoteAuthExchange = new RemoteAuthHttpExchange(exch);
29 ClassLoader currentThreadContextClassLoader = Thread.currentThread().getContextClassLoader();
30 Thread.currentThread().setContextClassLoader(CmsAuthenticator.class.getClassLoader());
31 LoginContext lc;
32 try {
33 lc = CmsAuth.USER.newLoginContext(new RemoteAuthCallbackHandler(remoteAuthExchange, remoteAuthExchange));
34 lc.login();
35 } catch (LoginException e) {
36 if (authIsRequired(remoteAuthExchange, remoteAuthExchange)) {
37 int statusCode = RemoteAuthUtils.askForWwwAuth(remoteAuthExchange, remoteAuthExchange, httpAuthRealm,
38 forceBasic);
39 return new Authenticator.Retry(statusCode);
40
41 } else {
42 lc = RemoteAuthUtils.anonymousLogin(remoteAuthExchange, remoteAuthExchange);
43 }
44 if (lc == null)
45 return new Authenticator.Failure(403);
46 } finally {
47 Thread.currentThread().setContextClassLoader(currentThreadContextClassLoader);
48 }
49
50 Subject subject = lc.getSubject();
51
52 // CurrentSubject.callAs(subject, () -> {
53 // RemoteAuthUtils.configureRequestSecurity(remoteAuthExchange);
54 // return null;
55 // });
56 // Subject.doAs(subject, new PrivilegedAction<Void>() {
57 //
58 // @Override
59 // public Void run() {
60 // // TODO also set login context in order to log out ?
61 // RemoteAuthUtils.configureRequestSecurity(new ServletHttpRequest(request));
62 // return null;
63 // }
64 //
65 // });
66 String username = CurrentUser.getUsername(subject);
67 HttpPrincipal httpPrincipal = new HttpPrincipal(username, httpAuthRealm);
68 return new Authenticator.Success(httpPrincipal);
69 }
70
71 protected boolean authIsRequired(RemoteAuthRequest remoteAuthRequest, RemoteAuthResponse remoteAuthResponse) {
72 return true;
73 }
74
75 }