gpt4 book ai didi

java - 如何限制未登录用户访问某些页面? (JSF 2.0)

转载 作者:行者123 更新时间:2023-11-30 06:35:43 27 4
gpt4 key购买 nike

我正在实现自己的身份验证机制,我想知道我所做的是否正确,如果不正确,我该如何正确执行。

首先解释一下我的身份验证机制是如何工作的:

-我的用户的详细信息在一个名为 Role 的对象中。该对象包含 3 个字段:

电子邮件:字符串

密码:字符串

用户类型:枚举

-当用户访问系统时,将对象Role保存到session中。

我的问题是:如何根据用户(角色)的 userType 字段限制对某些页面的访问?

这就是我所做的,但不起作用。

首先,我有一个托管 bean,用于检查用户是否已登录。

@ManagedBean
@RequestScoped
public class SecurityController {

//Some attributes...


public String redirectNotBuyer() {
Role role = (Role) FacesContext.getCurrentInstance()
.getExternalContext().getSessionMap().get("userRole");
//Checks if user is logged
if (role == null) {
// Please login
//Add message to authentification
return "login.xhtml";
} else if (role != null) {
if (!role.getType().toString().equalsIgnoreCase("BUYER")) {
// Buyer not authorized
return "main.xhtml";
}
}
return null;
}

public String redirectNotSeller() {
Role role = (Role) FacesContext.getCurrentInstance()
.getExternalContext().getSessionMap().get("userRole");
if (role == null) {
// Please login
//Add message to authentification
return "login.xhtml";
} else if (role != null) {
if (!role.getType().toString().equalsIgnoreCase("SELLERs")) {
// Buyer not authorized
return "main.xhtml";
}
}
return null;
}

//Getters, setters...

上述 2 种方法在用户不是买家和卖家的情况下重定向。

所以现在我所做的是在我不希望用户访问的页面中调用其中一种方法,以便用户被重定向到主页。示例:非授权用户进入名为 buyOffer.xhtml 的页面,只有 BUYERS 可以访问该页面:

<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core">


<ui:composition template="WEB-INF/templates/BasicTemplate.xhtml">
<!-- THE REGISTRATION FORM -->
<ui:define name="buyOfferForm">
<h2>Buy offer</h2>
#{SecurityController.redirectNotBuyer()}
</ui:define>
</ui:composition>

</html>

出于某种原因,当我以未登录用户或没有 BUYER 作为 userType 的用户访问此页面时,它不会被重定向到 main.xhtml 页面。这是为什么?

最佳答案

正确的机制是使用 Filter

查看

关于java - 如何限制未登录用户访问某些页面? (JSF 2.0),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5661460/

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