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

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

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

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

reference from:

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

configure JDBCRealm JAAS for mysql and tomcat 7 with form based authentication--reference的更多相关文章

  1. 打包mysql、tomcat、jdk为一个软件

    打包mysql.tomcat.jdk为一个软件 博客分类: 成长中的点滴  . 我们在本地开发web应用的时候,直接在IDE里面就可以完成jdk.容器.数据库的配置和集成. 但是如果当我们把应用程序交 ...

  2. 微软云Linux服务器 Mysql、tomcat远程连接错误解决办法

    在微软云linux服务器成功配置好mysql.tomcat,通过外部链接却发现一直错误.Mysql 一直提示错误代码2003, tomcat连接一直提示EOF. 反复检查配置都无问题,最后得知是微软云 ...

  3. 性能测试二十六:环境部署之Mysql+Redis+Tomcat环境整合

    系统中使用了缓存+数据库,通用读取数据规则1.先从缓存读数据,如果有,直接返回数据:2.如果没有,去数据库中读,然后再插入到缓存中,再返回数据 Mysql+Redis+Tomcat环境整合 1.修改P ...

  4. Redis学习(1)--环境配置,安装JDK,MySQL,tomcat

    Linux上安装jdk,mysql,tomcat安装 rpm命令: 相当于Windows的安装/卸载程序.可以进行程序的安装,更新,卸载,查看. 本地程序安装:rpm -ivh 程序名 本地程序查看: ...

  5. 【JAVAWEB学习笔记】26_Linux基础:简介安装、常用命令和JDK、Mysql、Tomcat的安装

    Linux基础 学习目标 1.了解Linux的简介与安装 2.掌握Linux常用的命令 3.掌握Linux系统上JDK.Mysql.Tomcat的安装 一.Linux的简介 1.Linux的概述 Li ...

  6. linux下安装php报错configure: error: Cannot find MySQL header files under /usr/include/mysql.

    linux下安装php报错configure: error: Cannot find MySQL header files under /usr/include/mysql. 2013-03-04 1 ...

  7. 部署web服务器的配置——补充mysql和tomcat

    今天想到了关于mysql的一些配置,以后关于配置mysql和tomcat相关的内容也会补充在这里. tomcat: 1. 更改内存(要设置tomcat内存,解决内存溢出的问题):安装版tomcat,打 ...

  8. 解决mysql跟php不在同一台机器上,编译安装php服务报错问题:configure: error: Cannot find MySQL header files under /application/mysql.

    在编译安装php服务时报错: configure: error: Cannot find MySQL header files under /application/mysql. Note that ...

  9. mysqlnd cannot connect to MySQL 4.1+ using the old insecure authentication解决办法

    mysqlnd是个好东西.不仅可以提高与mysql数据库通信的效率,而且也可以方便的设置一些超时.如,连接超时,查询超时.但是,使用mysqlnd的时候,有个地方需要注意.就是服务端的密码格式不能使用 ...

随机推荐

  1. ubuntu下mysql安装与测试

    原文地址: http://www.cnblogs.com/zhuyp1015/p/3561470.html 注意:原文地址中,最后g++ 编译源代码时少了个字母.添上即可. ubuntu上安装mysq ...

  2. Spring 初学 1

    Spring是一个轻量级的框架,他有自己的MVC框架SpringMVC,在以往的Web项目中大多采用Structs2+hibernate+Spring的框架,Structs做web层,Hibernat ...

  3. Mac、Linux与Windows

    Mac本身是基于达尔文内核(Darwin内核),是苹果由UNIX改造的类UNIX,然后在这内核基础上搭建的图形界面 Linux确实是个好东西,你只需要一个键盘,一个显示器,一根网线,接入网络,便能做几 ...

  4. spm使用之三spm应用实例

    spm 的init实际上是调用了grunt这个工具来实现一些交互式的提问和数据的获取. 看看npm就知道, npm有个命令叫init, 就是一样的交互式提问获取你要创建的nodejs的模块信息. sp ...

  5. 【UVA1579】俄罗斯套娃 Matryoshka (动态规划)

    题目: 分析: 其实就是两个dp结合起来.第一个dp求区间[l,r]全部合并起来要用的最小次数,可以用区间[l,k]&[k+1,r]转移(l<=k<r).第二个dp求前i个娃娃分成 ...

  6. 大数A-B

    还没写过大数减法,今天比赛还WA了两次... #include<iostream> #include<string> using namespace std; void sub ...

  7. Linux Shell编程(28)——进程替换

    进程替换与命令替换很相似. 命令替换把一个命令的结果赋给一个变量,例如 dir_contents=`ls -al`或xref=$. 进程替换则是把一个进程的输出回馈给另一个进程 (换句话说,它把一个命 ...

  8. (转载)如何优化MySQL insert性能

    (转载)http://blog.csdn.net/tigernorth/article/details/8094277 对于一些数据量较大的系统,面临的问题除了是查询效率低下,还有一个很重要的问题就是 ...

  9. 前端程序员:月薪 5K 到 5 万,我干了啥

    高贵的前端程序猿们: 如何在前端开发这种高精尖的技术领域找到心仪的工作?实现在咖啡馆喝喝咖啡敲敲代码就能升职加薪.买房买车.迎娶白富美走上人生巅峰的职业梦想?这篇<进化论:从 0 到 100,前 ...

  10. codeforces --- 115A

    A. Party time limit per test 3 seconds memory limit per test 256 megabytes input standard input outp ...