gpt4 book ai didi

java - 执行登录后如何管理 j_username 值?

转载 作者:行者123 更新时间:2023-11-30 03:00:57 24 4
gpt4 key购买 nike

我有一个具有 FORM 类型身份验证机制的 Web 应用程序,因此当用户请求 protected 资源时 login.jsp 会拦截该请求,发送 j_usernamej_password 到服务器,用户在该服务器上经过身份验证并被授权获取该特定资源,该资源被发送回客户端。

在以下请求期间,j_username 似乎不会存储在任何地方(请求参数/属性、 session 属性),但您可以通过调用 request.getUserPrincipal().getName() 获取该值.

谁以及如何实际将该值与当前用户耦合? j_username 真正存储在哪里?我的猜测是应用程序服务器是跟踪 [userid,sessionid] 对的服务器,以便在调用 request.getUserPrincipal().getName() 时它可以发回与当前 session 关联的用户 ID。

但这只是猜测,有人能证实/反驳吗?

最佳答案

My guess is that the application server is the one that is keeping track of the pairs [userid,sessionid] so that when request.getUserPrincipal().getName() is invoked it can send back the userid associated with the current session.

servlet specification 中没有指定这一点。然而,基于 FORM 的身份验证的“事实上的”方法确实可以归结为这一点。当您使 HTTP session 失效或过期时,您还可以通过看到用户主体消失来轻松确认这一点。

实际的实现取决于所使用的servlet容器。对于 Tomcat,它存储在 org.apache.catalina.Session 中类(代表内部 HttpSession 外观),它有一个 getPrincipal()Principal 复制到每个 HttpServletRequest 的方法。

发生的地方是 org.apache.catalina.authenticator.AuthenticatorBase ,在 invoke()方法。以下是 Tomcat 10.0.21 source code 的相关摘录:

509         if (cache) {
510 Principal principal = request.getUserPrincipal();
511 if (principal == null) {
512 Session session = request.getSessionInternal(false);
513 if (session != null) {
514 principal = session.getPrincipal();
515 if (principal != null) {
516 if (log.isDebugEnabled()) {
517 log.debug("We have cached auth type " + session.getAuthType() +
518 " for principal " + principal);
519 }
520 request.setAuthType(session.getAuthType());
521 request.setUserPrincipal(principal);
522 }
523 }
524 }
525 }

在第 514 行,您可以看到它是从 HTTP session 中提取的(至少,Tomcat 的内部外观无法通过公共(public) API 访问),在第 521 行,您可以看到它被设置在 Tomcat 的 HTTP 请求的内部外观上,其中反过来可以通过 HttpServletRequest#getUserPrincipal() 公开访问。

如果您好奇如何以及何时调用 Session#setPrincipal(),请前往 register()同一类的方法。

所有其他 servletcontainer 实现都有类似的方法。

另请参阅:

关于java - 执行登录后如何管理 j_username 值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35987707/

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