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 *     bstefanescu
018 */
019package org.nuxeo.ecm.webengine.jaxrs.login;
020
021import java.util.Map;
022
023import javax.security.auth.login.LoginContext;
024import javax.security.auth.login.LoginException;
025import javax.servlet.http.HttpServletRequest;
026import javax.servlet.http.HttpServletResponse;
027
028import org.apache.commons.codec.binary.Base64;
029import org.nuxeo.common.utils.StringUtils;
030import org.nuxeo.runtime.api.Framework;
031
032/**
033 * @author <a href="mailto:bs@nuxeo.com">Bogdan Stefanescu</a>
034 */
035public class Base64AuthenticationHandler implements AuthenticationHandler {
036
037    protected String realmName = "Nuxeo";
038
039    @Override
040    public void init(Map<String, String> properties) {
041        String name = properties.get("realmName");
042        if (name == null) {
043            realmName = name;
044        }
045    }
046
047    @Override
048    public LoginContext handleAuthentication(HttpServletRequest request, HttpServletResponse response)
049            throws LoginException {
050        String[] login = retrieveBasicLogin(request);
051        if (login != null) {
052            return Framework.login(login[0], login[1]);
053        }
054        return null;
055    }
056
057    protected String[] retrieveBasicLogin(HttpServletRequest httpRequest) {
058        String auth = httpRequest.getHeader("authorization");
059        if (auth != null && auth.toLowerCase().startsWith("basic")) {
060            int idx = auth.indexOf(' ');
061            String b64userpassword = auth.substring(idx + 1);
062            byte[] clearUp = Base64.decodeBase64(b64userpassword);
063            String userpassword = new String(clearUp);
064            String[] up = StringUtils.split(userpassword, ':', false);
065            if (up.length != 2) {
066                return null;
067            }
068            return up;
069        }
070        return null;
071    }
072
073    protected void handleLoginFailure(HttpServletRequest request, HttpServletResponse response) {
074        String s = "Basic realm=\"" + realmName + "\"";
075        response.setHeader("WWW-Authenticate", s);
076        response.setStatus(401);
077    }
078
079}