Subjectを取得するには、LoginModuleとValveの組み合わせを使用できます。認証が始まる前にバルブが呼び出されたという事実が私たちをここに助けてくれます。バルブが呼び出されると、セッションはThreadLocalに入れられます(JBOSSがThreadLocalに要求を保存する方法と同様)、LoginModule.commit()が呼び出されたときにサブジェクトをセッションに保存します。 jarファイルに以下のクラスのために、このアドオンコンパイルされたコードを設定して、$ CATALINA_BASE/confに/ server.xmlの
/$ CATALINA_BASE/libに
package my.test;
import java.io.IOException;
import java.util.Map;
import javax.security.auth.Subject;
import javax.security.auth.callback.CallbackHandler;
import javax.security.auth.login.LoginException;
import javax.security.auth.spi.LoginModule;
import javax.servlet.ServletException;
import org.apache.catalina.Session;
import org.apache.catalina.connector.Request;
import org.apache.catalina.connector.Response;
import org.apache.catalina.valves.ValveBase;
/**
* Use following class to retrieve subject in your HTTPServlet when using Tomcat.
*/
public class ContainerServices extends ValveBase implements LoginModule {
// Key to revtieve subject from session.
public static final String SUBJECT_KEY =
"javax.security.auth.Subject.container";
/**
* Session for current thread.
*/
static InheritableThreadLocal<Session> sessionHolder =
new InheritableThreadLocal<Session>();
// JAAS Subject being authenticated.
private Subject subject;
// Invoke the value.
public void invoke(Request request, Response response) throws IOException,
ServletException {
sessionHolder.set(request.getSessionInternal(true));
try {
// Next in the invocation chain
getNext().invoke(request, response);
} finally {
sessionHolder.remove();
}
}
// Initialize the login module
public void initialize(Subject subject, CallbackHandler callbackHandler,
Map<String, ?> sharedState, Map<String, ?> options) {
this.subject = subject;
}
// Store subject to session.
public boolean commit() throws LoginException {
Session session = sessionHolder.get();
if (session != null) {
session.getSession().setAttribute(ContainerServices.SUBJECT_KEY, subject);
}
return true;
}
// not used
public boolean abort() throws LoginException {
return false;
}
// not used
public boolean login() throws LoginException {
return true;
}
// not used
public boolean logout() throws LoginException {
return true;
}
}
の下に配置する
は、要素の子としてバルブの設定を次のように追加します。 jaas.configファイルで
<Valve className="my.test.ContainerServices" />
のLoginModuleと同じクラスを追加します。今
DummyAppLogin {
my.test.ContainerServices required debug=true;
my.test.DummyAppLoginModule required debug=true;
};
はログイン後、認証されたSubjectは以下のものを使用して取得することができます。
session.getAttribute(ContainerServices.SUBJECT_KEY);
、あなたが(サーブレットAPIの 'HttpServletRequest.getUserPrincipalを試すことができ、自分のレルムは、Webアプリケーションのために使用されていることを確認してください)' –
は、私はそれを知っていたし、それが動作しますが、私はまた、 – sasaman85