首页 > 代码库 > configure JDBCRealm JAAS for mysql and tomcat 7 with form based authentication--reference

configure JDBCRealm JAAS for mysql and tomcat 7 with form based authentication--reference

Hello all,

In this tutorial we are going to configure JDBCRealm JAAS for tomcat 7 and mysql database server.

Let us first understand what exactly these terminologies mean.

JAAS : Java Authentication and Authorization Service is used for user authentication. This provides separation of concerns for user authentication so that they are managed independently

JDBCRealm: We can say this is used to look for users in provided relational database. All the user credentials will be retrieved by tomcat using JDBCRealm.

Form based authentication: This is a mechanism by which security is provided for web resources. If the user is authenticated, then resource will be served, otherwise it will lead to a login page where user can fill in login credentials and after successful login, the resource will be served.

We will follow these steps for configuration

1. Prepare database for user credentials and roles

2. Configure tomcat 7 server for JDBCRealm with our database

3. Create a web application in eclipse

4. Configure security for the resources which we want to protect in our web application

5. Run example

1. Prepare database:

Copy paste the following sql script and run from mysql command prompt

 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
CREATE DATABASE tutorialsdb;
 
DROP DATABASE IF EXISTS tutorialsdb;
CREATE DATABASE tutorialsdb;
USE tutorialsdb;
CREATE TABLE users (
username varchar(20) NOT NULL PRIMARY KEY,
password varchar(20) NOT NULL
);
CREATE TABLE roles (
rolename varchar(20) NOT NULL PRIMARY KEY
);
CREATE TABLE users_roles (
username varchar(20) NOT NULL,
rolename varchar(20) NOT NULL,
PRIMARY KEY (username, rolename),
CONSTRAINT users_roles_fk1 FOREIGN KEY (username) REFERENCES users (username),
CONSTRAINT users_roles_fk2 FOREIGN KEY (rolename) REFERENCES roles (rolename)
);
INSERT INTO `tutorialsdb`.`users` (`username`, `password`) VALUES (‘prasadkharkar‘, ‘password‘);
INSERT INTO `tutorialsdb`.`roles` (`rolename`) VALUES (‘user‘);
INSERT INTO `tutorialsdb`.`users_roles` (`username`, `rolename`) VALUES (‘prasadkharkar‘, ‘user‘);
COMMIT;

This will create the database and add data into it.

2. Configure tomcat 7 server.xml for JDBCRealm

Add a realm tag in tomcat_home/conf/server.xml file. Place mysql-connector-java.jar in tomcat_home/lib

 

 
1
2
3
4
5
6
7
8
9
10
<Realm  className="org.apache.catalina.realm.JDBCRealm"
driverName="com.mysql.jdbc.Driver"
connectionURL="jdbc:mysql://localhost:3306/tutorialsdb"
connectionName="root"
connectionPassword="root"
userTable="users"
userNameCol="username"
userCredCol="password"
userRoleTable="users_roles"
roleNameCol="rolename" />

 

3. Create a dynamic web project in eclipse.

Click File -> New -> Dynamic Web Project. Name it Tomcat7FormBasedJAAS. Also place mysql-connector-java.jar in WEB-INF/lib

Directory structure after creating project

Directory structure after creating project

4. Configure security for web application

Paste following content in web.xml

 

 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
    id="WebApp_ID" version="3.0">
    <display-name>Tomcat7FormBasedJAAS</display-name>
    <security-constraint>
        <web-resource-collection>
            <web-resource-name>secured</web-resource-name>
            <url-pattern>/protected/*</url-pattern>
        </web-resource-collection>
        <auth-constraint>
            <role-name>user</role-name>
        </auth-constraint>
    </security-constraint>
    <security-role>
        <role-name>user</role-name>
    </security-role>
    <login-config>
        <auth-method>FORM</auth-method>
        <form-login-config>
            <form-login-page>/login.jsp</form-login-page>
            <form-error-page>/login_failure.jsp</form-error-page>
        </form-login-config>
    </login-config>
 
</web-app>

 

Create protected.jsp in Webcontent/protected folder and paste following code in it.

 

 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
 
Hello <%= request.getUserPrincipal().getName().toString() %>
You are able to view this page because you are authenticated user.
 
</body>
</html>

 

Create login.jsp as follows

 

 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
 
    <form method=post action="j_security_check">
        <p>
            <span>Username:</span> <br /> <input type="text" name="j_username">
        </p>
        <p>
            <span>Password:</span> <br /> <input type="password"
                name="j_password">
        </p>
        <p>
            <input type="submit" value="Login">
        </p>
    </form>
 
 
</body>
</html>

 

Note that the names for username, password and action must be j_username, j_password and j_security_check. It means we are using JAAS

Create a page if user authentication fails. Name it login_failure.jsp

 

 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
 
You are not valid user
 
</body>
</html>

 

5. Run and test the application

Start tomcat 7 server and hit

 

 
1
http://localhost:8080/Tomcat7FormBasedJAAS/protected/protected.jsp

 

Now that we are trying to access a protected file based on url pattern, the container will take us to the login page as per our configuration in web.xml

The following page should be displayed when you hit above url.

Login Page

Login Page

Now enter wrong credentials. say I enter username as prasadkharkar and password as 1234.

Now container will check whether these match the credentials specified in the database. If they don’t match it will redirect you to error page as follows

Login Error

Login Error

 

When you enter correct credentials..i.e. username as “prasadkharkar” and password as “password”. Then you will be successfully redirected to the protected resource that you are trying to access because now you are a authenticated user.

Successful Login

Successful Login

reference from:

http://www.thejavageek.com/2013/07/07/configure-jdbcrealm-jaas-for-mysql-and-tomcat-7-with-form-based-authentication/