KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > blojsom > plugin > security > BasicAuthenticationPlugin


1 /**
2  * Copyright (c) 2003-2006, David A. Czarnecki
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions are met:
7  *
8  * Redistributions of source code must retain the above copyright notice, this list of conditions and the
9  * following disclaimer.
10  * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the
11  * following disclaimer in the documentation and/or other materials provided with the distribution.
12  * Neither the name of "David A. Czarnecki" and "blojsom" nor the names of its contributors may be used to
13  * endorse or promote products derived from this software without specific prior written permission.
14  * Products derived from this software may not be called "blojsom", nor may "blojsom" appear in their name,
15  * without prior written permission of David A. Czarnecki.
16  *
17  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
18  * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
19  * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
20  * AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
21  * EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
22  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
23  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
24  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
26  * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
27  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
28  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
29  * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30  */

31 package org.blojsom.plugin.security;
32
33 import org.apache.commons.codec.binary.Base64;
34 import org.blojsom.authorization.AuthorizationException;
35 import org.blojsom.authorization.AuthorizationProvider;
36 import org.blojsom.blog.Blog;
37 import org.blojsom.blog.Entry;
38 import org.blojsom.plugin.PluginException;
39 import org.blojsom.plugin.admin.BaseAdminPlugin;
40 import org.blojsom.util.BlojsomConstants;
41
42 import javax.servlet.http.HttpServletRequest JavaDoc;
43 import javax.servlet.http.HttpServletResponse JavaDoc;
44 import java.io.UnsupportedEncodingException JavaDoc;
45 import java.text.MessageFormat JavaDoc;
46 import java.util.Map JavaDoc;
47
48 /**
49  * Basic Authentication plugin performs a BASIC authorization check so that users much authenticate
50  * before they are able to see any blog entries.
51  *
52  * @author David Czarnecki
53  * @version $Id: BasicAuthenticationPlugin.java,v 1.2 2006/03/20 22:50:58 czarneckid Exp $
54  * @since blojsom 3.0
55  */

56 public class BasicAuthenticationPlugin extends BaseAdminPlugin {
57
58     private static final String JavaDoc AUTHORIZATION_HEADER = "Authorization";
59     private static final String JavaDoc WWW_AUTHENTICATE_HEADER = "WWW-Authenticate";
60     private static final String JavaDoc BASIC_REALM_HEADER = "Basic realm=\"{0}\"";
61     private static final String JavaDoc FAILED_AUTHORIZATION_PAGE = "/org/blojsom/plugin/security/templates/failed-authorization";
62
63     private AuthorizationProvider _authorizationProvider;
64
65     /**
66      * Construct a new instance of the Basic Authentication plugin
67      */

68     public BasicAuthenticationPlugin() {
69     }
70
71    /**
72      * Set the {@link AuthorizationProvider}
73      *
74      * @param authorizationProvider {@link AuthorizationProvider}
75      */

76     public void setAuthorizationProvider(AuthorizationProvider authorizationProvider) {
77         _authorizationProvider = authorizationProvider;
78     }
79
80     /**
81      * Set the appropriate headers for BASIC authentication
82      *
83      * @param httpServletResponse Response
84      * @param blog {@link Blog}
85      */

86     protected void setAuthenticationRequired(HttpServletResponse JavaDoc httpServletResponse, Blog blog) {
87         httpServletResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
88         httpServletResponse.setHeader(WWW_AUTHENTICATE_HEADER, MessageFormat.format(BASIC_REALM_HEADER, new String JavaDoc[]{blog.getBlogName()}));
89     }
90
91     /**
92      * Decode the BASIC authentication credentials and check the username/password against
93      * the authorized users for the blog.
94      *
95      * @param httpServletRequest Request
96      * @param blog {@link Blog}
97      * @return <code>true</code> if the BASIC authentication credentials are available and pass authentication,
98      * <code>false</code> otherwise
99      */

100     protected boolean decodeCredentialsAndAuthenticate(HttpServletRequest JavaDoc httpServletRequest, Blog blog) {
101         String JavaDoc authorization = httpServletRequest.getHeader(AUTHORIZATION_HEADER);
102         if (authorization != null) {
103             String JavaDoc encodedCredentials = authorization.substring(6).trim();
104
105             try {
106                 String JavaDoc usernameAndPassword = new String JavaDoc(Base64.decodeBase64(encodedCredentials.getBytes(BlojsomConstants.UTF8)));
107                 int colonIndex = usernameAndPassword.indexOf(":");
108                 if (colonIndex > 0) {
109                     String JavaDoc username = usernameAndPassword.substring(0, colonIndex);
110                     String JavaDoc password = usernameAndPassword.substring(colonIndex + 1);
111
112                     try {
113                         _authorizationProvider.authorize(blog, null, username, password);
114
115                         return true;
116                     } catch (AuthorizationException e) {
117                         if (_logger.isErrorEnabled()) {
118                             _logger.error(e);
119                         }
120
121                         return false;
122                     }
123                 }
124             } catch (UnsupportedEncodingException JavaDoc e) {
125                 if (_logger.isErrorEnabled()) {
126                     _logger.error(e);
127                 }
128
129                 return false;
130             }
131         }
132
133         return false;
134     }
135
136     /**
137      * Process the blog entries
138      *
139      * @param httpServletRequest Request
140      * @param httpServletResponse Response
141      * @param blog {@link Blog} instance
142      * @param context Context
143      * @param entries Blog entries retrieved for the particular request
144      * @return Modified set of blog entries
145      * @throws PluginException If there is an error processing the blog entries
146      */

147     public Entry[] process(HttpServletRequest JavaDoc httpServletRequest, HttpServletResponse JavaDoc httpServletResponse, Blog blog, Map JavaDoc context, Entry[] entries) throws PluginException {
148         if (!decodeCredentialsAndAuthenticate(httpServletRequest, blog)) {
149             setAuthenticationRequired(httpServletResponse, blog);
150
151             httpServletRequest.setAttribute(BlojsomConstants.PAGE_PARAM, FAILED_AUTHORIZATION_PAGE);
152             
153             return new Entry[0];
154         }
155
156         return entries;
157     }
158
159     /**
160      * Perform any cleanup for the plugin. Called after {@link #process}.
161      *
162      * @throws org.blojsom.plugin.PluginException
163      * If there is an error performing cleanup for this plugin
164      */

165     public void cleanup() throws PluginException {
166     }
167
168     /**
169      * Called when BlojsomServlet is taken out of service
170      *
171      * @throws org.blojsom.plugin.PluginException
172      * If there is an error in finalizing this plugin
173      */

174     public void destroy() throws PluginException {
175     }
176 }
Popular Tags