001/*
002 * (C) Copyright 2006-2007 Nuxeo SA (http://nuxeo.com/) and others.
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 *     http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 *
016 * Contributors:
017 *     Nuxeo - initial API and implementation
018 *     Florent Guillaume
019 *     Florent Munch
020 */
021package org.nuxeo.ecm.platform.ui.web.auth.portal;
022
023import java.security.MessageDigest;
024import java.security.NoSuchAlgorithmException;
025import java.util.Base64;
026import java.util.Date;
027import java.util.List;
028import java.util.Map;
029
030import javax.servlet.http.HttpServletRequest;
031import javax.servlet.http.HttpServletResponse;
032
033import org.apache.commons.lang3.StringUtils;
034import org.apache.commons.logging.Log;
035import org.apache.commons.logging.LogFactory;
036import org.nuxeo.ecm.platform.api.login.UserIdentificationInfo;
037import org.nuxeo.ecm.platform.ui.web.auth.interfaces.NuxeoAuthenticationPlugin;
038
039public class PortalAuthenticator implements NuxeoAuthenticationPlugin {
040
041    private static final Log log = LogFactory.getLog(PortalAuthenticator.class);
042
043    public static final String SECRET_KEY_NAME = "secret";
044
045    public static final String MAX_AGE_KEY_NAME = "maxAge";
046
047    /** @since 10.3 */
048    public static final String DIGEST_ALGORITHM_KEY_NAME = "digestAlgorithm";
049
050    public static final String DIGEST_ALGORITHM_DEFAULT = "MD5";
051
052    private static final String TS_HEADER = "NX_TS";
053
054    private static final String RANDOM_HEADER = "NX_RD";
055
056    private static final String TOKEN_HEADER = "NX_TOKEN";
057
058    private static final String USER_HEADER = "NX_USER";
059
060    private static final String TOKEN_SEP = ":";
061
062    //
063    private String secret = "secret";
064
065    // one hour by default
066    private long maxAge = 60 * 60;
067
068    protected String digestAlgorithm = DIGEST_ALGORITHM_DEFAULT;
069
070    @Override
071    public List<String> getUnAuthenticatedURLPrefix() {
072        return null; // NOSONAR
073    }
074
075    @Override
076    public Boolean handleLoginPrompt(HttpServletRequest httpRequest, HttpServletResponse httpResponse, String baseURL) {
077        return Boolean.FALSE;
078    }
079
080    @Override
081    public UserIdentificationInfo handleRetrieveIdentity(HttpServletRequest httpRequest,
082            HttpServletResponse httpResponse) {
083
084        String ts = httpRequest.getHeader(TS_HEADER);
085        String random = httpRequest.getHeader(RANDOM_HEADER);
086        String token = httpRequest.getHeader(TOKEN_HEADER);
087        String userName = httpRequest.getHeader(USER_HEADER);
088
089        if (userName == null || ts == null || random == null || token == null) {
090            return null;
091        }
092
093        if (validateToken(ts, random, token, userName)) {
094            return new UserIdentificationInfo(userName, userName);
095        } else {
096            return null;
097        }
098    }
099
100    @Override
101    public void initPlugin(Map<String, String> parameters) {
102        if (parameters.containsKey(SECRET_KEY_NAME)) {
103            secret = parameters.get(SECRET_KEY_NAME);
104        }
105        if (parameters.containsKey(MAX_AGE_KEY_NAME)) {
106            String maxAgeStr = parameters.get(MAX_AGE_KEY_NAME);
107            if (maxAgeStr != null && !maxAgeStr.equals("")) {
108                maxAge = Long.parseLong(maxAgeStr);
109            }
110        }
111        if (parameters.containsKey(DIGEST_ALGORITHM_KEY_NAME)) {
112            String algo = parameters.get(DIGEST_ALGORITHM_KEY_NAME);
113            if (StringUtils.isNotBlank(algo)) {
114                digestAlgorithm = algo;
115            }
116        }
117    }
118
119    @Override
120    public Boolean needLoginPrompt(HttpServletRequest httpRequest) {
121        return Boolean.FALSE;
122    }
123
124    protected boolean validateToken(String ts, String random, String token, String userName) {
125        // reconstruct the token
126        String clearToken = ts + TOKEN_SEP + random + TOKEN_SEP + secret + TOKEN_SEP + userName;
127
128        byte[] hashedToken;
129        try {
130            hashedToken = MessageDigest.getInstance(digestAlgorithm).digest(clearToken.getBytes());
131        } catch (NoSuchAlgorithmException e) {
132            log.error("Invalid algorithm: " + digestAlgorithm);
133            return false;
134        }
135        String base64HashedToken = Base64.getEncoder().encodeToString(hashedToken);
136
137        // check that tokens are the same => that we have the same shared key
138        if (!base64HashedToken.equals(token)) {
139            return false;
140        }
141
142        // check time stamp
143        long portalTS = Long.parseLong(ts);
144        long currentTS = (new Date()).getTime();
145
146        return (currentTS - portalTS) / 1000 <= maxAge;
147    }
148
149}