嗨,我有一个应用程序使用自己的实现进行用户身份验证,通过在 HttpSession 中保存用户 pojo 并在会话完成时使该 HttpSession 对象无效,但我想要做的是使用安全上下文来验证用户. 假设我有 servlet AuthenticateUserServlet:
public void doPost(HttpServletRequest req,HttpServletResponse resp)
throws ServletException,IOException{
String username=req.getParameter("username");
String password=req.getParameter("password");
if(Authenticator.check(username,password)){
HttpSession session=req.getSession(true);
session.setAttribute("user",Authenticator.getUser(username));
PrintWriter out= req.getWriter();
out.println("<h2>Welcome</h2>");
}else{
PrintWriter out= req.getWriter();
out.println("<h2>the password or username are incorrect</h2>");
}
}
上面的代码不会给我安全上下文的力量所以我不想要的是当我检查用户是否可以登录时以某种方式告诉这个用户可以访问的安全上下文是他在我里面的角色AuthenticateUserServlet:
public void doPost(HttpServletRequest req,HttpServletResponse resp)
throws ServletException,IOException{
String username=req.getParameter("username");
String password=req.getParameter("password");
LoginContext lc = new LoginContext("my-jaas",new MyCallbackHandler(username,password));
try{
lc.login();
//notice i have not save any thing in the HTTPSeession
//i want my container to remember this user like what happens in the
// form based authentication where nothing gets saved in the httpSession
// but the user keeps logged in(cartalina uses a session object not httpsession for that)
PrintWriter out= req.getWriter();
out.println("<h2>Welcome</h2>");
}
catch(LoginException e ){
PrintWriter out= req.getWriter();
out.println(e.getMessage());
}
}
我已经创建了自己的 LoginModule(“my-jaas”),当我将基于表单的身份验证配置为在 tomcat7 中使用它时,它工作正常。