我不知道,JAAS認證是如何工作的,我只是指的是部分:
我需要把這個內部密碼進入用戶的會話...
如果你想存儲任何對用戶的會話進行後續處理,您可以在您的serlvets代碼中執行此操作
protected final void doGet(HttpServletRequest request,HttpServletResponse response) {
HttpSession session = request.getSession(true); //this returns an existing session, or creates new one
session.setAttribute(key,value);
...
}
這些存儲對象與會話一樣長住。
我做了類似的事情:在servlet-filter中,我檢查會話中的內部密碼,如果它不存在然後生成。但是,用戶登錄後,服務器上有多個相同的請求,則會創建不必要的多個密碼。這個密碼的生成是一件昂貴的事情。
如果內部密碼生成代價高昂,您不應該在servlet過濾類中創建它們,因爲這些過濾器適用於客戶端對服務器所做的任何請求。將pw代的相關代碼移到例如servlet,它執行用戶憑證的實際驗證。如果憑證沒有問題,請創建一次密碼並將其存儲在會話對象中,如上所述。
更新: 因此,假如你有某種HTML表單
<form method="post" action="AuthServlet">
<input type="text" name="username">
<input type="password" name="pwd">
<input type="submit" value="login">
</form>
AuthServlet(注:這個servlet只調用一次,當用戶試圖登錄): 進一步的假設,你需要某種服務器端鉤子的功能,如你所說,你要產生內部密碼
@WebServlet("/AuthServlet")
public class AuthServlet
extends HttpServlet {
// .. lines omitted ..
@Override
protected final void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException,IOException {
// ... lines omitted
// perform authentication with JAAS
try {
LoginContext loginContext = new LoginContext("SomeName", handler);
// starts the actual login
loginContext.login();
//at this point, user is authenticated..normally you would forward him to e.g. a jsp, welcoming the user
//request.getRequestDispatcher("anyJsp.jsp").forward(request, response);
//but you can also forward to another serlvet and perform business logic or else
request.getRequestDispatcher("/ServletName").forward(request, response);
} catch (LoginException e) {
//do sth., if auth fails
}
}
與ServletName
表示該servlet,您可以在doPost()
內執行您的密碼生成,並將此密碼附加到用戶的會話中。 如果您有某種用戶模型,並且用戶擁有角色。您可以查詢角色,並根據角色轉發到servlet。 這更有幫助嗎?
在驗證用戶的同時添加內部密碼生成邏輯就可以了。所以,我需要在JAAS認證模塊中添加這個邏輯。但是,我的問題僅限於純servlet。但是我的問題是:有沒有什麼辦法像web.xml中的任何配置一樣只需要一次登錄servlet即可。 – Azim
請不要顯示如何將值設置爲會話。我認爲從我的問題中可以清楚的看出,我曾與Servlet合作過,並具有關於服務器端技術的基本知識。 但謝謝你的答案。 – Azim
我已經更新了我的答案,我不得不承認,也許我沒有正確理解你,看到我的假設 – lunatikz