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