Monday, January 10, 2011

Basic Authentication (Tomcat & MySQL)

This method is using database as storage of user list and its roles.

1. Create a free trial account at EATJ hosting http://www.eatj.com/.
2. Login to your EATJ account and click MySQL Admin 4.1.
CREATE TABLE IF NOT EXISTS `user_auth` (
`USERNAME` varchar(30) NOT NULL default '',
`PASSWORD` varchar(30) NOT NULL default '',
PRIMARY KEY (`USERNAME`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1;

INSERT INTO `user_auth` (`USERNAME`, `PASSWORD`) VALUES
('hello', 'world');

CREATE TABLE IF NOT EXISTS `user_role` (
`ROLE_NAME` varchar(30) NOT NULL,
`USERNAME` varchar(30) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;

INSERT INTO `user_role` (`ROLE_NAME`, `USERNAME`) VALUES
('tomcat', 'hello'),
('manager', 'admin'),
('admin', 'admin');


3. Login to your EATJ ftp account, In conf/service.xml, Comment out <!--<Realm className="org.apache.catalina.realm.UserDatabaseRealm"
resourceName="UserDatabase"/>-->
Add:
<Realm className="org.apache.catalina.realm.JDBCRealm"
driverName="com.mysql.jdbc.Driver"
connectionURL="jdbc:mysql://localhost/<Your EATJ username>"
connectionName="<Your EATJ username>"
connectionPassword="<Your EATJ password>"
userTable="user_auth"
userNameCol="USERNAME"
userCredCol="PASSWORD"
userRoleTable="user_role"
roleNameCol="ROLE_NAME" />

4. In webapps/ROOT/WEB-INF/web.xml,
<!--Access Configuration based on Realms-->
<security-constraint>
<web-resource-collection>
<web-resource-name>All Page</web-resource-name>
<url-pattern>/*</url-pattern>
</web-resource-collection>
<auth-constraint>
<role-name>tomcat
</auth-constraint>
</security-constraint>

<login-config>
<auth-method>BASIC</auth-method>
<Realm-name>Tomcat-Advance-Authentication-Realm</Realm-name>
</login-config>


<web-apps>

5. Test it.

More tutorials: http://jsptutorblog.blogspot.com/