如何在EL中访问JAAS用户

时间:2014-09-08 10:22:01

标签: jsf el jaas

我使用JAAS进行身份验证和自动操作,但我不知道如何访问当前用户的信息。当我使用Filter时,我会执行以下操作:<h:outputText value="#{sessionScope['user'].nom}"></h:outputText>但是JAAS身份验证我不能这样做:\我想获取用户会话信息,以便在EJB中使用它们将一些值插入我的数据库。(对不起,我的英文不好:\) 你可以在这里找到我的登录方法:

 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" ;

感谢您的帮助:)

2 个答案:

答案 0 :(得分:2)

用户名由HttpServletRequest#getRemoteUser()提供。另请参阅javadoc

  

getRemoteUser

     

String getRemoteUser()

     

如果用户已通过身份验证,则返回发出此请求的用户的登录信息;如果用户尚未通过身份验证,则返回null。是否随每个后续请求一起发送用户名取决于浏览器和身份验证类型。与CGI变量REMOTE_USER的值相同。

在EL中,当前HttpServletRequest可用作#{request}。另见implicit EL objects。您可以像使用常规javabeans一样访问它上面的getter。

#{request.remoteUser}

所以,例如这应该做:

<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>

同等地,#{request.isUserInRole(...)}可以使用用户角色,如下所示:

<h:commandButton value="Delete" action="#{bean.delete}" 
    rendered="#{request.isUserInRole('Administrator')}" />

答案 1 :(得分:0)

将它放在您的JSF页面中:request.getUserPrincipal()