I'm using JAAS for authentication and autorization and I don't know how to access the information of the current user..When I use Filter I do something like this : <h:outputText value="#{sessionScope['user'].nom}"></h:outputText>
but with JAAS authentification I cant do the same :\ I want to get user session information to use them in EJB to insert some value into my database.(excuse me for my bad english :\ )
You can find here my login method :
public String loginn() throws Exception{
String message = "";
String navto = "" ;
HttpServletRequest request = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest();
try
{ //Login via the Servlet Context
request.login(username, password);
//Retrieve the Principal
Principal principal = request.getUserPrincipal();
if(principal == null){
throw new Exception("Invalid user/password");
}
//Display a message based on the User role
if
(request.isUserInRole("Administrator" )){
message = "Username : " + principal.getName() + " You are an Administrator, you can really many things up now";
navto = "admin";
}
else
if
(request.isUserInRole("Manager")){
message = "Username : " + principal.getName() + " You are only a Manager, Don't you have a Spreadsheet to be working on??" ;
navto = "manager" ;
}
else
if
(request.isUserInRole("Guest")){
message = "Username : " + principal.getName() + " You're wasting my resources..." ;
navto ="guest";
}
//Add the welcome message to the faces context
FacesContext.getCurrentInstance().addMessage( null , new FacesMessage(FacesMessage.SEVERITY_INFO, message, null ));
return navto;
}
catch
(ServletException e) {
FacesContext.getCurrentInstance().addMessage( null ,new FacesMessage(FacesMessage.SEVERITY_ERROR,"An Error Occured: Login failed" , null ));
e.printStackTrace();
}
return "failure" ;
Thank you for help :)
The user name is available by HttpServletRequest#getRemoteUser()
. See also the javadoc:
getRemoteUser
String getRemoteUser()
Returns the login of the user making this request, if the user has been authenticated, or
null
if the user has not been authenticated. Whether the user name is sent with each subsequent request depends on the browser and type of authentication. Same as the value of the CGI variableREMOTE_USER
.
In EL, the current HttpServletRequest
is available as #{request}
. See also implicit EL objects. You can just access getters on it the same way as with regular javabeans.
#{request.remoteUser}
So e.g. this should do:
<ui:fragment rendered="#{empty request.remoteUser}">
<p>You're not logged in. <h:link outcome="login">Please login</h:link>.</p>
</ui:fragment>
<ui:fragment rendered="#{not empty request.remoteUser}">
<p>Welcome, #{request.remoteUser}!</p>
</ui:fragment>
Equivalently, user roles are available by #{request.isUserInRole(...)}
as follows:
<h:commandButton value="Delete" action="#{bean.delete}"
rendered="#{request.isUserInRole('Administrator')}" />