登录JAAS验证模块的weblogic应用,有两种方法
一.直接使用weblogic本身的api进行实现
import java.io.IOException; import javax.security.auth.Subject; import javax.security.auth.callback.CallbackHandler; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import weblogic.security.SimpleCallbackHandler; public class LoginService extends HttpServlet { protected void doGet(HttpServletRequest arg0, HttpServletResponse arg1) throws ServletException, IOException { this.doPost(arg0, arg1); } protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { String userName = req.getParameter("userName"); String password = req.getParameter("password"); //登录成功后所要访问的url String url = req.getParameter("url"); try { CallbackHandler handler = new SimpleCallbackHandler(userName, password); Subject subject = weblogic.security.services.Authentication.login(handler); weblogic.servlet.security.ServletAuthentication.runAs(subject, req); res.sendRedirect(req.getContextPath() + "/" + url); } catch(Exception e) { e.printStackTrace(); } } }
采用这种方式,weblogic会调用JAAS LoginModule的的login,commit操作
二.使用httpclient框架
HttpClient client = new HttpClient(); client.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY); //登录成功后需要访问的url GetMethod authget = new GetMethod(url); try { client.executeMethod(authget); } catch(HttpException httpe) { httpe.printStackTrace(); } catch(IOException ioe) { ioe.printStackTrace(); } finally { authget.releaseConnection(); } NameValuePair[] data = new NameValuePair[2]; data[0] = new NameValuePair(J_USERNAME, user.getName()); data[1] = new NameValuePair(J_PASSWORD, user.getPassword()); /** * 登录页面提交,获取cookie即sessionid * 由于servlet规范中默认session的cookiename属性为:JSESSIONID * 如果本域采用默认JSESSIONID作为cookie的name,则与请求域cookie发生冲突,导致请求域session失效,重新登录 * 可在weblogic.xml中配置session的cookiename属性 * <session-descriptor> * <session-param> * <param-name>CookieName</param-name> * <param-value>LOGIN_SESSIONID</param-value> * </session-param> * </session-descriptor> */ //JAAS验证servlet,如:REDIRECT_LOGIN=/j_security_check PostMethod authpost = new PostMethod(context + REDIRECT_LOGIN); authpost.setRequestBody(data); try { client.executeMethod(authpost); org.apache.commons.httpclient.Cookie[] cookies = client.getState().getCookies(); for(int i = 0; i < cookies.length; i++) { javax.servlet.http.Cookie cookie = new javax.servlet.http.Cookie(cookies[i].getName(), cookies[i].getValue()); /** * response添加登录成功后产生的cookie */ response.addCookie(cookie); } /** * 重定向至目标地址 */ response.sendRedirect(forword); } catch(HttpException httpe) { httpe.printStackTrace(); return; } catch(IOException ioe) { ioe.printStackTrace(); return; } finally { authpost.releaseConnection(); }