gpt4 book ai didi

java - 如何在安全上下文中以编程方式进行身份验证和创建 session

转载 作者:行者123 更新时间:2023-11-30 02:44:25 25 4
gpt4 key购买 nike

嗨,我有一个应用程序,它使用自己的实现来进行用户身份验证,方法是在 HttpSession 中保存用户 pojo 并在 session 完成时使该 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 中,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());
}
}

关于java - 如何在安全上下文中以编程方式进行身份验证和创建 session ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40628541/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com