How to restrict access to not logged users to certain pages? (JSF 2.0)
I am implementing my own authentication mechanism and i want to know if what i am doing is correct and if not how can i do it correctly.
First ill explain how my authentication mechanism works:
-The details of my users are inside an object called Role. This object contains 3 fields:
email:String
password:String
userType:Enum
-When the user accesses the system, the object Role is saved into the session.
My question is: How can i restrict the access to certain pages to users(Role) based in their userType
fields?
This is what i do but doesnt work.
First i have a managed bean that checks if the usser is logged.
@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...
Those 2 methods above redirect in case the user is not a Buyer and in case the user is not a seller.
So now what i do is in the page that i dont want the user to go i call one of those methods, so the user gets redirected to the main page. Example: A non authorized user enters 开发者_JS百科a page that is called buyOffer.xhtml, that only BUYERS can access:
<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>
For some reason when i go to this page with a not logged in user or a user that is not has BUYER as userType, it does not get redirected to the main.xhtml page. Why is that?
The proper mechanism would be the use of Filter
.
See
- basic-security-in-jsf
精彩评论