我正在尝试在像Servlet Request提供的EJB中手动登录。
到目前为止一切顺利。我实现了CallbackHandler:
public class PasswordCallbackHandler implements CallbackHandler {
private String username;
private char[] password;
public PasswordCallbackHandler(String username, char[] password) {
super();
this.username = username;
this.password = password;
}
public void handle(Callback[] callbacks) throws IOException,
UnsupportedCallbackException {
if(callbacks == null) {
return;
}
for (int i = 0; i < callbacks.length; i++) {
if (callbacks[i] instanceof NameCallback) {
NameCallback nc = (NameCallback) callbacks[i];
nc.setName(username);
} else if (callbacks[i] instanceof PasswordCallback) {
PasswordCallback pc = (PasswordCallback) callbacks[i];
pc.setPassword(password);
} else {
throw new UnsupportedCallbackException(callbacks[i],
"Unrecognized Callback");
}
}
}
}
我的代码:
PasswordCallbackHandler handler = new PasswordCallbackHandler("user", "password".toCharArray());
LoginContext context = new LoginContext("realm", handler);
context.login();
主题显示:
Subject:
Principal: user
Principal: Roles(members:ADMIN,USER)
Principal: CallerPrincipal(members:user)
所以登录本身有效。我现在的问题是我在做什么?当我从容器中获取当前主体时,我仍然收到匿名。在JBoss 7.1和Wildfly上测试过。
@Resource
private SessionContext ctx;
Principal callerPrincipal = ctx.getCallerPrincipal();
if(callerPrincipal == null) {
return null;
}
String playerName = callerPrincipal.getName(); // Also after login() it returns anonymous.
我是否误解了这个功能?我需要什么?如何在容器接受我的新用户凭据的情况下进行登录?
当我在过滤器中使用来自Servlet API的login()时,它可以工作。
问候, 米
答案 0 :(得分:0)
主体将是关键。我忽略了doAs()。