`

jee6 学习笔记 11: Secure JSF2 web app with JAAS and JBoss7.1

阅读更多

This article describes how to secure a JSF2 web application with Java Authentication and Authorization Service (JAAS) and JBoss7.1. It uses a "FORM" authentication method. Users and roles are stored in a mysql database. We also want to use JSF2 tags and Primefaces tags as well, not a plain html form.

 

1. Introduction

 

Briefly, JAAS would be provided by the container, ie, JBoss7.1 in our example. In order to handle the login form by our own application code, we need to activate the login process in the login bean, by calling the JAAS login module api. JEE6/Servelet 3.0 provides JAAS api in the HttpServeltRequest object, as follows:

 

request.login(username, password);
request.logout();

 

So, this results in the login backing bean to get the reference of the HttpServletRequest object and call the login(username, password). Here the username and password would be the form parameters user submitted. This is nothing new.

 

 

2. Configurations

 

JAAS is more about configurations. We need to configure a security domain in JBoss7.1 and secure resources(URLs) in web.xml of our web application. We also need to add a jboss-web.xml to hook up our configured security domain in JBoss7.1 to our web application configurations. In the database, we have two tables "user" and "role". The "user" table would hold username and password etc. The "role" table would hold mappings of "username" to the roles we defined for the web application.

 

2.1 Configure a JBoss7.1 secuirty domain

 

This involves adding our security domain to the "standalone.xml " for the standalone server. Open this file and search for "<security-domains>". Under this section, adding our own security domain configuration:

 

<security-domain name="jwSecureTest">
   <authentication>
      <login-module code="Database" flag="required">
           <module-option name="dsJndiName" value="java:/ProJee6DS"/>
           <module-option name="principalsQuery" 
                       value="select password from user where username=?"/>
           <module-option name="rolesQuery" 
                       value="select role, 'Roles' from role where username=?"/>
       </login-module>
   </authentication>
</security-domain>

 

Our secrity domain is going to use datasource  "java:/ProJee6DS"(u have to configure it. same to the datasource web app uses) to authenticate users. The "principalsQuery" would select user password from table "user" and "rolesQuery" would select the roles that the logged in user would have. Once user logged in successfully, these data would be saved in the login context for the user (-; this is my guess.

 

2.2 Database tables configuration

 

So lets add those "user" and "role" tables in database. We have two roles "admin" and "usr".

 

create table user (
  id int, 
  username varchar(20) not null, 
  password varchar(10) not null, 
  email varchar(100)
);

create table role (
  username varchar(20) not null,
  role varchar(10) not null
);

insert into user values (1, 'j2ee', 'j2ee', null);
insert into user values (2, 'jason', 'jason', 'jason@123.com');

insert into role values ('j2ee', 'admin');
insert into role values ('jason', 'usr');

 

 

2.3 Configure our web application web.xml

 

In "web.xml", we have to define the pages/urls to secure. For example, it needs "admin" role to access. We also define the access error page to handle the http "403" error. Note, we need to define it's a Servlet 3.0 web application. Since the JAAS api only available after 3.0

 

Here's the relevant section:

 

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
		xmlns="http://java.sun.com/xml/ns/javaee" 
                xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
		xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="ProJee6" version="3.0">

<!-- except for login.jsf, every page requires at lease role "usr", ie, u need to login -->
	<security-constraint>  
		<web-resource-collection>  
	    	<web-resource-name>login protected resources</web-resource-name>  
			<url-pattern>/home.jsf</url-pattern>
	    	<url-pattern>/tst/*</url-pattern>  
	    </web-resource-collection>  
	    <auth-constraint>  
	    	<role-name>usr</role-name> 
                <role-name>admin</role-name>
	    </auth-constraint>  
</security-constraint>

<!-- /student/* only accessible to users with role "admin" -->
 <security-constraint>

     <web-resource-collection>
            <web-resource-name>protected resources</web-resource-name>
            <url-pattern>/student/*</url-pattern>
	    <http-method>GET</http-method>
	    <http-method>POST</http-method>
      </web-resource-collection>
 
      <auth-constraint>
            <!-- restrict role "usr" to access this page 
            <role-name>usr</role-name>
            -->
            <role-name>admin</role-name>
      </auth-constraint>
        
         <!-- uncomment to configure ssl: need to configure https connector.
	 <user-data-constraint>
	     <transport-guarantee>CONFIDENTIAL</transport-guarantee>    
	 </user-data-constraint>
	 -->
</security-constraint>

<!-- define auth method "FORM" and our login page -->
<login-config>
    <auth-method>FORM</auth-method>
    <form-login-config>
        <form-login-page>/login.jsf</form-login-page>
        <form-error-page>/login.jsf</form-error-page>
    </form-login-config>
</login-config>

......

<!-- define our http 403 error page -->
<error-page>
    <error-code>403</error-code>
    <location>/noAccess.jsf</location>
</error-page>

 

 

2.4 Adding jboss-web.xml

 

This descriptor is used to hook up the security domain we defined in JBoss "jwSecureTest" to our application. It needs to be packaged into "WEB-INF/jboss-web.xml":

 

<?xml version="1.0" encoding="UTF-8"?>
<jboss-web>
	<security-domain>java:/jaas/jwSecureTest</security-domain>   
</jboss-web>

 

 

2.5. Implement our login page and its backing bean

 

We dont need to change our login page at all. Here's it anyway:

 

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
	"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:h="http://java.sun.com/jsf/html"
      xmlns:f="http://java.sun.com/jsf/core"
      xmlns:ui="http://java.sun.com/jsf/facelets"
      xmlns:p="http://primefaces.org/ui"> 
    
<h:head>
	<title>login page</title>
</h:head>

<h:body>
  <p:panel header="Login Panel" style="width:50%">
  <h:messages/>
     <h:form>
     <h:panelGrid columns="2">
         <h:outputLabel value="#{msgs.username}: "/> 
         <h:inputText id="nameId" value="#{loginBean.user.username}" 
              required="true" requiredMessage="username is required"/>
   
         <h:outputLabel value="${msgs.password}: "/> 
         <h:inputSecret id="passId" value="#{loginBean.user.password}" 
              required="true" requiredMessage="password is required"/>
   
         <!-- call action bean method login() -->
         <h:panelGroup>
            <h:commandButton type="submit" 
                     value="#{msgs.login}" action="#{loginBean.login}"/>
            
           <p:spacer width="20"/>

            <h:outputText value="are you #{flash.USER.username}?" 
                     rendered="#{not empty flash.USER.username}"/>
         </h:panelGroup>
      </h:panelGrid>
      </h:form>
  </p:panel>
</h:body>
</html>

 

 

But we need to change the backing bean to start the JAAS login process by calling its api:

 

package com.jxee.action;

import java.io.Serializable;
import java.security.Principal;

import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.faces.context.Flash;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;

import com.jxee.ejb.usr.UserDAO;
import com.jxee.model.User;

/**
 * Backing bean for login.xhtml
 * @ManagedBean used to replace the declaration of the bean in faces-config.xml
 * <br/>you can give it a name, like @ManagedBean("myBean"), otherwise, it defaults
 * to the class name with the first character lower cased, eg, "loginBean". So in this
 * example, it can be accessed in JSF pages like this: #{loginBean.login}
 */
@ManagedBean
@SuppressWarnings("all")
public class LoginBean implements Serializable {
  
  private static final Logger log = Logger.getLogger(LoginBean.class);
  
  // inject EJB UserDAO for accessing database
  // @EJB private UserDAO userDao;  // this is not used when using JAAS
  
  private User user = new User();
  
  public User getUser() { return this.user; }
  public void setUser(User user) { this.user = user; }
  
  /**
   * jaas login
   */
  public String login() {
      ExternalContext cntxt = FacesContext.getCurrentInstance().getExternalContext();
      HttpServletRequest req = (HttpServletRequest) cntxt.getRequest();

      try {
          req.login(this.user.getUsername(), this.user.getPassword());
          log.info(">>> user logged in: " + this.user.getUsername());
          return "/home.jsf";
      }
      catch(Exception e) {
          log.error(String.format("login failed. user: %s, due to: %s ", 
                              this.user.getUsername(),e.getMessage()));
      }
    
      return "/login.jsf";
  }
  
  /**
   * jaas logout
   */
  public String logout() {

     ExternalContext cntxt = FacesContext.getCurrentInstance().getExternalContext();
     HttpServletRequest req = (HttpServletRequest) cntxt.getRequest();
     Principal pp = req.getUserPrincipal();
     String aname = pp.getName();

     try {
        req.logout();
        log.info(">>> user logged out: " + aname);
     }
     catch(Exception e) {
        log.error(String.format("Error logout user %s, due to: %s", 
                              aname, e.getMessage()));
     }

     return "/login.jsf?faces-redirect=true";
  }

  ......

}

 

The http 403 error page "/noAccess.xhtml":

 

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

	<ui:define name="title">home</ui:define>
	
	<ui:define name="content">
	    <p:panel header="Access Error" style="width:60%;border:0px">
	        <b>#{msgs.noAccess}</b>
	    </p:panel>
    </ui:define>
</ui:composition>

 

 

With these configurations, onle users with "admin" role can access the pages "/student/*". This include pages "/student/studentSearch.js" and "student/studentDetails.jsf". That is, according to our database data, user "jason" has no access to these pages.

 

Next, i'll take a look at prorgammatic approach of JAAS to secure application components. JEE6 provides annotations to test if calling client is in a role to secure the calling of a method.

 

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics