Võ Văn Hải's blog

Chỉ có một điều tuyệt đối đó là mọi thứ đều tương đối…

Form-based security in servlet

Trong ví dụ này, tôi sẽ hướng dẫn các bạn cách thức secure 1 web application dựa trên kỵ thuật form-based, tức là chúng ta tự tạo 1 trang dành cho việc đăng nhập và dữ liệu đăng nhập thường thì sẽ được lưu giữ trong database.

Kỹ thuật này là kỹ thuật ay được dùng nhất trong các ứng dụng web bởi tính năng dễ quản lý người sử dụng và việc phân phát tài nguyên cũng dễ hơn.

Giả sử bạn có 1 database và trong đó có 1 bảng có tên users với 2 fields mang tên username và password. Ở đây tôi dùng MySQL là RDBMS. cấu trúc bảng như  sau:

formbased_secutiry_01

Nhập liệu vài mẫu tin và bạn chắc là nhớ 1 mẫu ti nhé. ví dụ tôi nhập username là “ty” va password la “men”.Sau đó chúng ta bắt đầu viết ứng dụng.

Cấu trúc project
formbased_secutiry_02

Các bước viết ứng dụng:

1. Tạo 1 Dynamic Web Project có tên Servlet_Security_FormBased, chọn Target Runtime là Tomcat.

2.  Tạo các trang html như sau:

– trang welcome.html có nội dung sau

<html>
<head>
<meta http-equiv=”Content-Type” content=”text/html; charset=UTF-8″>
<title>Demo of Form-based security</title>
</head>
<body>
<h1>Welcome to security areas</h1>
<h2>Come from:
<a href=”https://vovanhai.wordpress.com”&gt;
https://vovanhai.wordpress.com
</a>
</h2>
</body>
</html>

– trang logon.html có nội dung sau

<html>
<head>
<meta http-equiv=”Content-Type” content=”text/html; charset=UTF-8″>
<title>Logon</title>
</head>
<body>
<h2 align=”center”>
VUI LÒNG ĐĂNG NHẬP TRƯỚC KHI TRUY XUẤT
</h2>
<form action=”LogonProcess” method=”post”>
<table>
<tr>
<td>User Name:</td>
<td><input type=”text” name=”us”/> </td>
</tr>
<tr>
<td>Password:</td>
<td><input type=”password” name=”psw”/> </td>
</tr>
<tr>
<td><input type=”submit”/ value=”Logon”> </td>
<td><input type=”reset”/ value=”Reset”> </td>
</tr>
</table>
</form>
</body>
</html>

– trang error.html có nội dung sau

<html>
<head>
<meta http-equiv=”Content-Type” content=”text/html; charset=UTF-8″>
<title>Logon error</title>
</head>
<body>
<h1>Bạn đã không có quyền để truy xuất khu vực này.</h1>
</body>
</html>

3. Viết servlet xử lý. nội dung như sau:


package vovanhai.wordpress.com;

import java.io.IOException;

import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.ResultSet;

import java.sql.Statement;

import javax.servlet.RequestDispatcher;

import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

/**

* Servlet implementation class LogonProcess

*/

public class LogonProcess extends HttpServlet {

private static final long serialVersionUID = 1L;

/**

* @see HttpServlet#HttpServlet()

*/

public LogonProcess() {

super();

}

//Đoạn code này kiểm tra username và password có trùng khớp với dữ liệu trong csdl không

private boolean logon(String us,String psw){

boolean ret=false;

try {

Class.forName(“com.mysql.jdbc.Driver”);//đăng ký driver

String dburl=“jdbc:mysql://localhost/logondb?” +

“user=root&password=”;

Connection con=DriverManager.getConnection(dburl);//tạo connection

Statement st=con.createStatement();

ResultSet rs=st.executeQuery(“select * from users where username='”+us+

“‘ and password='”+psw+“‘”);//thực thi câu sql

if(rs.next())//nếu tồn tại thì return true

return true;

} catch (Exception e) {

e.printStackTrace();

}

return ret;

}

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

String us=request.getParameter(“us”);

String psw=request.getParameter(“psw”);

if(!logon(us,psw))

response.sendRedirect(“error.html”);

else{

RequestDispatcher rd=request.getRequestDispatcher(“welcome.html”);

rd.forward(request, response);

}

}

}

Lưu ý servlet ở đây chỉ có dùng doPost, không có doGet. Nếu bạn có doGet, thông tin đăng nhập của bạn sẽ hiển thị lên url.

3. Cấu hình application và security

<?xml version=”1.0″ encoding=”UTF-8″?>
<web-app xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance&#8221; xmlns=”http://java.sun.com/xml/ns/javaee&#8221; xmlns:web=”http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd&#8221; xsi:schemaLocation=”http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd&#8221; id=”WebApp_ID” version=”2.5″>
<display-name>Servlet_Security_FormBased</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
<login-config>
<auth-method>FORM</auth-method>
<form-login-config>
<form-login-page>/logon.html</form-login-page>
<form-error-page>/error.html</form-error-page>
</form-login-config>
</login-config>
<security-constraint>
<web-resource-collection>
<web-resource-name>Success</web-resource-name>
<url-pattern>/welcome.html</url-pattern>
<http-method>GET</http-method>
<http-method>POST</http-method>
</web-resource-collection>

<auth-constraint>
<role-name>manager</role-name>
</auth-constraint>

</security-constraint>
<security-role>
<role-name>manager</role-name>
</security-role>

<servlet>
<description></description>
<display-name>LogonProcess</display-name>
<servlet-name>LogonProcess</servlet-name>
<servlet-class>vovanhai.wordpress.com.LogonProcess</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>LogonProcess</servlet-name>
<url-pattern>/LogonProcess</url-pattern>
</servlet-mapping>
</web-app>

Chúng ta lưu ý các element:

<login-config>
<auth-method>FORM</auth-method>
<form-login-config>
<form-login-page>/logon.html</form-login-page>
<form-error-page>/error.html</form-error-page>
</form-login-config>
</login-config>

chỉ định authentication model là FORM, và chúng ta phải chỉ định form đăng nhập của chúng ta là form nào, form nếu bị lỗi đăng nhập là form nào.

Element  <security-constraint> để chỉ định tài nguyên nào được hạn chế truy cập.

4. Triển khai

Sau khi triển khai, vào url http://localhost:8080/Servlet_Security_FormBased/welcome.html chúng ta sẽ được chuyển sang trang logon do đây là tài nguyên cần bảo vệ, giao diện như sau:
formbased_secutiry_03

Nếu việc đăng nhập là sai thì kết quả như sau:
formbased_secutiry_04
Nếu việc đăng nhập OK thì kết quả như sau:
formbased_secutiry_05

Chúc các bạn thành công!

6 Responses to “Form-based security in servlet”

  1. khoa said

    Chao Thay
    Thay co bai nao chi login bang cach su dung Tomcat ko a? em cam on tha, neu co thay email cho e nha.
    Tuc la project co trang login, ma minh thao tac qua tomcat;
    Giong nhu bai tren, neu thanh cong thi vao trang success, neu that bai thi chuyen qua trang fail

  2. LyLy said

    Thầy ơi, e muốn làm một bài tập về jsp. Thầy có bài nào demo ko ah?
    Bài tập của e yêu cầu phải login/logout
    Admin có các chức năng: manage user profile of employee, manage users, assign user’s role, manage Roles.
    Manager: Manage Employees.
    Nếu có thầy up luôn đc ko ah>
    E cảm ơn thầy ah.

  3. hoalong said

    thầy ơi cho em hỏi: em đang học java với xml.thầy có ví dụ nào cho em xin.thầy có broject nào lấy tài liệu từ database ghi ra file xml sau đó chuyển qua file pdf hoậc file nào bất kỳ cũng được.cảm ơn thầy!!!!!!
    thầy có thể gửi qua địa chỉ này

  4. hishigi said

    Thưa thầy cho em hỏi nếu sau khi login thành công mà muốn cho nó ko hiện ra cái welcome mà nó hiện ra 1 servlet mình đã viết thì làm như nào ạ? Các bạn ai biết trả lợi hộ mình với nha

  5. Nguyễn Anh Tuấn said

    Thưa thầy, e muốn gắn cờ vào đâu đó để khi truy cập các trang mà yêu cầu phải login thì trang đó sẽ check cờ là đăng nhập hay chưa, nếu rồi thì cho làm việc, còn không thì redirect về trang login.
    Thầy có thể cho e biết scope nào sẽ lưu cờ đó không ạ?

  6. Võ Văn Hải said

    làm việc với session!

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.