1 package org.apache.jcs.utils.servlet;
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22 import java.io.IOException;
23
24 import javax.servlet.http.HttpServletRequest;
25 import javax.servlet.http.HttpServletResponse;
26
27 import org.apache.commons.logging.Log;
28 import org.apache.commons.logging.LogFactory;
29 import org.apache.jcs.utils.config.IUtilConstants;
30
31 import sun.misc.BASE64Decoder;
32
33 /***
34 * Used to perform basic http authentication.
35 */
36 public class BasicHttpAuthenticator
37 {
38 private final static Log log = LogFactory.getLog( BasicHttpAuthenticator.class );
39
40 /*** Contains the "WWW-Authenticate" http response header. */
41 private final String wwwAuthHeader;
42
43 /***
44 * @param jcs
45 * the jcs parameter used to specify the "WWW-Authenticate" http
46 * response header.
47 */
48 public BasicHttpAuthenticator( String jcs )
49 {
50 this.wwwAuthHeader = "BASIC jcs=\"" + jcs + "\"";
51 }
52
53 /***
54 * Authenticates the http <code>"Authorization"</code> header information.
55 * <p>
56 * @param req
57 * @param res
58 * @return boolean
59 */
60 public final boolean authenticate( HttpServletRequest req, HttpServletResponse res )
61 {
62 try
63 {
64 if ( !authorized( req.getHeader( "Authorization" ) ) )
65 {
66 res.setContentType( "text/html" );
67 res.setHeader( "WWW-Authenticate", wwwAuthHeader );
68 res.sendError( HttpServletResponse.SC_UNAUTHORIZED );
69 return false;
70 }
71 }
72 catch ( IOException ex )
73 {
74 log.warn( ex.getMessage() );
75 return false;
76 }
77 return true;
78 }
79
80 /***
81 * Returns true iff the given "Authorization" http request header contains
82 * authorized user id and password.
83 * <p>
84 * @param authHeader
85 * @return
86 * @throws IOException
87 */
88 private boolean authorized( String authHeader )
89 throws IOException
90 {
91 if ( authHeader == null || authHeader.length() < 9 )
92 {
93 return false;
94 }
95
96 String userpassEncoded = authHeader.substring( 6 );
97
98 BASE64Decoder dec = new BASE64Decoder();
99 String userpassDecoded = new String( dec.decodeBuffer( userpassEncoded ) );
100 int idx = userpassDecoded.indexOf( ':' );
101
102 if ( idx == -1 )
103 {
104 return false;
105 }
106 String userid = userpassDecoded.substring( 0, idx );
107 String password = userpassDecoded.substring( idx + 1 );
108
109 if ( userid.trim().length() <= 0 || password.trim().length() <= 0 )
110 {
111 return false;
112 }
113 return checkPassword( userid, password );
114 }
115
116 /***
117 * Default implementation of checking the password.
118 * <p>
119 * @param userid
120 * @param password
121 * @return true iff the given user id and password is valid.
122 */
123 protected boolean checkPassword( String userid, String password )
124 {
125 return userid.equalsIgnoreCase( IUtilConstants.ADMIN_USERID )
126 && password.equals( IUtilConstants.ADMIN_PASSWORD );
127 }
128 }