Navigation in restricted area Java EE on Glassfish 4.1

364 Views Asked by At

I am developing a webapp based on Java EE 7 on Glassfish 4.1. I'm new to this environment and I followed some guides to create a JDBC Realm based authentication.

I have only one user role (named USER) that should be able to access all the XHTML pages in the /user folder.

The problem is that when the user logs in, he is redirected to his personal homepage (until now everything is fine), but if I add any link to another page in the same /user folder I still have to login again! Also if I refresh the user's homepage I still have to login.

How is it possible to resolve this problem? Am I missing something?

Here is some code you may find useful to help me:

web.xml

<login-config>
    <auth-method>FORM</auth-method>
    <realm-name>myJdbcRealm</realm-name>
    <form-login-config>
        <form-login-page>/login.xhtml</form-login-page>
        <form-error-page>/loginErr.xhtml</form-error-page>
    </form-login-config>
</login-config>
<security-constraint>
    <web-resource-collection>
        <web-resource-name>Logged User</web-resource-name>
        <description/>
        <url-pattern>/user/*</url-pattern>
    </web-resource-collection>
    <auth-constraint>
        <role-name>USER</role-name>
    </auth-constraint>
</security-constraint>
<security-role>
    <role-name>USER</role-name>
</security-role>

glassfish-web.xml

<glassfish-web-app error-url="">
  <class-loader delegate="true"/>
  <jsp-config>
    <property name="keepgenerated" value="true">
      <description>Keep a copy of the generated servlet class' java code.</description>
    </property>
  </jsp-config>
  <security-role-mapping>
    <role-name>USER</role-name>
    <group-name>USER</group-name>
  </security-role-mapping>
</glassfish-web-app>

login.xhtml

<h:form style="width: 500px; margin: auto; ">
    <p:panel header="Login Form">
        <p:panelGrid columns="2" id="loginGrid">
            <p:outputLabel for="usernameInput" value="Username"/>
            <p:inputText id="usernameInput" value="#{loginBean.username}" 
                         required="false" />
            <p:outputLabel for="passwordInput" value="Password"/>
            <p:password id="passwordInput" value="#{loginBean.password}" 
                        required="false" />
            <p:commandButton value="Login" 
                             action="#{loginBean.login()}" update="loginGrid" />

            <p:messages/>
        </p:panelGrid>
    </p:panel>
</h:form>

LoginBean.java

public String login() {
    FacesContext context = FacesContext.getCurrentInstance();
    HttpServletRequest request = (HttpServletRequest) context.getExternalContext().getRequest();
    try {
        request.login(this.username, this.password);
    } catch (ServletException e) {
        MessageBean.addError("Login failed");
        return NavigationBean.toLogin();
    }
    return "/user/home?faces-redirect=true";
}
0

There are 0 best solutions below