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