gpt4 book ai didi

jakarta-ee - 用户登录Web应用程序时如何实现 "Stay Logged In"

转载 作者:行者123 更新时间:2023-12-03 05:53:12 26 4
gpt4 key购买 nike

在大多数网站上,当用户要提供用户名和密码登录系统时,都会有一个复选框,例如“保持登录状态”。如果您选中该框,您将在同一 Web 浏览器的所有 session 中保持登录状态。如何在 Java EE 中实现相同的功能?

我正在使用基于 FORM 的容器管理身份验证和 JSF 登录页面。

<security-constraint>
<display-name>Student</display-name>
<web-resource-collection>
<web-resource-name>CentralFeed</web-resource-name>
<description/>
<url-pattern>/CentralFeed.jsf</url-pattern>
</web-resource-collection>
<auth-constraint>
<description/>
<role-name>STUDENT</role-name>
<role-name>ADMINISTRATOR</role-name>
</auth-constraint>
</security-constraint>
<login-config>
<auth-method>FORM</auth-method>
<realm-name>jdbc-realm-scholar</realm-name>
<form-login-config>
<form-login-page>/index.jsf</form-login-page>
<form-error-page>/LoginError.jsf</form-error-page>
</form-login-config>
</login-config>
<security-role>
<description>Admin who has ultimate power over everything</description>
<role-name>ADMINISTRATOR</role-name>
</security-role>
<security-role>
<description>Participants of the social networking Bridgeye.com</description>
<role-name>STUDENT</role-name>
</security-role>

最佳答案

Java EE 8 及更高版本

如果您使用的是 Java EE 8 或更高版本,请输入 @RememberMe定制HttpAuthenticationMechanism以及 RememberMeIdentityStore .

@ApplicationScoped
@AutoApplySession
@RememberMe
public class CustomAuthenticationMechanism implements HttpAuthenticationMechanism {

@Inject
private IdentityStore identityStore;

@Override
public AuthenticationStatus validateRequest(HttpServletRequest request, HttpServletResponse response, HttpMessageContext context) {
Credential credential = context.getAuthParameters().getCredential();

if (credential != null) {
return context.notifyContainerAboutLogin(identityStore.validate(credential));
}
else {
return context.doNothing();
}
}
}
public class CustomIdentityStore implements RememberMeIdentityStore {

@Inject
private UserService userService; // This is your own EJB.

@Inject
private LoginTokenService loginTokenService; // This is your own EJB.

@Override
public CredentialValidationResult validate(RememberMeCredential credential) {
Optional<User> user = userService.findByLoginToken(credential.getToken());
if (user.isPresent()) {
return new CredentialValidationResult(new CallerPrincipal(user.getEmail()));
}
else {
return CredentialValidationResult.INVALID_RESULT;
}
}

@Override
public String generateLoginToken(CallerPrincipal callerPrincipal, Set<String> groups) {
return loginTokenService.generateLoginToken(callerPrincipal.getName());
}

@Override
public void removeLoginToken(String token) {
loginTokenService.removeLoginToken(token);
}

}

您可以找到a real world exampleJava EE Kickoff Application .

<小时/>

Java EE 6/7

如果您使用的是 Java EE 6 或 7,请自行开发一个长期存在的 cookie 来跟踪唯一客户端并使用 Servlet 3.0 API 提供的编程登录 HttpServletRequest#login()当用户未登录但 cookie 存在时。

如果您创建另一个数据库表,其中 java.util.UUID 值为 PK,相关用户的 ID 为 FK,这是最容易实现的。

假设以下登录表单:

<form action="login" method="post">
<input type="text" name="username" />
<input type="password" name="password" />
<input type="checkbox" name="remember" value="true" />
<input type="submit" />
</form>

以及映射到 /loginServletdoPost() 方法中的以下内容:

String username = request.getParameter("username");
String password = hash(request.getParameter("password"));
boolean remember = "true".equals(request.getParameter("remember"));
User user = userService.find(username, password);

if (user != null) {
request.login(user.getUsername(), user.getPassword()); // Password should already be the hashed variant.
request.getSession().setAttribute("user", user);

if (remember) {
String uuid = UUID.randomUUID().toString();
rememberMeService.save(uuid, user);
addCookie(response, COOKIE_NAME, uuid, COOKIE_AGE);
} else {
rememberMeService.delete(user);
removeCookie(response, COOKIE_NAME);
}
}

(COOKIE_NAME 应该是唯一的 Cookie 名称,例如 "remember"COOKIE_AGE 应该是以秒为单位的年龄,例如 2592000 持续 30 天)

以下是映射到受限页面的 FilterdoFilter() 方法:

HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) res;
User user = request.getSession().getAttribute("user");

if (user == null) {
String uuid = getCookieValue(request, COOKIE_NAME);

if (uuid != null) {
user = rememberMeService.find(uuid);

if (user != null) {
request.login(user.getUsername(), user.getPassword());
request.getSession().setAttribute("user", user); // Login.
addCookie(response, COOKIE_NAME, uuid, COOKIE_AGE); // Extends age.
} else {
removeCookie(response, COOKIE_NAME);
}
}
}

if (user == null) {
response.sendRedirect("login");
} else {
chain.doFilter(req, res);
}

与这些 cookie 辅助方法结合使用(可惜 Servlet API 中缺少它们):

public static String getCookieValue(HttpServletRequest request, String name) {
Cookie[] cookies = request.getCookies();
if (cookies != null) {
for (Cookie cookie : cookies) {
if (name.equals(cookie.getName())) {
return cookie.getValue();
}
}
}
return null;
}

public static void addCookie(HttpServletResponse response, String name, String value, int maxAge) {
Cookie cookie = new Cookie(name, value);
cookie.setPath("/");
cookie.setMaxAge(maxAge);
response.addCookie(cookie);
}

public static void removeCookie(HttpServletResponse response, String name) {
addCookie(response, name, null, 0);
}

虽然 UUID 极难暴力破解,但您可以为用户提供一个选项,将“记住”选项锁定到用户的 IP 地址 (request.getRemoteAddr()) 并将其存储/比较在数据库中。这使得它更加健壮一点。此外,在数据库中存储“到期日期”也会很有用。

每当用户更改密码时替换 UUID 值也是一个好习惯。

<小时/>

Java EE 5 或更低版本

请升级。

关于jakarta-ee - 用户登录Web应用程序时如何实现 "Stay Logged In",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5082846/

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