2015-12-26 36 views
1

在我的Java EE應用程序中,我通過JDBC領域實施了身份驗證/自動化(第一次應用此解決方案)。使用JDBC領域進行身份驗證

以下代碼在成功登錄時沒有任何問題,問題是當我鍵入錯誤的憑據時:無論如何它都會登錄,即使它捕獲到ServletException(登錄失敗),這些代碼行也不會執行在調試模式下):

request.setAttribute(「msg」,「Login in error」);

nextPage =「/errorPage.jsp」;

另一個奇怪的事情:無論什麼我傳遞給

getServletContext()方法的getRequestDispatcher(下一頁)的.forward(請求,響應 );

as nextPage(我試圖把靜態的「/errorPage.jsp」),它總是轉發到index.jsp。

的Login.jsp

@WebServlet("/Login") 
    public class Login extends HttpServlet { 
     private static final long serialVersionUID = 1L; 

/** 
* @see HttpServlet#HttpServlet() 
*/ 
public Login() { 
    super(); 
    // TODO Auto-generated constructor stub 
} 

/** 
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) 
*/ 
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 
    // TODO Auto-generated method stub 
} 

/** 
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) 
*/ 
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 

    String username = request.getParameter("username").trim(); 
    String password = request.getParameter("password").trim(); 
    String nextPage = "/index.jsp"; 

    try { 
     request.login(username, password); 
    } 
    catch (ServletException ex) { 
     request.setAttribute("msg", "Error in login"); 
     nextPage = "/errorPage.jsp"; 
    } 

     getServletContext().getRequestDispatcher(nextPage).forward(request, response); 
    } 
} 

的login.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" 
    pageEncoding="UTF-8"%> 
<% 
    request.logout(); 
%> 
<!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=UTF-8"> 
<title>Welcome</title> 
</head> 
<body> 
    <h1>Hi! You need to login.</h1> 
    <form method="POST" action="/MyApp/Login"> 
     Usuario: <input type="text" name="username" /> Password: <input 
      type="password" name="password" /> <input type="submit" 
      value="Send" /> 
    </form> 
</body> 
</html> 

的web.xml

<?xml version="1.0" encoding="UTF-8"?> 
<web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" 
    version="3.0"> 
    <display-name>MyApp</display-name> 
    <welcome-file-list> 
     <welcome-file>login.jsp</welcome-file> 
    </welcome-file-list> 
    <login-config> 
     <auth-method>FORM</auth-method> 
     <realm-name>jdbcRealm</realm-name> 
     <form-login-config> 
      <form-login-page>/login.jsp</form-login-page> 
      <form-error-page>/errorPage.jsp</form-error-page> 
     </form-login-config> 
    </login-config> 
    <security-constraint> 
     <web-resource-collection> 
      <web-resource-name>Admin stuff</web-resource-name> 
      <url-pattern>/admin/*</url-pattern> 
      <http-method>GET</http-method> 
      <http-method>POST</http-method> 
     </web-resource-collection> 
     <auth-constraint> 
      <role-name>admin</role-name> 
     </auth-constraint> 
     <user-data-constraint> 
      <transport-guarantee>CONFIDENTIAL</transport-guarantee> 
     </user-data-constraint> 
    </security-constraint> 
    <security-constraint> 
     <web-resource-collection> 
      <web-resource-name>User stuff</web-resource-name> 
      <url-pattern>/user/*</url-pattern> 
      <http-method>GET</http-method> 
      <http-method>POST</http-method> 
     </web-resource-collection> 
     <auth-constraint> 
      <role-name>user</role-name> 
     </auth-constraint> 
     <user-data-constraint> 
      <transport-guarantee>CONFIDENTIAL</transport-guarantee> 
     </user-data-constraint> 
    </security-constraint> 
    <security-role> 
     <role-name>admin</role-name> 
    </security-role> 
    <security-role> 
     <role-name>user</role-name> 
    </security-role> 
</web-app> 

在此之前,我試過container-managed security溶液(與登錄的表單動作調用j_security_check組件)。

登錄正常工作與此(即使有錯誤的憑證),但我得到了另一個嚴重的問題之前,我沒有:在一個用例,用戶可以看到該項目正在開發,但它不應該能夠看到其他用戶的項目。我用下面的servlet實現了它,但問題在於(像其他解決方案一樣),它跳過了一些指令(例如,在數據庫中查找用戶的指令),並且出現異常,重定向到錯誤頁。

public class ViewUserProjects extends HttpServlet { 
    private static final long serialVersionUID = 1L; 

    public ViewUserProjects() { 
     super(); 
     // TODO Auto-generated constructor stub 
    } 

    protected void doGet(HttpServletRequest request, 
      HttpServletResponse response) throws ServletException, IOException { 
     DAO dao = (DAO) getServletContext().getAttribute("bd"); 

     Principal p = request.getUserPrincipal(); 
     String username = p.getName(); 

     try { 
      User user = dao.getUserByName(name); 
      request.getSession().setAttribute("user", user); 

      ArrayList<Project> projects = new ArrayList<Project>(); 

      tareas = ad.getUserProjects(Integer.parseInt(user.getId())); 

      request.setAttribute("projects", projects); 

      getServletContext().getRequestDispatcher(
        "/user/viewProjects.jsp").forward(request, 
          response); 
     } catch (Exception ex) { 
      request.setAttribute("msg", 
        "Error"); 
      getServletContext().getRequestDispatcher("/errorPage.jsp").forward(
        request, response); 
     } 
    } 

    protected void doPost(HttpServletRequest request, 
      HttpServletResponse response) throws ServletException, IOException { 
     // TODO Auto-generated method stub 
    } 

} 

回答

-1

你在哪裏檢查從表單輸入中輸入的用戶名和密碼是否正確。您是通過查詢數據庫進行身份驗證還是通過匹配代碼中設置的用戶名和密碼值進行身份驗證?我相信這會給你一個線索。確保來自表單輸入的用戶名和密碼與代碼中設置的用戶名和密碼相匹配。讓我知道你是否有其他問題。如果這個解決您的問題,請把它標記爲正確答案

response.setContentType("text/html"); 
    String msg = " "; 

    String username = request.getParameter("username"); 
    String password = request.getParameter("password"); 
    try { 

if (username.equals("nick") && password.equals("nick_password")) { 


      nextPage = "HELLO" + username + "! Your login is SUCESSFULL"; 

     } else { 
      nextPage = "HELLO" + username + "!Your login is UNSUCESSFULL"; 
     } 

}// close try 
+0

認證在通過JDBC領域https://docs.oracle.com/javaee/6/tutorial/doc/glxgo.html – user3673449

1

當使用JDBCRealm,它是一個更好的做法是使用container-managed security應用authentication/authorization而不是從你的應用程序代碼中處理這個(你正在做的)

所以我們允許服務器來處理這個問題,這意味着使用form-based authentication(您正在使用)按照Servlet Specification會是這樣的:

一是形式:

<form action="j_security_check" method="POST"> 
    Username:<input type="text" name="j_username" placeholder="Username" /> 
    Password:<input type="password" name="j_password" placeholder="Password" /> 
    <input type="submit" value="Log In" /> 
</form> 

那麼在我們Deployment Descriptor我們必須添加一些配置,你似乎已經有,但這裏是另一個例子:

注意我相信你mising在這裏我們使用了403錯誤* <error-page>標籤這是Forbidden resource

<security-constraint> 
    <display-name>securityConstraint1</display-name> 
    <web-resource-collection> 
     <web-resource-name>resources</web-resource-name> 
     <description /> 
     <url-pattern>/protected/*</url-pattern> 
    </web-resource-collection> 
    <auth-constraint> 
     <role-name>appUser</role-name> 
     <role-name>appAdmin</role-name> 
    </auth-constraint> 
</security-constraint> 

<security-constraint> 
    <display-name>securityConstraint2</display-name> 
    <web-resource-collection> 
     <web-resource-name>resources</web-resource-name> 
     <description /> 
     <url-pattern>/protected/admni/*</url-pattern> 
    </web-resource-collection> 
    <auth-constraint> 
     <role-name>appAdmin</role-name> 
    </auth-constraint> 
</security-constraint> 

<login-config> 
    <auth-method>FORM</auth-method> 
    <realm-name>appRealm</realm-name> 
    <form-login-config> 
     <form-login-page>/index.xhtml</form-login-page> 
     <form-error-page>/public/forbidden.xhtml</form-error-page> 
    </form-login-config> 
</login-config> 

<security-role> 
    <role-name>appUser</role-name> 
</security-role> 

<security-role> 
    <role-name>appAdmin</role-name> 
</security-role> 

<error-page> 
    <error-code>403</error-code> 
    <location>/public/forbidden.xhtml</location> 
</error-page> 

我們不能忘了Data Protection(你已經擁有):

<user-data-constraint> 
    <transport-guarantee>CONFIDENTIAL</transport-guarantee> 
</user-data-constraint> 

所以現在我們需要定義ROLES的應用,這是在定義的應用程序服務器所以首先映射組來完成。 ¿您正在使用哪個應用程序服務器?

下面是使用GlassFish

我們需要添加一個例子的glassfish-web.xmlsun-web.xml

<?xml version="1.0" encoding="UTF-8"?> 
<!DOCTYPE sun-web-app PUBLIC "-//Sun Microsystems, Inc.//DTD GlassFish Application Server 3.0 Servlet 3.0//EN" "http://www.sun.com/software/appserver/dtds/sun-web-app_3_0-0.dtd"> 
<sun-web-app error-url=""> 

    <security-role-mapping> 
     <role-name>appUser</role-name> 
     <group-name>1</group-name> 
    </security-role-mapping> 

    <security-role-mapping> 
     <role-name>appAdmin</role-name> 
     <group-name>2</group-name> 
    </security-role-mapping> 

    <class-loader delegate="true"/> 
    <jsp-config> 
    <property name="keepgenerated" value="true"> 
     <description>Keep a copy of the generated servlet class' java code.</description> 
    </property> 
    </jsp-config> 
</sun-web-app> 

所以角色被映射到存在於real repository實際組名。 (這是直接在你的應用服務器上創建的)。

爲了這個工作,我們需要在我們的DB中創建一個TABLE以定義用戶組。

Realm此處創建於Server Admin Console

GlassFish中去:

配置>>服務器配置>>安全>>三界

而這裏的境界配置的一個例子。

JDBCRealm

+0

謝謝您的回答來實現。在嘗試我發佈的解決方案之前,我先從你建議的那個開始。我用我遇到的問題更新了我的問題。 – user3673449

+0

您可以添加更多關於數據庫如何映射的細節,您如何配置jdbcRealm以及您正在使用哪個應用程序服務器? –

+0

此外,編輯的代碼似乎有點關閉,我沒有看到你正在使用'tareas'或'username',因爲你傳遞'dao.getUserByName(name)'我認爲有些代碼丟失了,你能請寫完整的代碼? –