JAAS, doing login from outside the container
I have an application with JAAS and i need do an exter开发者_如何学运维nal login from the legacy, so i wrote a servlet with this code bellow, it works fine, but when i do another submit the JAAS tries authenticate again and has failure, and the user is redirected to login page.
here is doPost method:
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
NfWebCallbackHandler callbackHandler = new NfWebCallbackHandler(req);
LoginContext loginContext = null;
boolean loginSuccess = true;
try {
loginContext = new LoginContext("MyLoginContext", callbackHandler);
loginContext.login();
} catch (LoginException e) {
loginSuccess = false;
RequestDispatcher dispatcher = req
.getRequestDispatcher("/login.jsf");
dispatcher.forward(req, resp);
e.printStackTrace();
}
if (loginSuccess) {
RequestDispatcher dispatcher = req.getRequestDispatcher(req
.getParameter("targetUrl"));
dispatcher.forward(req, resp);
}
}
any idea is welcome! thanks!
When you use a JAAS Login Module outside the purview of the container (or at least in a mannaer unrecognizable to the container), the container will not be aware of the fact that the Subject and the set of Principals (associated with the subject) are to be stored and managed by the container.
When you use one of the container-managed authentication schemes, the container actually stores the subject in the Session implementation class (at least in Tomcat 6, this is true), in a manner that is completely opaque to the developer; using getAttribute()
on the session object will never return the Subject, and neither can use setAttribute()
to override the Subject. When needed, the subject is retrieved from this session field and used for various purposes by the container; for instance, when you invoke getUserPrincipal()
or getRemoteUser()
on the HttpServletRequest
object, the Principal associated with the Subject is actually used to return the result.
If you need to get the container to do all this heavy-lifting for you, then you need to use the JAAS Login module in conjunction with a container managed authentication scheme. If you do not want to go this way, then you'll need to "remember" the Subject and the Principals for the duration of the session; not to forget, all of this has to be done in a secure manner.
I forgot to register my solution for this case, i used this class:
org.jboss.web.tomcat.security.login.WebAuthentication
i wrote something like that:
WebAuthentication webAuthentication = new WebAuthentication();
req.getSession().setAttribute("webAuthentication", webAuthentication);
I dont remember where i found this, but was very useful!
Thanx Vineet Reynolds, the only one who tried to help me hehehe
精彩评论