Apache Shiro 配置 LDAP 驗證
通常在根據LDAP進行身份驗證時一般進行以下三步:
- 利用一個LDAP使用者的使用者名稱和密碼繫結到LDAP伺服器。
- 在LDAP中檢索一個使用者的條目,然後將提供的密碼和檢索到的LDAP記錄中進行驗證。
- 根據LDAP提供的記錄,再去本系統中查詢授權資訊。
Shiro 提供了DefaultLdapRealm
,只做了第二步,根據使用者的條目和密碼來驗證。並不能滿足我們的需求,所以肯定是要定製化LdapRealm。
這裡使用Spring Ldap 來簡化Ldap操作
public class LdapRealm extends AuthorizingRealm { private static final Logger logger = LoggerFactory.getLogger(LdapRealm.class); private LdapTemplate ldapTemplate; @Autowired private UserService userService; @Autowired private RoleService roleService; @Autowired private MenuService menuService; @Override protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException { String username = (String) token.getPrincipal(); String password = new String((char[]) token.getCredentials()); try { LdapQuery ldapQuery = LdapQueryBuilder.query().base("DC=example,DC=com").searchScope(SearchScope.SUBTREE) .filter("(sAMAccountName={0})", username); boolean authResult = ldapTemplate.authenticate(ldapQuery.base(), ldapQuery.filter().encode(), password); if (!authResult) { logger.debug("ldap authentication for {} failed", username); return null; } User ldapUser = (User) ldapTemplate.searchForObject(ldapQuery, new LdapUserAttrMapper()); User user = userService.selectUserById(ldapUser.getUserId()); if (user == null) { // 使用者名稱不存在丟擲異常 throw new UnknownAccountException(); } if (user.getRemoveFlag()) { // 使用者被管理員鎖定丟擲異常 throw new LockedAccountException(); } SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(user, token.getCredentials(), "LdapRealm"); return authenticationInfo; } catch (Exception e) { logger.error("ldap authentication failed", e.toString()); return null; } } @Override protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) { Long userId = ShiroUtils.getUserId(); SimpleAuthorizationInfo info = new SimpleAuthorizationInfo(); // 角色加入AuthorizationInfo認證物件 info.setRoles(roleService.selectRoleKeys(userId)); // 許可權加入AuthorizationInfo認證物件 info.setStringPermissions(menuService.selectPermsByUserId(userId)); return info; } public LdapTemplate getLdapTemplate() { return ldapTemplate; } public void setLdapTemplate(LdapTemplate ldapTemplate) { this.ldapTemplate = ldapTemplate; } }
關鍵的程式碼如下,驗證使用者和獲取LDAP使用者資訊
LdapQuery ldapQuery = LdapQueryBuilder.query().base("DC=example,DC=com").searchScope(SearchScope.SUBTREE) .filter("(sAMAccountName={0})", username); boolean authResult = ldapTemplate.authenticate(ldapQuery.base(), ldapQuery.filter().encode(), password); User ldapUser = (User) ldapTemplate.searchForObject(ldapQuery, new LdapUserAttrMapper());
Spring 的 ldap 配置如下:
<bean id="ldapContextSource" class="org.springframework.ldap.core.support.LdapContextSource"> <property name="url" value="ldap://192.168.100.1:3268"/> <property name="userDn" value="CN=Reader"/> <property name="password" value="secret"/> </bean> <bean id="ldapTemplate" class="org.springframework.ldap.core.LdapTemplate"> <property name="contextSource" ref="ldapContextSource"/> </bean> <bean id="ldapRealm" class="com.example.shiro.LdapRealm"> <property name="ldapTemplate" ref="ldapTemplate"/> </bean>