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