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                log.debug( "No cookie {} present in session ID=:  {}", PREFS_COOKIE_NAME, sid );
088                throw new FailedLoginException( "The user cookie was not found." );
089            }
090
091            log.debug( "Logged in session ID={}; asserted={}", sid, name );
092            // If login succeeds, commit these principals/roles
093            m_principals.add( new WikiPrincipal( name, WikiPrincipal.FULL_NAME ) );
094            return true;
095        } catch( final IOException e ) {
096            log.error( "IOException: " + e.getMessage() );
097            return false;
098        } catch( final UnsupportedCallbackException e ) {
099            final String message = "Unable to handle callback, disallowing login.";
100            log.error( message, e );
101            throw new LoginException( message );
102        }
103    }
104
105    /**
106     *  Returns the username cookie value.
107     *
108     *  @param request The Servlet request, as usual.
109     *  @return the username, as retrieved from the cookie
110     */
111    public static String getUserCookie( final HttpServletRequest request ) {
112        final String cookie = HttpUtil.retrieveCookieValue( request, PREFS_COOKIE_NAME );
113        final String usernameCookie = TextUtil.urlDecodeUTF8( cookie );
114        return usernameCookie!= null && usernameCookie.contains( "-->" ) ?
115               usernameCookie.substring( 0, usernameCookie.indexOf( "-->" ) ) :
116               usernameCookie;
117    }
118
119    /**
120     *  Sets the username cookie.  The cookie value is URLEncoded in UTF-8.
121     *
122     *  @param response The Servlet response
123     *  @param name     The name to write into the cookie.
124     */
125    public static void setUserCookie( final HttpServletResponse response, String name ) {
126        name = TextUtil.urlEncodeUTF8( name );
127        final Cookie userId = new Cookie( PREFS_COOKIE_NAME, name );
128        userId.setMaxAge( 1001 * 24 * 60 * 60 ); // 1001 days is default.
129        response.addCookie( userId );
130    }
131
132    /**
133     *  Removes the user cookie from the response. This makes the user appear again as an anonymous coward.
134     *
135     *  @param response The servlet response.
136     */
137    public static void clearUserCookie( final HttpServletResponse response ) {
138        HttpUtil.clearCookie( response, PREFS_COOKIE_NAME );
139    }
140
141}