Weblogic迁移Jboss时从HttpServletRequest获取LDAP用户信息问题求解
错误原因
原有实现依赖Weblogic容器的私有API HttpSession.getInternalAttribute() 读取内部存储的LDAP认证用户信息,而JBoss底层采用Undertow Web容器,无对应私有方法,直接触发java.lang.NoSuchMethodException异常。
跨容器兼容实现方案
改用Java EE标准安全API获取认证用户信息,无需依赖各容器私有实现,和原有Weblogic逻辑完全对齐,修改后代码如下:
public static UserBean getUserFromSession(HttpServletRequest request) throws SessionExpiredException { try { Principal authUser = null; int attempts = 0; // 保留原有重试逻辑,适配LDAP认证延迟场景 while (authUser == null && attempts < 30) { // 标准API获取认证用户主体,兼容所有符合Java EE规范的容器 authUser = request.getUserPrincipal(); if (authUser == null) { attempts++; Thread.sleep(4000); } } if (authUser != null) { // 校验用户角色,用标准API比字符串匹配更准确可靠 if (!request.isUserInRole("MAD_Extr_PrivateChannels_Aut")) { Tools.addLogEntry("private_channel.log", "User does not have MAD_Extr_PrivateChannels_Aut role"); throw new Exception("Your user does not have a role assigned for Private Channel"); } ObjectMapper objectMapper = new ObjectMapper(); String authUserString = objectMapper.writeValueAsString(authUser); Tools.addLogEntry("private_channel.log", authUserString); if (!authUserString.contains("air")) { Tools.addLogEntry("private_channel.log", "User does not have air cn"); throw new Exception("Your user does not have an airline assigned"); } TypeReference<HashMap> typeRef = new TypeReference<HashMap>() {}; Map mapUser = objectMapper.readValue(authUserString, typeRef); String dn = mapUser.get("dn").toString(); Tools.addLogEntry("private_channel.log", "User dn: " + dn); String[] dnParts = dn.split(","); if (dnParts.length < 3) { Tools.addLogEntry("private_channel.log", "User does not have 3 parts in dn"); throw new Exception("Your user does not have an airline properly"); } UserBean response = new UserBean(); response.setAirlineCode(dnParts[2].replace("ou=", "").toUpperCase()); response.setUserName(dnParts[0].replace("cn=", "")); Tools.addLogEntry("private_channel.log", "User name: " + mapUser.get("name")); response.setUserId(mapUser.get("name").toString()); return response; } else { throw new SessionExpiredException(); } } catch (Exception ex) { throw new SessionExpiredException(); } }
额外配置说明
需要提前在JBoss中配置好LDAP安全域,确保认证完成后Principal对象会携带LDAP的dn、名称、角色等属性,和原有Weblogic返回的weblogic.authuser结构对齐即可。
内容的提问来源于stack exchange,提问作者Camilo Valencia
相关产品推荐
相关产品推荐

