1 package org
.argeo
.cms
.internal
.http
;
3 import javax
.security
.auth
.Subject
;
4 import javax
.security
.auth
.login
.LoginContext
;
5 import javax
.security
.auth
.login
.LoginException
;
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
;
14 import com
.sun
.net
.httpserver
.Authenticator
;
15 import com
.sun
.net
.httpserver
.HttpExchange
;
16 import com
.sun
.net
.httpserver
.HttpPrincipal
;
18 public class CmsAuthenticator
extends Authenticator
{
19 // final static String HEADER_AUTHORIZATION = "Authorization";
20 // final static String HEADER_WWW_AUTHENTICATE = "WWW-Authenticate";
22 // private final static CmsLog log = CmsLog.getLog(CmsAuthenticator.class);
24 // TODO make it configurable
25 private final String httpAuthRealm
= "Argeo";
26 private final boolean forceBasic
= false;
29 public Result
authenticate(HttpExchange exch
) {
30 // if (log.isTraceEnabled())
31 // HttpUtils.logRequestHeaders(log, request);
32 RemoteAuthHttpExchange remoteAuthExchange
= new RemoteAuthHttpExchange(exch
);
33 ClassLoader currentThreadContextClassLoader
= Thread
.currentThread().getContextClassLoader();
34 Thread
.currentThread().setContextClassLoader(CmsAuthenticator
.class.getClassLoader());
37 lc
= CmsAuth
.USER
.newLoginContext(new RemoteAuthCallbackHandler(remoteAuthExchange
, remoteAuthExchange
));
39 } catch (LoginException e
) {
40 if (authIsRequired(remoteAuthExchange
, remoteAuthExchange
)) {
41 int statusCode
= RemoteAuthUtils
.askForWwwAuth(remoteAuthExchange
, remoteAuthExchange
, httpAuthRealm
,
43 return new Authenticator
.Retry(statusCode
);
46 lc
= RemoteAuthUtils
.anonymousLogin(remoteAuthExchange
, remoteAuthExchange
);
49 return new Authenticator
.Failure(403);
51 Thread
.currentThread().setContextClassLoader(currentThreadContextClassLoader
);
54 Subject subject
= lc
.getSubject();
56 // CurrentSubject.callAs(subject, () -> {
57 // RemoteAuthUtils.configureRequestSecurity(remoteAuthExchange);
60 // Subject.doAs(subject, new PrivilegedAction<Void>() {
63 // public Void run() {
64 // // TODO also set login context in order to log out ?
65 // RemoteAuthUtils.configureRequestSecurity(new ServletHttpRequest(request));
70 String username
= CurrentUser
.getUsername(subject
);
71 HttpPrincipal httpPrincipal
= new HttpPrincipal(username
, httpAuthRealm
);
72 return new Authenticator
.Success(httpPrincipal
);
75 protected boolean authIsRequired(RemoteAuthRequest remoteAuthRequest
, RemoteAuthResponse remoteAuthResponse
) {