Struts2中利用filter、session實現安全訪問和身份認證
阿新 • • 發佈:2019-01-26
1、開發環境:
Eclipse軟體
JDK 1.7
Apach Tomcat 7
2、通過eclipse建立Dynamic Web Project後,匯入相應的Struts2 的jar檔案:
3、匯入jar包後,建立如下圖所示專案相應目錄:
許可權說明
(1) 根目錄(WebContent)下的資源,如:index.jsp和login.jsp,允許匿名訪問。
(2) Admin目錄下的admin.jsp只允許角色為”admin”的使用者訪問。 User目錄下的user.jsp只允許角色為”user”的使用者訪問
4、相應的jsp程式碼如下:
@index.jsp:
@login.jsp:<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!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 name="welcome" action="welcome" method="post"> <table> <tr> <td>welcome to you !</td> </tr> <tr> <td><input value="login" type="submit" /></td> </tr> </table> </form> </body> </html>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/"; %> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <base href="<%=basePath%>"> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> </head> <body> <form name="login" action="login" method="post"> <table> <tr> <td>使用者名稱</td> <td><input name="name" type="text" /></td> </tr> <tr> <td>密碼</td> <td><input name="password" type="password" /></td> </tr> <tr> <td></td> <td><input value="submit" type="submit" /></td> </tr> </table> </form> <%=path%> <%=request.getRequestURI()%> <%=request.getServletPath()%> </body> </html>
@user.jsp:
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!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> <% String user = (String) session.getAttribute("name"); String balance = (String) session.getAttribute("balance"); String address = (String) session.getAttribute("address"); String tel = (String) session.getAttribute("tel"); %> <form> <table> <tr> <td>使用者名稱:</td> <td><%=user %></td> </tr> <tr> <td>餘額:</td> <td><%=balance %></td> </tr> <tr> <td>住址:</td> <td><%=address %></td> </tr> <tr> <td>電話:</td> <td><%=tel %></td> </tr> </table> </form> </body> </html>
@admin.jsp:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!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>
<%
String user = (String) session.getAttribute("name");
String balance = (String) session.getAttribute("balance");
String address = (String) session.getAttribute("address");
String tel = (String) session.getAttribute("tel");
%>
<form>
<table>
<tr>
<td>使用者名稱:</td>
<td><%=user %></td>
</tr>
<tr>
<td>餘額:</td>
<td><%=balance %></td>
</tr>
<tr>
<td>住址:</td>
<td><%=address %></td>
</tr>
<tr>
<td>電話:</td>
<td><%=tel %></td>
</tr>
</table>
</form>
</body>
</html>
@建立用於登陸驗證類Login.java:
package com.axb.cheney.filter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.apache.struts2.interceptor.ServletRequestAware;
import com.opensymphony.xwork2.ActionSupport;
public class Login extends ActionSupport
implements ServletRequestAware
{
private static final long serialVersionUID = 1L;
private String name;
private String password;
private HttpServletRequest request;
public String pass()
{
HttpServletRequest req = this.request;
HttpSession session = req.getSession();
if ((this.name.equals("user1")) && (this.password.equals("password1"))) {
session.setAttribute("name", this.name);
session.setAttribute("balance", "10,000");
session.setAttribute("address", "廣東省深圳市福田區購物公園");
session.setAttribute("tel", "12665654856");
System.out.println("login:" + this.name);
return "user";
}if ((this.name.equals("admin")) && (this.password.equals("password2"))) {
session.setAttribute("name", this.name);
session.setAttribute("balance", "9,000");
session.setAttribute("address", "廣東省珠海市香洲區北理工");
session.setAttribute("tel", "14956569898");
System.out.println("login:" + this.name);
return "admin";
}
System.out.println("login: fail");
return "failure";
}
public String getName()
{
return this.name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return this.password;
}
public void setPassword(String password) {
this.password = password;
}
public HttpServletRequest getRequest() {
return this.request;
}
public void setServletRequest(HttpServletRequest request)
{
this.request = request;
}
}
@修改Struts.xml檔案:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
"http://struts.apache.org/dtds/struts-2.3.dtd">
<struts>
<constant name="struts.enable.DynamicMethodInvocation" value="false" />
<constant name="struts.devMode" value="true" />
<package name="default" namespace="/" extends="struts-default">
<default-action-ref name="index" />
<global-results>
<result name="error">/WEB-INF/error.jsp</result>
</global-results>
<action name="welcome">
<result>/login.jsp </result>
</action>
<action name="login" class="com.axb.cheney.filter.Login"
method="pass">
<result name="failure">/login.jsp </result>
<result name="user">/user/user.jsp </result>
<result name="admin">/admin/admin.jsp </result>
</action>
</package>
</struts>
@建立用於攔截驗證身份的UserAuthenticationFilter.java
package com.axb.cheney.filter;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
public class UserAuthenticationFilter
implements Filter
{
private static String LOGIN_PAGE = "/login.jsp";
public void destroy()
{
}
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException
{
HttpServletRequest req = (HttpServletRequest)request;
HttpServletResponse res = (HttpServletResponse)response;
String currentUrl = req.getServletPath();
HttpSession session = req.getSession();
System.out.println("UserAuthenticationFilter");
if (currentUrl.equals("")) currentUrl = currentUrl + "/";
if ((currentUrl.startsWith("/")) && (!currentUrl.startsWith("/login.jsp"))) {
String user = (String)session.getAttribute("name");
if (user == null) {
res.sendRedirect(req.getContextPath() + LOGIN_PAGE);
return;
}
if (!user.equals("user1")) {
session.removeAttribute("name");
res.sendRedirect(req.getContextPath() + LOGIN_PAGE);
return;
}
}
chain.doFilter(request, response);
}
public void init(FilterConfig arg0)
throws ServletException
{
}
}
@建立用於攔截驗證身份的AdminAuthenticationFilter.java
package com.axb.cheney.filter;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
public class AdminAuthenticationFilter
implements Filter
{
private static String LOGIN_PAGE = "/login.jsp";
public void destroy()
{
}
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException
{
HttpServletRequest req = (HttpServletRequest)request;
HttpServletResponse res = (HttpServletResponse)response;
String currentUrl = req.getServletPath();
HttpSession session = req.getSession();
System.out.println("AdminAuthenticationFilter");
if (currentUrl.equals("")) currentUrl = currentUrl + "/";
if ((currentUrl.startsWith("/")) && (!currentUrl.startsWith("/login.jsp"))) {
String user = (String)session.getAttribute("name");
if (user == null) {
res.sendRedirect(req.getContextPath() + LOGIN_PAGE);
return;
}
if (!user.equals("admin")) {
session.removeAttribute("name");
res.sendRedirect(req.getContextPath() + LOGIN_PAGE);
return;
}
}
chain.doFilter(request, response);
}
public void init(FilterConfig arg0)
throws ServletException
{
}
}
@最後配置web.xml檔案用於過濾admin和user目錄下的資源訪問
<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_9" version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<display-name>SAML</display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<filter>
<filter-name>struts2</filter-name>
<filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<filter>
<filter-name>UserAuthentication</filter-name>
<filter-class>com.axb.cheney.filter.UserAuthenticationFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>UserAuthentication</filter-name>
<url-pattern>/user/*</url-pattern>
</filter-mapping>
<filter>
<filter-name>AdminAuthentication</filter-name>
<filter-class>com.axb.cheney.filter.AdminAuthenticationFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>AdminAuthentication</filter-name>
<url-pattern>/admin/*</url-pattern>
</filter-mapping>
</web-app>
5、測試結果如下:
@當第一次執行tomcat時,頁面顯示index.jsp主介面,如圖1所示。
當點選頁面<login>按鈕,頁面將調轉到圖2所示使用者登陸頁面。
圖1
圖2
@當你想通過直接訪問user資源時,如圖3所示,輸入資源相應路徑時,訪問User子目錄的任何資源,
都將被UserAuthenticationFilter捕獲。UserAuthenticationFilter對請求進行驗證,檢查session中是否
有正確的登入資訊,是否有相應的許可權。如果通過了驗證,允許訪問,否則不允許訪問,向客戶端瀏
覽器返回login.jsp,讓使用者進行登入。
圖3
圖4
@當驗證正確時,頁面顯示請求的相應內容,如圖5所示
圖5