001/*
002    Licensed to the Apache Software Foundation (ASF) under one
003    or more contributor license agreements.  See the NOTICE file
004    distributed with this work for additional information
005    regarding copyright ownership.  The ASF licenses this file
006    to you under the Apache License, Version 2.0 (the
007    "License"); you may not use this file except in compliance
008    with the License.  You may obtain a copy of the License at
009
010       http://www.apache.org/licenses/LICENSE-2.0
011
012    Unless required by applicable law or agreed to in writing,
013    software distributed under the License is distributed on an
014    "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
015    KIND, either express or implied.  See the License for the
016    specific language governing permissions and limitations
017    under the License.    
018 */
019package org.apache.wiki.auth.login;
020
021import org.apache.logging.log4j.LogManager;
022import org.apache.logging.log4j.Logger;
023import org.apache.wiki.auth.WikiPrincipal;
024import org.apache.wiki.util.HttpUtil;
025import org.apache.wiki.util.TextUtil;
026
027import javax.security.auth.callback.Callback;
028import javax.security.auth.callback.UnsupportedCallbackException;
029import javax.security.auth.login.FailedLoginException;
030import javax.security.auth.login.LoginException;
031import javax.servlet.http.Cookie;
032import javax.servlet.http.HttpServletRequest;
033import javax.servlet.http.HttpServletResponse;
034import javax.servlet.http.HttpSession;
035import java.io.IOException;
036
037/**
038 * <p>
039 * Logs in a user based on assertion of a name supplied in a cookie. If the
040 * cookie is not found, authentication fails.
041 * </p>
042 * This module must be used with a CallbackHandler (such as
043 * {@link WebContainerCallbackHandler}) that supports the following Callback
044 * types:
045 * </p>
046 * <ol>
047 * <li>{@link HttpRequestCallback}- supplies the cookie, which should contain
048 * a user name.</li>
049 * </ol>
050 * <p>
051 * After authentication, a generic WikiPrincipal based on the username will be
052 * created and associated with the Subject.
053 * </p>
054 * @see javax.security.auth.spi.LoginModule#commit()
055 * @see CookieAuthenticationLoginModule
056 * @since 2.3
057 */
058public class CookieAssertionLoginModule extends AbstractLoginModule {
059
060    /** The name of the cookie that gets stored to the user browser. */
061    public static final String PREFS_COOKIE_NAME = "JSPWikiAssertedName";
062
063    private static final Logger log = LogManager.getLogger( CookieAssertionLoginModule.class );
064
065    /**
066     * {@inheritDoc}
067     *
068     * Logs in the user by calling back to the registered CallbackHandler with
069     * an HttpRequestCallback. The CallbackHandler must supply the current
070     * servlet HTTP request as its response.
071     * @return the result of the login; if a cookie is
072     * found, this method returns <code>true</code>. If not found, this
073     * method throws a <code>FailedLoginException</code>.
074     * @see javax.security.auth.spi.LoginModule#login()
075     */
076    public boolean login() throws LoginException {
077        // Otherwise, let's go and look for the cookie!
078        final HttpRequestCallback hcb = new HttpRequestCallback();
079        final Callback[] callbacks = new Callback[] { hcb };
080        try {
081            m_handler.handle( callbacks );
082            final HttpServletRequest request = hcb.getRequest();
083            final HttpSession session = ( request == null ) ? null : request.getSession( false );
084            final String sid = ( session == null ) ? NULL : session.getId();
085            final String name = (request != null) ? getUserCookie( request ) : null;
086            if ( name == null ) {
087                if ( log.isDebugEnabled() ) {
088                    log.debug( "No cookie " + PREFS_COOKIE_NAME + " present in session ID=:  " + sid );
089                }
090                throw new FailedLoginException( "The user cookie was not found." );
091            }
092
093            if ( log.isDebugEnabled() ) {
094                log.debug( "Logged in session ID=" + sid + "; asserted=" + name );
095            }
096            // If login succeeds, commit these principals/roles
097            m_principals.add( new WikiPrincipal( name, WikiPrincipal.FULL_NAME ) );
098            return true;
099        } catch( final IOException e ) {
100            log.error( "IOException: " + e.getMessage() );
101            return false;
102        } catch( final UnsupportedCallbackException e ) {
103            final String message = "Unable to handle callback, disallowing login.";
104            log.error( message, e );
105            throw new LoginException( message );
106        }
107    }
108
109    /**
110     *  Returns the username cookie value.
111     *
112     *  @param request The Servlet request, as usual.
113     *  @return the username, as retrieved from the cookie
114     */
115    public static String getUserCookie( final HttpServletRequest request ) {
116        final String cookie = HttpUtil.retrieveCookieValue( request, PREFS_COOKIE_NAME );
117        final String usernameCookie = TextUtil.urlDecodeUTF8( cookie );
118        return usernameCookie!= null && usernameCookie.contains( "-->" ) ?
119               usernameCookie.substring( 0, usernameCookie.indexOf( "-->" ) ) :
120               usernameCookie;
121    }
122
123    /**
124     *  Sets the username cookie.  The cookie value is URLEncoded in UTF-8.
125     *
126     *  @param response The Servlet response
127     *  @param name     The name to write into the cookie.
128     */
129    public static void setUserCookie( final HttpServletResponse response, String name ) {
130        name = TextUtil.urlEncodeUTF8( name );
131        final Cookie userId = new Cookie( PREFS_COOKIE_NAME, name );
132        userId.setMaxAge( 1001 * 24 * 60 * 60 ); // 1001 days is default.
133        response.addCookie( userId );
134    }
135
136    /**
137     *  Removes the user cookie from the response. This makes the user appear again as an anonymous coward.
138     *
139     *  @param response The servlet response.
140     */
141    public static void clearUserCookie( final HttpServletResponse response ) {
142        HttpUtil.clearCookie( response, PREFS_COOKIE_NAME );
143    }
144
145}