001/* 
002 * Copyright (c) 2006-2011 Nuxeo SA (http://nuxeo.com/) and others.
003 *
004 * All rights reserved. This program and the accompanying materials
005 * are made available under the terms of the Eclipse Public License v1.0
006 * which accompanies this distribution, and is available at
007 * http://www.eclipse.org/legal/epl-v10.html
008 *
009 * Contributors:
010 *     Stephane Lacoin (aka matic)
011 */
012
013package org.nuxeo.ecm.core.opencmis.impl.client;
014
015import java.security.MessageDigest;
016import java.security.NoSuchAlgorithmException;
017import java.util.Collections;
018import java.util.Date;
019import java.util.HashMap;
020import java.util.List;
021import java.util.Map;
022import java.util.Random;
023
024import org.apache.chemistry.opencmis.client.bindings.spi.AbstractAuthenticationProvider;
025import org.nuxeo.common.utils.Base64;
026
027public class NuxeoPortalSSOAuthenticationProvider extends AbstractAuthenticationProvider {
028
029    private static final long serialVersionUID = 1L;
030
031    public final static String SECRET_KEY = "NUXEO_PORTAL_SSO_SECRET";
032
033    protected String getSecretKey() {
034        return (String) getSession().get(SECRET_KEY);
035    }
036
037    @Override
038    public Map<String, List<String>> getHTTPHeaders(String url) {
039
040        long ts = new Date().getTime();
041        long random = new Random(ts).nextInt();
042
043        String secret = getSecretKey();
044
045        String username = getUser();
046
047        String clearToken = String.format("%d:%d:%s:%s", ts, random, secret, username);
048
049        byte[] hashedToken;
050
051        try {
052            hashedToken = MessageDigest.getInstance("MD5").digest(clearToken.getBytes());
053        } catch (NoSuchAlgorithmException e) {
054            throw new Error("Cannot compute token", e);
055        }
056
057        String base64HashedToken = Base64.encodeBytes(hashedToken);
058
059        // set request headers
060
061        Map<String, List<String>> headers = new HashMap<String, List<String>>();
062
063        headers.put("NX_USER", Collections.singletonList(username));
064        headers.put("NX_TOKEN", Collections.singletonList(base64HashedToken));
065        headers.put("NX_RD", Collections.singletonList(String.valueOf(random)));
066        headers.put("NX_TS", Collections.singletonList(String.valueOf(ts)));
067
068        return Collections.unmodifiableMap(headers);
069
070    }
071
072}