001/*
002 * (C) Copyright 2006-2011 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 *     Stephane Lacoin (aka matic)
018 */
019
020package org.nuxeo.ecm.core.opencmis.impl.client;
021
022import java.security.MessageDigest;
023import java.security.NoSuchAlgorithmException;
024import java.util.Collections;
025import java.util.Date;
026import java.util.HashMap;
027import java.util.List;
028import java.util.Map;
029import java.util.Random;
030
031import org.apache.chemistry.opencmis.client.bindings.spi.AbstractAuthenticationProvider;
032import org.apache.chemistry.opencmis.commons.impl.Base64;
033
034public class NuxeoPortalSSOAuthenticationProvider extends AbstractAuthenticationProvider {
035
036    private static final long serialVersionUID = 1L;
037
038    protected static final Random RANDOM = new Random();
039
040    public final static String SECRET_KEY = "NUXEO_PORTAL_SSO_SECRET";
041
042    protected String getSecretKey() {
043        return (String) getSession().get(SECRET_KEY);
044    }
045
046    @Override
047    public Map<String, List<String>> getHTTPHeaders(String url) {
048
049        long ts = new Date().getTime();
050        long random = RANDOM.nextInt();
051
052        String secret = getSecretKey();
053
054        String username = getUser();
055
056        String clearToken = String.format("%d:%d:%s:%s", ts, random, secret, username);
057
058        byte[] hashedToken;
059
060        try {
061            hashedToken = MessageDigest.getInstance("MD5").digest(clearToken.getBytes());
062        } catch (NoSuchAlgorithmException e) {
063            throw new Error("Cannot compute token", e);
064        }
065
066        String base64HashedToken = Base64.encodeBytes(hashedToken);
067
068        // set request headers
069
070        Map<String, List<String>> headers = new HashMap<String, List<String>>();
071
072        headers.put("NX_USER", Collections.singletonList(username));
073        headers.put("NX_TOKEN", Collections.singletonList(base64HashedToken));
074        headers.put("NX_RD", Collections.singletonList(String.valueOf(random)));
075        headers.put("NX_TS", Collections.singletonList(String.valueOf(ts)));
076
077        return Collections.unmodifiableMap(headers);
078
079    }
080
081}