The password files? 密碼文件
在任何的安全配置中,首先你得告訴應用程序在哪里可以找到用戶名和密碼以及角色。你可以使用LDAP服務器和數據庫服務器來存儲這類的信息。最簡單的情況是在應用的classpath中使用簡單的文本文件。下面是一個user.properties文件,它存儲的是用戶和密碼對。在這個例子中有兩個賬號分別為admin和user.
admin=jboss
user=ejb3
下面是一個roles.properties文件。它存儲了用戶和角色之間的關系。每一個用戶都可以擁有多個角色。比如用戶admin就同時擁有AdminUser和RegularUser兩種角色。
admin=AdminUser,RegularUser
user=RegularUser
The sample application? 示例程序
?作為一個例子,讓我們試著做一個有密碼保護功能的投資計算器程序。為了使用這個計算器,你需要用user或者admin的身份登陸。我建議你此時還是使用user登陸(密碼是ejb3)
RegularUser可以使用計算器,只有AdminUser有權增加更多的funds和investor profiles。所以,如果使用user登陸并嘗試運行下面的兩個程序,你將遭遇安全異常。然后你可以試著以admin的身份再嘗試一遍(密碼是jboss)
?
Security annotations? 安全標注
?在EJB 3.0中, 你可以使用安全標注來指定在哪里可以找到密碼/角色的列表,并且還可以指定哪種角色的用戶允許訪問這個方法。在下面的例子中,@SecurityDomain("other")表示在當前classpath下的.properties文件 是用來認證(authentication)的。@RolesAllowed表示哪些角色可以訪問這種方法。用@PermitAll標注的方法則不受安全約束。
@SecurityDomain( " other " )
public ? class ?SecureCalculator? implements ?Calculator?{
??@RolesAllowed({ " AdminUser " })
?? public ? void ?addFund?(String?name,? double ?growthrate)?{
???? // ?


??}
??@RolesAllowed({ " AdminUser " })
?? public ? void ?addInvestor?(String?name,? int ?start,? int ?end)?{
???? // ?


??}
??@PermitAll
?? public ?Collection? < Fund > ?getFunds?()?{
???? // ?


??}
?? // ?


??@RolesAllowed({ " RegularUser " })
?? public ? double ?calculate?( int ?fundId,? int ?investorId,?
??????????????????????????????????????? double ?saving)?{
???? // ?


??}
}
The web layer configuration? web層的配置
?如果你是通過web頁面登陸到系統,你的身份則會被應用的web層捕獲,然后傳遞到EJB 3.0的中間層。你不得不配置web.xml文件來聲明哪些頁面受密碼保護以及這些頁面允許哪些角色訪問。下面就是web.xml文件的內容。
?? < display-name > EJB3Trail </ display-name >
?? < security-constraint >
?????? < web-resource-collection >
????????? < web-resource-name >
????????????The?Protected?Calculator
????????? </ web-resource-name >
????????? < url-pattern > services/security/addfund.jsp </ url-pattern >
????????? < url-pattern > services/security/addinvestor.jsp </ url-pattern >
????????? < url-pattern > services/security/calculator.jsp </ url-pattern >
?????? </ web-resource-collection >
?????? < auth-constraint >
????????? < role-name > AdminUser </ role-name >
????????? < role-name > RegularUser </ role-name >
?????? </ auth-constraint >
?????? < user-data-constraint >
????????? < transport-guarantee > NONE </ transport-guarantee >
?????? </ user-data-constraint >
??? </ security-constraint >
??? < security-role >
?????? < description > Authorized?to?access?everything. </ description >
?????? < role-name > AdminUser </ role-name >
??? </ security-role >
??? < security-role >
?????? < description > Authorized?to?limited?access. </ description >
?????? < role-name > RegularUser </ role-name >
??? </ security-role >
??? < login-config >
?????? < auth-method > FORM </ auth-method >
?????? < form-login-config >
????????? < form-login-page > security/login.html </ form-login-page >
????????? < form-error-page > security/loginFailed.html </ form-error-page >
?????? </ form-login-config >
??? </ login-config >
</ web-app >