淺談 Tomcat 身份認證機制 - Basic 認證方式
在上一篇「淺談 Tomcat 身份認證機制 - 認證機制的基本元素」中, 已經先稍微介紹了所需要的基本元素, 因此在這篇我們就使用這個基本元素來看 Tomcat 所以提供的幾種認證方式. 目前 Tomcat 總共提供了下列幾種的認證方式:
- HTTP Basic Authentication
- HTTP Digest Authentication
- Form Based Authentication
- HTTPS Client Authentication
首先為了讓整個程式單純化, 這邊的認證 repository 使用 MemoryRealm. (其他還有 UserDatabaseRealm, JDBCRealm) MemoryRealm 會去讀取 $CATALINA_HOME/conf/tomcat-users.xml 檔案, 並且把帳號資料存到 memory 中.
tomcat-users.xml 的格式會類似底下的 XML:
<?xml version="1.0" encoding='utf-8'?>
<tomcat-users>
<role rolename="tomcat"/>
<role rolename="role1"/>
<role rolename="manager"/>
<user username="tomcat" password="tomcat" roles="tomcat" />
<user username="role1" password="tomcat" roles="role1" />
<user username="both" password="tomcat" roles="tomcat,role1" />
<user username="manager" password="manager" roles="manager"/>
</tomcat-users>
上面的結構跟之前的 User - UserRoles - Roles 的 ER Model 是非常類似的. 上述的 XML 定義了 tomcat , role1 以及 manager 三種 roles, 以及 tomcat, role1, both, manager四個 user, 以及其 password 跟個別所屬的 role.
接著需要設定 Web Application 關於 security constraint 的部份. 在 WEB-INF 目錄下的 web.xml 檔案, 需要加入底下的 XML:
<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>BASIC</auth-method>
<realm-name>Basic Authentication</realm-name>
</login-config>
url-pattern 定義了所需要被管制權限的檔案. 以這個例子就是所有的 jsp 檔案. role-name 定義了那些 role 可以使用該區域的 jsp 檔案. login-config 裡面的 auth-mothod 定義了該 web application 要使用 basic 的認證方式. 當把上述內容都設定好之後, 重新 restart tomcat, 當你去 access 該 web application 下的 jsp 檔案, 會跳出一個視窗要你輸入帳號密碼:

輸入 manager/manager 即可進入. 若是輸入的是其他 role 的帳號, 則會無法進入該 web application.
沒有留言:
張貼留言