001/**
002 *   GRANITE DATA SERVICES
003 *   Copyright (C) 2006-2013 GRANITE DATA SERVICES S.A.S.
004 *
005 *   This file is part of the Granite Data Services Platform.
006 *
007 *   Granite Data Services is free software; you can redistribute it and/or
008 *   modify it under the terms of the GNU Lesser General Public
009 *   License as published by the Free Software Foundation; either
010 *   version 2.1 of the License, or (at your option) any later version.
011 *
012 *   Granite Data Services is distributed in the hope that it will be useful,
013 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
014 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser
015 *   General Public License for more details.
016 *
017 *   You should have received a copy of the GNU Lesser General Public
018 *   License along with this library; if not, write to the Free Software
019 *   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
020 *   USA, or see <http://www.gnu.org/licenses/>.
021 */
022package org.granite.messaging.service.security;
023
024import java.lang.reflect.Field;
025import java.lang.reflect.InvocationTargetException;
026import java.security.Principal;
027import java.util.Map;
028
029import javax.servlet.http.HttpServletRequest;
030import javax.servlet.http.HttpServletRequestWrapper;
031import javax.servlet.http.HttpSession;
032
033import org.apache.catalina.Context;
034import org.apache.catalina.Realm;
035import org.apache.catalina.Session;
036import org.apache.catalina.authenticator.Constants;
037import org.apache.catalina.connector.Request;
038import org.apache.catalina.connector.RequestFacade;
039import org.granite.context.GraniteContext;
040import org.granite.messaging.webapp.HttpGraniteContext;
041
042/**
043 * @author Franck WOLFF
044 */
045public class Tomcat7SecurityService extends AbstractSecurityService {
046
047    private final Field requestField;
048
049    public Tomcat7SecurityService() {
050        super();
051        try {
052            // We need to access the org.apache.catalina.connector.Request field from
053            // a org.apache.catalina.connector.RequestFacade. Unfortunately there is
054            // no public getter for this field (and I don't want to create a Valve)...
055            requestField = RequestFacade.class.getDeclaredField("request");
056            requestField.setAccessible(true);
057        } catch (Exception e) {
058            throw new RuntimeException("Could not get 'request' field in Tomcat RequestFacade", e);
059        }
060    }
061
062    protected Field getRequestField() {
063        return requestField;
064    }
065
066    
067    public void configure(Map<String, String> params) {
068    }
069
070    
071    public void login(Object credentials, String charset) throws SecurityServiceException {
072        String[] decoded = decodeBase64Credentials(credentials, charset);
073
074        HttpGraniteContext context = (HttpGraniteContext)GraniteContext.getCurrentInstance();
075        HttpServletRequest httpRequest = context.getRequest();
076        Request request = getRequest(httpRequest);
077        Realm realm = getRealm(request);
078
079        Principal principal = realm.authenticate(decoded[0], decoded[1]);
080        if (principal == null)
081            throw SecurityServiceException.newInvalidCredentialsException("Wrong username or password");
082
083        request.setAuthType(AUTH_TYPE);
084        request.setUserPrincipal(principal);
085
086        Session session = request.getSessionInternal();
087        session.setAuthType(AUTH_TYPE);
088        session.setPrincipal(principal);
089        session.setNote(Constants.SESS_USERNAME_NOTE, decoded[0]);
090        session.setNote(Constants.SESS_PASSWORD_NOTE, decoded[1]);
091        
092        endLogin(credentials, charset);
093    }
094
095    public Object authorize(AbstractSecurityContext context) throws Exception {
096
097        startAuthorization(context);
098        
099        HttpGraniteContext graniteContext = (HttpGraniteContext)GraniteContext.getCurrentInstance();
100        HttpServletRequest httpRequest = graniteContext.getRequest();
101        Request request = getRequest(httpRequest);
102        Session session = request.getSessionInternal(false);
103
104        Principal principal = null;
105        if (session != null) {
106            request.setAuthType(session.getAuthType());
107                principal = session.getPrincipal();
108                if (principal == null && tryRelogin())
109                        principal = session.getPrincipal();
110        }
111
112        request.setUserPrincipal(principal);
113
114        if (context.getDestination().isSecured()) {
115            if (principal == null) {
116                if (httpRequest.getRequestedSessionId() != null) {
117                    HttpSession httpSession = httpRequest.getSession(false);
118                    if (httpSession == null || httpRequest.getRequestedSessionId().equals(httpSession.getId()))
119                        throw SecurityServiceException.newSessionExpiredException("Session expired");
120                }
121                throw SecurityServiceException.newNotLoggedInException("User not logged in");
122            }
123
124            boolean accessDenied = true;
125            for (String role : context.getDestination().getRoles()) {
126                if (request.isUserInRole(role)) {
127                    accessDenied = false;
128                    break;
129                }
130            }
131            if (accessDenied)
132                throw SecurityServiceException.newAccessDeniedException("User not in required role");
133        }
134
135        try {
136            return endAuthorization(context);
137        } 
138        catch (InvocationTargetException e) {
139            for (Throwable t = e; t != null; t = t.getCause()) {
140                // Don't create a dependency to javax.ejb in SecurityService...
141                if (t instanceof SecurityException ||
142                    "javax.ejb.EJBAccessException".equals(t.getClass().getName()))
143                    throw SecurityServiceException.newAccessDeniedException(t.getMessage());
144            }
145            throw e;
146        }
147    }
148
149    public void logout() throws SecurityServiceException {
150        HttpGraniteContext context = (HttpGraniteContext)GraniteContext.getCurrentInstance();
151
152        Session session = getSession(context.getRequest(), false);
153        if (session != null && session.getPrincipal() != null) {
154            session.setAuthType(null);
155            session.setPrincipal(null);
156            session.removeNote(Constants.SESS_USERNAME_NOTE);
157            session.removeNote(Constants.SESS_PASSWORD_NOTE);
158            
159            endLogout();
160            
161            session.expire();
162        }
163    }
164
165    protected Principal getPrincipal(HttpServletRequest httpRequest) {
166        Request request = getRequest(httpRequest);
167        Session session = request.getSessionInternal(false);
168        return (session != null ? session.getPrincipal() : null);
169    }
170
171    protected Session getSession(HttpServletRequest httpRequest, boolean create) {
172        Request request = getRequest(httpRequest);
173        return request.getSessionInternal(create);
174    }
175
176    protected Request getRequest(HttpServletRequest request) {
177        while (request instanceof HttpServletRequestWrapper)
178            request = (HttpServletRequest)((HttpServletRequestWrapper)request).getRequest();
179        try {
180            return (Request)requestField.get(request);
181        } catch (Exception e) {
182            throw new RuntimeException("Could not get tomcat request", e);
183        }
184    }
185
186    protected Realm getRealm(Request request) {
187        String serverName = request.getServerName();
188        String contextPath = request.getContextPath();
189        
190        Context context = request.getContext();
191        if (context == null)
192            throw new NullPointerException("Could not find Tomcat context for: " + contextPath);
193        Realm realm = context.getRealm();
194        if (realm == null)
195            throw new NullPointerException("Could not find Tomcat realm for: " + serverName + "" + contextPath);
196
197        return realm;
198    }
199}