如何在安全上下文中以编程方式验证和创建会话

How to authenticate and create session programmatically in security context

你好,我有一个应用程序使用它自己的实现来进行用户身份验证,方法是在 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());
     }


}

我已经创建了自己的登录模块 ("my-jaas"),当我配置基于表单的身份验证以在 tomcat7 中使用它时,它工作正常。

对于 Servlet 3.0,HttpServletRequest (https://docs.oracle.com/javaee/6/api/javax/servlet/http/HttpServletRequest.html#login(java.lang.String,%20java.lang.String)) 中有一个 login 方法,因此您可以像

一样登录
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());
     }        
}