嗨,我有一个应用程序使用其自己的实现对用户进行身份验证,方法是将用户pojo保存在HttpSession中,并在会话完成后使该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中使用它时,它可以正常工作。
最佳答案
在Servlet 3.0中,login
(https://docs.oracle.com/javaee/6/api/javax/servlet/http/HttpServletRequest.html#login(java.lang.String,%20java.lang.String))中有一个HttpServletRequest
方法,因此您可以像
public void doPost(HttpServletRequest req,HttpServletResponse resp)
throws ServletException,IOException{
String username=req.getParameter("username");
String password=req.getParameter("password");
try{
req.login(username, password);
PrintWriter out= req.getWriter();
out.println("<h2>Welcome</h2>");
} catch(ServletException e ){
PrintWriter out= req.getWriter();
out.println(e.getMessage());
}
}