我找到了一个代码,该代码应该到达已登录的用户:
InitialContext ic = new InitialContext();
SessionContext sessionContext = (SessionContext)ic.lookup("java:comp/EJBContext");
System.out.println("look up injected sctx: " + sessionContext);
Principal p = sessionContext.getCallerPrincipal();
System.out.println(p.getName());
但它仍然给了我<anonymus>
。这是为什么?我怎样才能达到记录用户的姓名?
答案 0 :(得分:2)
你可以试试这个。
Subject subject = Subject.getSubject(AccessController.getContext());
Set<java.security.Principal> principals = s.getPrincipals();
for (java.security.Principal principal : principals) {
if (principal.getClass() == WLSUserImpl.class) {
return principal.getName();
}
}
WLSUserImpl来自weblogic.security.principal包。这只适用于weblogic。
答案 1 :(得分:1)
你的bean需要被标记为安全的(使用任何规范提供的方法让安全相关的拦截器发挥作用)。
作为第一步,您可以执行以下操作:
@Override
@PermitAll
public String whoAmI() {
return context.getCallerPrincipal().getName();
}
这只是一个允许所有角色访问该方法的示例。 @PermitAll安全注释的存在将指示EJB容器将EJB安全拦截器纳入其中。请查看此文档以获取更多详细信息。为您提供jboss示例 https://docs.jboss.org/author/display/AS72/Securing+EJBs
答案 2 :(得分:1)
您也可以使用mbean API来获取它
import javax.naming.*;
import javax.management.MBeanInfo;
import weblogic.jndi.Environment;
import weblogic.management.runtime.ServerRuntimeMBean;
import weblogic.security.providers.authentication.DefaultAuthenticatorMBean;
import weblogic.management.security.authentication.UserReaderMBean;
import weblogic.management.security.authentication.GroupReaderMBean;
import weblogic.management.MBeanHome;
import weblogic.management.WebLogicMBean;
import weblogic.management.tools.Info;
import weblogic.management.Helper;
import weblogic.management.security.authentication.*;
public class ListUsersAndGroups
{
public static void main(String[] args)
{
MBeanHome home = null;
try
{
Environment env = new Environment();
env.setProviderUrl(“t3://localhost:7001?);
env.setSecurityPrincipal(“weblogic”);
env.setSecurityCredentials(“weblogic”);
Context ctx = env.getInitialContext();
home = (MBeanHome)ctx.lookup(“weblogic.management.adminhome”);
weblogic.management.security.RealmMBean rmBean = home.getActiveDomain().getSecurityConfiguration().getDefaultRealm();
AuthenticationProviderMBean[] authenticationBeans = rmBean.getAuthenticationProviders();
DefaultAuthenticatorMBean defaultAuthenticationMBean = (DefaultAuthenticatorMBean)authenticationBeans[0];
UserReaderMBean userReaderMBean = (UserReaderMBean)defaultAuthenticationMBean;
GroupReaderMBean groupReaderMBean = (GroupReaderMBean)defaultAuthenticationMBean;
String userCurName = userReaderMBean.listUsers(“*”, 100);
while (userReaderMBean.haveCurrent(userCurName) )
{
String user = userReaderMBean.getCurrentName(userCurName);
System.out.println(“\n User: ” + user);
userReaderMBean.advance(userCurName);
}
String cursorName = groupReaderMBean.listGroups(“*”, 100);
while (groupReaderMBean.haveCurrent(cursorName) )
{
String group = groupReaderMBean.getCurrentName(cursorName);
System.out.println(“\n Group: ” + group);
groupReaderMBean.advance(cursorName);
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
}