淺談 Tomcat 身份認證機制 - Form 認證方式
在前面已經把 「Basic 認證方式」談完了, 接下來這邊要談的是最常使用到的 Form 認證方式. 一般我們在使用一些網路 Service 都會使用 Form-based 認證方式. 最常見的方式就是要你填入帳號, 密碼, 接著系統會確認你的資料是否正確. 若是正確則讓你登入系統, 若是有誤, 則回到原登入畫面讓你重新輸入帳號密碼.
在 Tomcat 裡面提供的 Form 認證方式, 需要 follow 一些它的 rule. 首先先更改 web.xml, 將認證方式更改為 FORM.
<security-constraint>
<display-name>Tomcat Server Configuration Security Constraint</display-name> <web-resource-collection>
<web-resource-name>Protected Area</web-resource-name>
<!-- Define the context-relative URL(s) to be protected -->
<url-pattern>*.jsp</url-pattern>
</web-resource-collection>
<auth-constraint>
<!-- Anyone with one of the listed roles may access this area -->
<role-name>manager</role-name>
</auth-constraint>
</security-constraint>
<login-config>
<auth-method>FORM</auth-method>
<realm-name>FORM Authentication Method</realm-name>
<form-login-config>
<form-login-page>/login.jsp</form-login-page>
<form-error-page>/error.jsp</form-error-page>
</form-login-config>
</login-config>
跟 BASIC 的認證方式類似, security-constraint 的部份同樣也是限制只有 manager role 的帳號才能夠 access jsp 檔案. 而 auth-method 則改成 FORM; 另外加入 form-login-config element. 包含了 form-login-page (登入的頁面位置) 以及 form-error-page (若是帳號輸入錯誤會導向到該頁面).
接著撰寫 login.jsp:
<form method="POST" action='<%= response.encodeURL("j_security_check") %>' name="loginForm">
User Name: <input type="text" name="j_username" size="16" id="username"/> <br/>
Password: <input type="password" name="j_password" size="16" id="password"/> <br/>
<input type="submit" value="login" />
</form>
如同上面所的到的, 這邊我們需要 follow tomcat 所定的一些規則. 首先是帳號的 name 必須是 j_username, 密碼的 name 必須是 j_password, 而 action 必須是 j_security_check.
(這邊若是有興趣可以去 trace tomcat source code: org.apache.catalina.realm 下面的檔案.)
底下是登入的畫面
底下是登入錯誤的頁面 (error.jsp)
沒有留言:
張貼留言