4. JAASRealm + FORM認證
- Accesses authentication information through the Java Authentication & Authorization Service (JAAS) framework.
- 通過實現JAAS(JSR196標準)的服務,獲取認證信息
4.1 創建Realm所需的數據表
mysql -uroot -p < security.sql
4.2 配置JAASRealm
$CATALINA_BASE/conf/server.xml
<Context docBase="security-rest" ……>
<Realm className="org.apache.catalina.realm.JAASRealm"
appName="RestJaasRealm"
roleClassNames="com.example.jaas.RestRolePrincipal"
userClassNames="com.example.jaas.RestUserPrincipal"/>
</Context>
Realm定義在context中,否則會導致roleClassNames和userClassNames中定義的類找不到。appName定義的名字和restJaas.conf中定義的須一致。
4.3 JAAS配置文件
/security-rest/src/main/resources/restJaas.conf
RestJaasRealm{
com.example.jaas.RestLoginModule required;
};
第二參數取值和含義
- Required 該模塊必須認證用戶,如果認證失敗,使用其它登錄模塊認證
- Requisite 如果認證失敗,將終止認證
- Sufficient 如果認證成功,即獲得登錄認證;如果認證失敗,使用其它登錄模塊認證
- Optional 認證將繼續下去,即使該模塊認證成功
4.4 JAAS實現類
jax-rs2-guide\sample\6\security-rest\src\main\java\com\example\jaas>ls -l
- LoginModule實現類:RestLoginModule.java
- LoginModule實現類的數據庫操作類:RestLoginDao.java
- Role接口POJO類:RestRolePrincipal.java
- User接口POJO類:RestUserPrincipal.java
4.5 配置JVM啓動參數
-Djava.security.auth.login.config="D:\+aries\github\jax-rs2-guide\sample\6\security-rest\src\main\resources\restJaas.conf"
4.6 數據庫驅動
$CATALINA_HOME/lib
M2_REPO/mysql/mysql-connector-java/5.1.25/mysql-connector-java-5.1.25.jar
4.7 配置應用的web.xml
/security-rest/src/main/webapp/WEB-INF/web.xml
<security-constraint>
<web-resource-collection>
<url-pattern>/*</url-pattern>
<http-method>GET</http-method>
<http-method>POST</http-method>
<http-method>UPDATE</http-method>
<http-method>DELETE</http-method>
</web-resource-collection>
<web-resource-collection>
<url-pattern>/webapi/*</url-pattern>
<http-method>GET</http-method>
<http-method>POST</http-method>
<http-method>UPDATE</http-method>
<http-method>DELETE</http-method>
</web-resource-collection>
<auth-constraint>
<role-name>admin</role-name>
</auth-constraint>
</security-constraint>
<security-constraint>
<web-resource-collection>
<url-pattern>/*</url-pattern>
<http-method>GET</http-method>
</web-resource-collection>
<web-resource-collection>
<url-pattern>/webapi/*</url-pattern>
<http-method>GET</http-method>
</web-resource-collection>
<auth-constraint>
<role-name>user</role-name>
</auth-constraint>
</security-constraint>
<login-config>
<auth-method>FORM</auth-method>
<form-login-config>
<form-login-page>/login.html</form-login-page>
</form-login-config>
</login-config>
<welcome-file-list>
<welcome-file>/index.html</welcome-file>
</welcome-file-list>
4.8 登錄頁面
<form action="j_security_check">
<div>
<span>User Name</span>
<input id="j_username" name="j_username" type="text" />
</div>
<div style="margin-top:10px;margin-bottom:10px;">
<span>Pass Word</span>
<input id="j_password" name="j_password" type="password" />
</div>
<input type="submit" value="Sign In" />
</form>
4.9 JAAS流程
在JAASRealm.authenticate認證方法中,有兩個主要對象:
- CallbackHandler 持有登錄信息的回調
- LoginContext 通過配置文件感知LoginModule實現類的上下文
認證分爲兩個步驟: