]> git.argeo.org Git - lgpl/argeo-commons.git/blob - org.argeo.cms/src/org/argeo/cms/internal/http/CmsAuthenticator.java
Improve ACR attribute typing.
[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
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 RemoteAuthHttpExchange remoteAuthExchange = new RemoteAuthHttpExchange(exch);
27 ClassLoader currentThreadContextClassLoader = Thread.currentThread().getContextClassLoader();
28 Thread.currentThread().setContextClassLoader(CmsAuthenticator.class.getClassLoader());
29 LoginContext lc;
30 try {
31 lc = CmsAuth.USER.newLoginContext(new RemoteAuthCallbackHandler(remoteAuthExchange, remoteAuthExchange));
32 lc.login();
33 } catch (LoginException e) {
34 if (authIsRequired(remoteAuthExchange, remoteAuthExchange)) {
35 int statusCode = RemoteAuthUtils.askForWwwAuth(remoteAuthExchange, remoteAuthExchange, httpAuthRealm,
36 forceBasic);
37 return new Authenticator.Retry(statusCode);
38
39 } else {
40 lc = RemoteAuthUtils.anonymousLogin(remoteAuthExchange, remoteAuthExchange);
41 }
42 if (lc == null)
43 return new Authenticator.Failure(403);
44 } finally {
45 Thread.currentThread().setContextClassLoader(currentThreadContextClassLoader);
46 }
47
48 Subject subject = lc.getSubject();
49
50 String username = CurrentUser.getUsername(subject);
51 HttpPrincipal httpPrincipal = new HttpPrincipal(username, httpAuthRealm);
52 return new Authenticator.Success(httpPrincipal);
53 }
54
55 protected boolean authIsRequired(RemoteAuthRequest remoteAuthRequest, RemoteAuthResponse remoteAuthResponse) {
56 return true;
57 }
58
59 }